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

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red;
        let green;
        let blue;
        if (code >= 232) {
          red = ((code - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code -= 16;
          const remainder = code % 36;
          red = Math.floor(code / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
      enumerable: false
    }
  });
  return styles;
}
var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
var init_ansi_styles = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
    ANSI_BACKGROUND_OFFSET = 10;
    wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
    wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
    wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
    styles = {
      modifier: {
        reset: [0, 0],
        // 21 isn't widely supported and 22 does the same thing
        bold: [1, 22],
        dim: [2, 22],
        italic: [3, 23],
        underline: [4, 24],
        overline: [53, 55],
        inverse: [7, 27],
        hidden: [8, 28],
        strikethrough: [9, 29]
      },
      color: {
        black: [30, 39],
        red: [31, 39],
        green: [32, 39],
        yellow: [33, 39],
        blue: [34, 39],
        magenta: [35, 39],
        cyan: [36, 39],
        white: [37, 39],
        // Bright color
        blackBright: [90, 39],
        gray: [90, 39],
        // Alias of `blackBright`
        grey: [90, 39],
        // Alias of `blackBright`
        redBright: [91, 39],
        greenBright: [92, 39],
        yellowBright: [93, 39],
        blueBright: [94, 39],
        magentaBright: [95, 39],
        cyanBright: [96, 39],
        whiteBright: [97, 39]
      },
      bgColor: {
        bgBlack: [40, 49],
        bgRed: [41, 49],
        bgGreen: [42, 49],
        bgYellow: [43, 49],
        bgBlue: [44, 49],
        bgMagenta: [45, 49],
        bgCyan: [46, 49],
        bgWhite: [47, 49],
        // Bright color
        bgBlackBright: [100, 49],
        bgGray: [100, 49],
        // Alias of `bgBlackBright`
        bgGrey: [100, 49],
        // Alias of `bgBlackBright`
        bgRedBright: [101, 49],
        bgGreenBright: [102, 49],
        bgYellowBright: [103, 49],
        bgBlueBright: [104, 49],
        bgMagentaBright: [105, 49],
        bgCyanBright: [106, 49],
        bgWhiteBright: [107, 49]
      }
    };
    modifierNames = Object.keys(styles.modifier);
    foregroundColorNames = Object.keys(styles.color);
    backgroundColorNames = Object.keys(styles.bgColor);
    colorNames = [...foregroundColorNames, ...backgroundColorNames];
    ansiStyles = assembleStyles();
    ansi_styles_default = ansiStyles;
  }
});

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

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

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

// ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json
var require_package = __commonJS({
  "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json"(exports2, module2) {
    module2.exports = {
      name: "dotenv",
      version: "16.5.0",
      description: "Loads environment variables from .env file",
      main: "lib/main.js",
      types: "lib/main.d.ts",
      exports: {
        ".": {
          types: "./lib/main.d.ts",
          require: "./lib/main.js",
          default: "./lib/main.js"
        },
        "./config": "./config.js",
        "./config.js": "./config.js",
        "./lib/env-options": "./lib/env-options.js",
        "./lib/env-options.js": "./lib/env-options.js",
        "./lib/cli-options": "./lib/cli-options.js",
        "./lib/cli-options.js": "./lib/cli-options.js",
        "./package.json": "./package.json"
      },
      scripts: {
        "dts-check": "tsc --project tests/types/tsconfig.json",
        lint: "standard",
        pretest: "npm run lint && npm run dts-check",
        test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
        "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
        prerelease: "npm test",
        release: "standard-version"
      },
      repository: {
        type: "git",
        url: "git://github.com/motdotla/dotenv.git"
      },
      homepage: "https://github.com/motdotla/dotenv#readme",
      funding: "https://dotenvx.com",
      keywords: [
        "dotenv",
        "env",
        ".env",
        "environment",
        "variables",
        "config",
        "settings"
      ],
      readmeFilename: "README.md",
      license: "BSD-2-Clause",
      devDependencies: {
        "@types/node": "^18.11.3",
        decache: "^4.6.2",
        sinon: "^14.0.1",
        standard: "^17.0.0",
        "standard-version": "^9.5.0",
        tap: "^19.2.0",
        typescript: "^4.8.4"
      },
      engines: {
        node: ">=12"
      },
      browser: {
        fs: false
      }
    };
  }
});

// ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
  "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js"(exports2, module2) {
    var fs7 = require("fs");
    var path4 = require("path");
    var os3 = require("os");
    var crypto7 = require("crypto");
    var packageJson = require_package();
    var version3 = packageJson.version;
    var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
    function parse4(src) {
      const obj = {};
      let lines = src.toString();
      lines = lines.replace(/\r\n?/mg, "\n");
      let match2;
      while ((match2 = LINE.exec(lines)) != null) {
        const key = match2[1];
        let value = match2[2] || "";
        value = value.trim();
        const maybeQuote = value[0];
        value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
        if (maybeQuote === '"') {
          value = value.replace(/\\n/g, "\n");
          value = value.replace(/\\r/g, "\r");
        }
        obj[key] = value;
      }
      return obj;
    }
    function _parseVault(options) {
      const vaultPath = _vaultPath(options);
      const result = DotenvModule.configDotenv({ path: vaultPath });
      if (!result.parsed) {
        const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
        err2.code = "MISSING_DATA";
        throw err2;
      }
      const keys = _dotenvKey(options).split(",");
      const length = keys.length;
      let decrypted;
      for (let i4 = 0; i4 < length; i4++) {
        try {
          const key = keys[i4].trim();
          const attrs = _instructions(result, key);
          decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
          break;
        } catch (error2) {
          if (i4 + 1 >= length) {
            throw error2;
          }
        }
      }
      return DotenvModule.parse(decrypted);
    }
    function _warn(message) {
      console.log(`[dotenv@${version3}][WARN] ${message}`);
    }
    function _debug(message) {
      console.log(`[dotenv@${version3}][DEBUG] ${message}`);
    }
    function _dotenvKey(options) {
      if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
        return options.DOTENV_KEY;
      }
      if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
        return process.env.DOTENV_KEY;
      }
      return "";
    }
    function _instructions(result, dotenvKey) {
      let uri;
      try {
        uri = new URL(dotenvKey);
      } catch (error2) {
        if (error2.code === "ERR_INVALID_URL") {
          const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        }
        throw error2;
      }
      const key = uri.password;
      if (!key) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environment = uri.searchParams.get("environment");
      if (!environment) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
      const ciphertext = result.parsed[environmentKey];
      if (!ciphertext) {
        const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
        err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
        throw err2;
      }
      return { ciphertext, key };
    }
    function _vaultPath(options) {
      let possibleVaultPath = null;
      if (options && options.path && options.path.length > 0) {
        if (Array.isArray(options.path)) {
          for (const filepath of options.path) {
            if (fs7.existsSync(filepath)) {
              possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
            }
          }
        } else {
          possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
        }
      } else {
        possibleVaultPath = path4.resolve(process.cwd(), ".env.vault");
      }
      if (fs7.existsSync(possibleVaultPath)) {
        return possibleVaultPath;
      }
      return null;
    }
    function _resolveHome(envPath) {
      return envPath[0] === "~" ? path4.join(os3.homedir(), envPath.slice(1)) : envPath;
    }
    function _configVault(options) {
      const debug = Boolean(options && options.debug);
      if (debug) {
        _debug("Loading env from encrypted .env.vault");
      }
      const parsed = DotenvModule._parseVault(options);
      let processEnv = process.env;
      if (options && options.processEnv != null) {
        processEnv = options.processEnv;
      }
      DotenvModule.populate(processEnv, parsed, options);
      return { parsed };
    }
    function configDotenv(options) {
      const dotenvPath = path4.resolve(process.cwd(), ".env");
      let encoding = "utf8";
      const debug = Boolean(options && options.debug);
      if (options && options.encoding) {
        encoding = options.encoding;
      } else {
        if (debug) {
          _debug("No encoding is specified. UTF-8 is used by default");
        }
      }
      let optionPaths = [dotenvPath];
      if (options && options.path) {
        if (!Array.isArray(options.path)) {
          optionPaths = [_resolveHome(options.path)];
        } else {
          optionPaths = [];
          for (const filepath of options.path) {
            optionPaths.push(_resolveHome(filepath));
          }
        }
      }
      let lastError;
      const parsedAll = {};
      for (const path5 of optionPaths) {
        try {
          const parsed = DotenvModule.parse(fs7.readFileSync(path5, { encoding }));
          DotenvModule.populate(parsedAll, parsed, options);
        } catch (e4) {
          if (debug) {
            _debug(`Failed to load ${path5} ${e4.message}`);
          }
          lastError = e4;
        }
      }
      let processEnv = process.env;
      if (options && options.processEnv != null) {
        processEnv = options.processEnv;
      }
      DotenvModule.populate(processEnv, parsedAll, options);
      if (lastError) {
        return { parsed: parsedAll, error: lastError };
      } else {
        return { parsed: parsedAll };
      }
    }
    function config(options) {
      if (_dotenvKey(options).length === 0) {
        return DotenvModule.configDotenv(options);
      }
      const vaultPath = _vaultPath(options);
      if (!vaultPath) {
        _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
        return DotenvModule.configDotenv(options);
      }
      return DotenvModule._configVault(options);
    }
    function decrypt(encrypted, keyStr) {
      const key = Buffer.from(keyStr.slice(-64), "hex");
      let ciphertext = Buffer.from(encrypted, "base64");
      const nonce = ciphertext.subarray(0, 12);
      const authTag = ciphertext.subarray(-16);
      ciphertext = ciphertext.subarray(12, -16);
      try {
        const aesgcm = crypto7.createDecipheriv("aes-256-gcm", key, nonce);
        aesgcm.setAuthTag(authTag);
        return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
      } catch (error2) {
        const isRange = error2 instanceof RangeError;
        const invalidKeyLength = error2.message === "Invalid key length";
        const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
        if (isRange || invalidKeyLength) {
          const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        } else if (decryptionFailed) {
          const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
          err2.code = "DECRYPTION_FAILED";
          throw err2;
        } else {
          throw error2;
        }
      }
    }
    function populate(processEnv, parsed, options = {}) {
      const debug = Boolean(options && options.debug);
      const override = Boolean(options && options.override);
      if (typeof parsed !== "object") {
        const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
        err2.code = "OBJECT_REQUIRED";
        throw err2;
      }
      for (const key of Object.keys(parsed)) {
        if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
          if (override === true) {
            processEnv[key] = parsed[key];
          }
          if (debug) {
            if (override === true) {
              _debug(`"${key}" is already defined and WAS overwritten`);
            } else {
              _debug(`"${key}" is already defined and was NOT overwritten`);
            }
          }
        } else {
          processEnv[key] = parsed[key];
        }
      }
    }
    var DotenvModule = {
      configDotenv,
      _configVault,
      _parseVault,
      config,
      decrypt,
      parse: parse4,
      populate
    };
    module2.exports.configDotenv = DotenvModule.configDotenv;
    module2.exports._configVault = DotenvModule._configVault;
    module2.exports._parseVault = DotenvModule._parseVault;
    module2.exports.config = DotenvModule.config;
    module2.exports.decrypt = DotenvModule.decrypt;
    module2.exports.parse = DotenvModule.parse;
    module2.exports.populate = DotenvModule.populate;
    module2.exports = DotenvModule;
  }
});

// ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/env-options.js
var require_env_options = __commonJS({
  "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/env-options.js"(exports2, module2) {
    var options = {};
    if (process.env.DOTENV_CONFIG_ENCODING != null) {
      options.encoding = process.env.DOTENV_CONFIG_ENCODING;
    }
    if (process.env.DOTENV_CONFIG_PATH != null) {
      options.path = process.env.DOTENV_CONFIG_PATH;
    }
    if (process.env.DOTENV_CONFIG_DEBUG != null) {
      options.debug = process.env.DOTENV_CONFIG_DEBUG;
    }
    if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
      options.override = process.env.DOTENV_CONFIG_OVERRIDE;
    }
    if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
      options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
    }
    module2.exports = options;
  }
});

// ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/cli-options.js
var require_cli_options = __commonJS({
  "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/cli-options.js"(exports2, module2) {
    var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
    module2.exports = function optionMatcher(args) {
      return args.reduce(function(acc, cur) {
        const matches = cur.match(re);
        if (matches) {
          acc[matches[1]] = matches[2];
        }
        return acc;
      }, {});
    };
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
var require_readline = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareReadLine = void 0;
    var prepareReadLine = () => {
      const stdin = process.stdin;
      const stdout = process.stdout;
      const readline = require("readline");
      const rl = readline.createInterface({
        input: stdin,
        escapeCodeTimeout: 50
      });
      readline.emitKeypressEvents(stdin, rl);
      return {
        stdin,
        stdout,
        closable: rl
      };
    };
    exports2.prepareReadLine = prepareReadLine;
  }
});

// ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
  "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
    "use strict";
    var ESC = "\x1B";
    var CSI = `${ESC}[`;
    var beep = "\x07";
    var cursor = {
      to(x4, y2) {
        if (!y2) return `${CSI}${x4 + 1}G`;
        return `${CSI}${y2 + 1};${x4 + 1}H`;
      },
      move(x4, y2) {
        let ret = "";
        if (x4 < 0) ret += `${CSI}${-x4}D`;
        else if (x4 > 0) ret += `${CSI}${x4}C`;
        if (y2 < 0) ret += `${CSI}${-y2}A`;
        else if (y2 > 0) ret += `${CSI}${y2}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`
    };
    var scroll = {
      up: (count = 1) => `${CSI}S`.repeat(count),
      down: (count = 1) => `${CSI}T`.repeat(count)
    };
    var 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 i4 = 0; i4 < count; i4++)
          clear += this.line + (i4 < count - 1 ? cursor.up() : "");
        if (count)
          clear += cursor.left;
        return clear;
      }
    };
    module2.exports = { cursor, scroll, erase, beep };
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
var require_utils = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.clear = void 0;
    var sisteransi_1 = require_src();
    var strip = (str) => {
      const pattern = [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
      ].join("|");
      const RGX = new RegExp(pattern, "g");
      return typeof str === "string" ? str.replace(RGX, "") : str;
    };
    var stringWidth = (str) => [...strip(str)].length;
    var clear = function(prompt, perLine) {
      if (!perLine)
        return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
      let rows = 0;
      const lines = prompt.split(/\r?\n/);
      for (let line of lines) {
        rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
      }
      return sisteransi_1.erase.lines(rows);
    };
    exports2.clear = clear;
  }
});

// ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
  "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root.Date.now();
    };
    function debounce(func, wait, options) {
      var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result;
      }
      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time = now();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
      }
      function trailingEdge(time) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = void 0;
        return result;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result : trailingEdge(now());
      }
      function debounced() {
        var time = now(), isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function throttle(func, wait, options) {
      var leading = true, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = "leading" in options ? !!options.leading : leading;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
        "leading": leading,
        "maxWait": wait,
        "trailing": trailing
      });
    }
    function isObject(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module2.exports = throttle;
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
var require_hanji = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports2) {
    "use strict";
    var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P || (P = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e4) {
            reject(e4);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e4) {
            reject(e4);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.onTerminate = exports2.renderWithTask = exports2.render = exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
    var readline_1 = require_readline();
    var sisteransi_1 = require_src();
    var utils_1 = require_utils();
    var lodash_throttle_1 = __importDefault2(require_lodash());
    var Prompt3 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
        this.inputCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        } else if (type === "input") {
          this.inputCallbacks.push(callback);
        }
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      input(str, key) {
        this.inputCallbacks.forEach((it) => it(str, key));
      }
    };
    exports2.Prompt = Prompt3;
    var SelectState3 = class {
      constructor(items) {
        this.items = items;
        this.selectedIdx = 0;
      }
      bind(prompt) {
        prompt.on("input", (str, key) => {
          const invalidate = this.consume(str, key);
          if (invalidate)
            prompt.requestLayout();
        });
      }
      consume(str, key) {
        if (!key)
          return false;
        if (key.name === "down") {
          this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
          return true;
        }
        if (key.name === "up") {
          this.selectedIdx -= 1;
          this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
          return true;
        }
        return false;
      }
    };
    exports2.SelectState = SelectState3;
    var deferred = () => {
      let resolve2;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve2 = res;
        reject = rej;
      });
      return {
        resolve: resolve2,
        reject,
        promise
      };
    };
    exports2.deferred = deferred;
    var Terminal = class {
      constructor(view5, stdin, stdout, closable) {
        this.view = view5;
        this.stdin = stdin;
        this.stdout = stdout;
        this.closable = closable;
        this.text = "";
        this.status = "idle";
        if (this.stdin.isTTY)
          this.stdin.setRawMode(true);
        const keypress = (str, key) => {
          if (key.name === "c" && key.ctrl === true) {
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            if (terminateHandler) {
              terminateHandler(this.stdin, this.stdout);
              return;
            }
            this.stdout.write(`
^C
`);
            process.exit(1);
          }
          if (key.name === "escape") {
            this.status = "aborted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "aborted", data: void 0 });
            return;
          }
          if (key.name === "return") {
            this.status = "submitted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "submitted", data: this.view.result() });
            return;
          }
          view5.input(str, key);
        };
        this.stdin.on("keypress", keypress);
        this.view.attach(this);
        const { resolve: resolve2, promise } = (0, exports2.deferred)();
        this.resolve = resolve2;
        this.promise = promise;
        this.renderFunc = (0, lodash_throttle_1.default)((str) => {
          this.stdout.write(str);
        });
      }
      tearDown(keypress) {
        this.stdout.write(sisteransi_1.cursor.show);
        this.stdin.removeListener("keypress", keypress);
        if (this.stdin.isTTY)
          this.stdin.setRawMode(false);
        this.closable.close();
      }
      result() {
        return this.promise;
      }
      toggleCursor(state2) {
        if (state2 === "hide") {
          this.stdout.write(sisteransi_1.cursor.hide);
        } else {
          this.stdout.write(sisteransi_1.cursor.show);
        }
      }
      requestLayout() {
        const string2 = this.view.render(this.status);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string2;
        this.renderFunc(`${clearPrefix}${string2}`);
      }
    };
    exports2.Terminal = Terminal;
    var TaskView2 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        }
      }
    };
    exports2.TaskView = TaskView2;
    var TaskTerminal = class {
      constructor(view5, stdout) {
        this.view = view5;
        this.stdout = stdout;
        this.text = "";
        this.view.attach(this);
      }
      requestLayout() {
        const string2 = this.view.render("pending");
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string2;
        this.stdout.write(`${clearPrefix}${string2}`);
      }
      clear() {
        const string2 = this.view.render("done");
        this.view.detach(this);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.stdout.write(`${clearPrefix}${string2}`);
      }
    };
    exports2.TaskTerminal = TaskTerminal;
    function render10(view5) {
      const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
      if (view5 instanceof Prompt3) {
        const terminal = new Terminal(view5, stdin, stdout, closable);
        terminal.requestLayout();
        return terminal.result();
      }
      stdout.write(`${view5}
`);
      closable.close();
      return;
    }
    exports2.render = render10;
    function renderWithTask7(view5, task) {
      return __awaiter2(this, void 0, void 0, function* () {
        const terminal = new TaskTerminal(view5, process.stdout);
        terminal.requestLayout();
        const result = yield task;
        terminal.clear();
        return result;
      });
    }
    exports2.renderWithTask = renderWithTask7;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports2.onTerminate = onTerminate;
  }
});

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

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

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

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
function setErrorMap(map2) {
  overrideErrorMap = map2;
}
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() {
    init_en();
    overrideErrorMap = en_default;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x4) => !!x4)
  });
  ctx.common.issues.push(issue);
}
var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() {
    init_errors();
    init_en();
    makeIssue = (params) => {
      const { data, path: path4, errorMaps, issueData } = params;
      const fullPath = [...path4, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
      for (const map2 of maps) {
        errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    ParseStatus = class _ParseStatus {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s4 of results) {
          if (s4.status === "aborted")
            return INVALID;
          if (s4.status === "dirty")
            status.dirty();
          arrayValue.push(s4.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x4) => x4.status === "aborted";
    isDirty = (x4) => x4.status === "dirty";
    isValid = (x4) => x4.status === "valid";
    isAsync = (x4) => typeof Promise !== "undefined" && x4 instanceof Promise;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() {
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() {
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val2, step) {
  const valDecCount = (val2.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function deepPartialify(schema6) {
  if (schema6 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema6.shape) {
      const fieldSchema = schema6.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema6._def,
      shape: () => newShape
    });
  } else if (schema6 instanceof ZodArray) {
    return new ZodArray({
      ...schema6._def,
      type: deepPartialify(schema6.element)
    });
  } else if (schema6 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema6.unwrap()));
  } else if (schema6 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema6.unwrap()));
  } else if (schema6 instanceof ZodTuple) {
    return ZodTuple.create(schema6.items.map((item) => deepPartialify(item)));
  } else {
    return schema6;
  }
}
function mergeValues(a3, b3) {
  const aType = getParsedType(a3);
  const bType = getParsedType(b3);
  if (a3 === b3) {
    return { valid: true, data: a3 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b3);
    const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a3, ...b3 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a3[key], b3[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a3.length !== b3.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index6 = 0; index6 < a3.length; index6++) {
      const itemA = a3[index6];
      const itemB = b3[index6];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b3) {
    return { valid: true, data: a3 };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p3 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p3 === "string" ? { message: p3 } : p3;
  return p22;
}
function custom(check2, _params = {}, fatal) {
  if (check2)
    return ZodAny.create().superRefine((data, ctx) => {
      const r4 = check2(data);
      if (r4 instanceof Promise) {
        return r4.then((r5) => {
          if (!r5) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r4) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
var init_types = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() {
    init_ZodError();
    init_errors();
    init_errorUtil();
    init_parseUtil();
    init_util();
    ParseInputLazyPath = class {
      constructor(parent, value, path4, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path4;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error2 = new ZodError(ctx.common.issues);
            this._error = error2;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: (params == null ? void 0 : params.async) ?? false,
            contextualErrorMap: params == null ? void 0 : params.errorMap
          },
          path: (params == null ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        var _a2, _b;
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err2) {
            if ((_b = (_a2 = err2 == null ? void 0 : err2.message) == null ? void 0 : _a2.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params == null ? void 0 : params.errorMap,
            async: true
          },
          path: (params == null ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check2, message) {
        const getIssueProperties = (val2) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val2);
          } else {
            return message;
          }
        };
        return this._refinement((val2, ctx) => {
          const result = check2(val2);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val2)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check2, refinementData) {
        return this._refinement((val2, ctx) => {
          if (!check2(val2)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data) => this["~validate"](data)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.length < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.length > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "length") {
            const tooBig = input.data.length > check2.value;
            const tooSmall = input.data.length < check2.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              }
              status.dirty();
            }
          } else if (check2.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "regex") {
            check2.regex.lastIndex = 0;
            const testResult = check2.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "trim") {
            input.data = input.data.trim();
          } else if (check2.kind === "includes") {
            if (!input.data.includes(check2.value, check2.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check2.value, position: check2.position },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check2.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check2.kind === "startsWith") {
            if (!input.data.startsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "endsWith") {
            if (!input.data.endsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "datetime") {
            const regex = datetimeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "time") {
            const regex = timeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ip") {
            if (!isValidIP(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "jwt") {
            if (!isValidJWT(input.data, check2.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cidr") {
            if (!isValidCidr(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check2) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
          offset: (options == null ? void 0 : options.offset) ?? false,
          local: (options == null ? void 0 : options.local) ?? false,
          ...errorUtil.errToObj(options == null ? void 0 : options.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
          ...errorUtil.errToObj(options == null ? void 0 : options.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options == null ? void 0 : options.position,
          ...errorUtil.errToObj(options == null ? void 0 : options.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (params == null ? void 0 : params.coerce) ?? false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check2.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min) && Number.isFinite(max);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params == null ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (input.data % check2.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (params == null ? void 0 : params.coerce) ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: (params == null ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.getTime() < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check2.message,
                inclusive: true,
                exact: false,
                minimum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.getTime() > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check2.message,
                inclusive: true,
                exact: false,
                maximum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check2) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: (params == null ? void 0 : params.coerce) || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i4) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i4) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema6, params) => {
      return new ZodArray({
        type: schema6,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              var _a2, _b;
              const defaultError = ((_b = (_a2 = this._def).errorMap) == null ? void 0 : _b.call(_a2, issue, ctx).message) ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema6) {
        return this.augment({ [key]: schema6 });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index6) {
        return new _ZodObject({
          ...this._def,
          catchall: index6
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types3, params) => {
      return new ZodUnion({
        options: types3,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema6 = this._def.items[itemIndex] || this._def.rest;
          if (!schema6)
            return null;
          return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x4) => !!x4);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error2) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error2
            }
          });
        }
        function makeReturnsIssue(returns, error2) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error2
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error2 = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e4) => {
              error2.addIssue(makeArgsIssue(args, e4));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e4) => {
              error2.addIssue(makeReturnsIssue(result, e4));
              throw error2;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema6, params) => {
      return new ZodPromise({
        type: schema6,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base))
              return INVALID;
            const result = effect.transform(base.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
              if (!isValid(base))
                return INVALID;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema6, effect, params) => {
      return new ZodEffects({
        schema: schema6,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema6, params) => {
      return new ZodEffects({
        schema: schema6,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a3, b3) {
        return new _ZodPipeline({
          in: a3,
          out: b3,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce = {
      string: (arg) => ZodString.create({ ...arg, coerce: true }),
      number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
      boolean: (arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      }),
      bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
      date: (arg) => ZodDate.create({ ...arg, coerce: true })
    };
    NEVER = INVALID;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util,
  void: () => voidType
});
var init_external = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() {
    init_errors();
    init_parseUtil();
    init_typeAliases();
    init_util();
    init_types();
    init_ZodError();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js
var init_v3 = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() {
    init_external();
    init_external();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js
var init_esm = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() {
    init_v3();
    init_v3();
  }
});

// src/global.ts
function assertUnreachable(x4) {
  throw new Error("Didn't expect to get here");
}
function softAssertUnreachable(x4) {
  return null;
}
var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
var init_global = __esm({
  "src/global.ts"() {
    "use strict";
    originUUID = "00000000-0000-0000-0000-000000000000";
    snapshotVersion = "7";
    mapValues = (obj, map2) => {
      const result = Object.keys(obj).reduce(function(result2, key) {
        result2[key] = map2(obj[key]);
        return result2;
      }, {});
      return result;
    };
    mapKeys = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const newKey = map2(key, val2);
          return [newKey, val2];
        })
      );
      return result;
    };
    mapEntries = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map2(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
    customMapEntries = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map2(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
  }
});

// src/serializer/mysqlSchema.ts
var index, fk, column, tableV3, compositePK, uniqueConstraint, checkConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
var init_mysqlSchema = __esm({
  "src/serializer/mysqlSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    fk = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    column = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk)
    }).strict();
    compositePK = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    tableV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk)
    }).strict();
    table = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk),
      compositePrimaryKeys: recordType(stringType(), compositePK),
      uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
      checkConstraint: recordType(stringType(), checkConstraint).default({})
    }).strict();
    viewMeta = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    view = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict().merge(viewMeta);
    kitInternals = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect = literalType("mysql");
    schemaHash = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternalV3 = objectType({
      version: literalType("3"),
      dialect,
      tables: recordType(stringType(), tableV3)
    }).strict();
    schemaInternalV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    schemaInternalV5 = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    schemaInternal = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table),
      views: recordType(stringType(), view).default({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    schemaV3 = schemaInternalV3.merge(schemaHash);
    schemaV4 = schemaInternalV4.merge(schemaHash);
    schemaV5 = schemaInternalV5.merge(schemaHash);
    schema = schemaInternal.merge(schemaHash);
    tableSquashedV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    tableSquashed = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    viewSquashed = view.omit({
      algorithm: true,
      sqlSecurity: true,
      withCheckOption: true
    }).extend({ meta: stringType() });
    schemaSquashed = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), tableSquashed),
      views: recordType(stringType(), viewSquashed)
    }).strict();
    schemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableSquashedV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    MySqlSquasher = {
      squashIdx: (idx) => {
        index.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashCheck: (input) => {
        return `${input.name};${input.value}`;
      },
      unsquashCheck: (input) => {
        const [name, value] = input.split(";");
        return { name, value };
      },
      squashView: (view5) => {
        return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`;
      },
      unsquashView: (meta) => {
        const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
        const toReturn = {
          algorithm,
          sqlSecurity,
          withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
        };
        return viewMeta.parse(toReturn);
      }
    };
    squashMysqlScheme = (json) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return MySqlSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return MySqlSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return MySqlSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return MySqlSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check2) => {
            return MySqlSquasher.squashCheck(check2);
          });
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      const mappedViews = Object.fromEntries(
        Object.entries(json.views).map(([key, value]) => {
          const meta = MySqlSquasher.squashView(value);
          return [key, {
            name: value.name,
            isExisting: value.isExisting,
            columns: value.columns,
            definition: value.definition,
            meta
          }];
        })
      );
      return {
        version: "5",
        dialect: json.dialect,
        tables: mappedTables,
        views: mappedViews
      };
    };
    mysqlSchema = schema;
    mysqlSchemaV5 = schemaV5;
    mysqlSchemaSquashed = schemaSquashed;
    backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
    dryMySql = mysqlSchema.parse({
      version: "5",
      dialect: "mysql",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      views: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/pgSchema.ts
var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
var init_pgSchema = __esm({
  "src/serializer/pgSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    indexV2 = objectType({
      name: stringType(),
      columns: recordType(
        stringType(),
        objectType({
          name: stringType()
        })
      ),
      isUnique: booleanType()
    }).strict();
    columnV2 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: stringType().optional()
    }).strict();
    tableV2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV2),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    enumSchemaV1 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    enumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    pgSchemaV2 = objectType({
      version: literalType("2"),
      tables: recordType(stringType(), tableV2),
      enums: recordType(stringType(), enumSchemaV1)
    }).strict();
    references = objectType({
      foreignKeyName: stringType(),
      table: stringType(),
      column: stringType(),
      onDelete: stringType().optional(),
      onUpdate: stringType().optional()
    }).strict();
    columnV1 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: references.optional()
    }).strict();
    tableV1 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV1),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    pgSchemaV1 = objectType({
      version: literalType("1"),
      tables: recordType(stringType(), tableV1),
      enums: recordType(stringType(), enumSchemaV1)
    }).strict();
    indexColumn = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index2 = objectType({
      name: stringType(),
      columns: indexColumn.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV6 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk2 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    columnV7 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional()
    }).strict();
    column2 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint2 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    tableV32 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    compositePK2 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint2 = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
    view2 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    tableV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV4),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    tableV5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV5),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    tableV6 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV6),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    tableV7 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnV7),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    table2 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
      policies: recordType(stringType(), policy).default({}),
      checkConstraints: recordType(stringType(), checkConstraint2).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash2 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals2 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    pgSchemaInternalV3 = objectType({
      version: literalType("3"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV32),
      enums: recordType(stringType(), enumSchemaV1)
    }).strict();
    pgSchemaInternalV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV42),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaInternalV5 = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV5),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaInternalV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV6),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaExternal = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: arrayType(table2),
      enums: arrayType(enumSchemaV1),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    pgSchemaInternalV7 = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV7),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      sequences: recordType(stringType(), sequenceSchema),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaInternal = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), table2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view2).default({}),
      sequences: recordType(stringType(), sequenceSchema).default({}),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policy).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    tableSquashed2 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    tableSquashedV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableSquashedV42),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashed = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view2),
      sequences: recordType(stringType(), sequenceSquashed),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policySquashed).default({})
    }).strict();
    pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
    pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
    pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash2);
    pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash2);
    pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash2);
    pgSchema = pgSchemaInternal.merge(schemaHash2);
    backwardCompatiblePgSchema = unionType([
      pgSchemaV5,
      pgSchemaV6,
      pgSchema
    ]);
    PgSquasher = {
      squashIdx: (idx) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.map(
          (c3) => `${c3.expression}--${c3.isExpression}--${c3.asc}--${c3.nulls}--${c3.opclass ? c3.opclass : ""}`
        ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
      },
      unsquashIdx: (input) => {
        const [
          name,
          columnsString,
          isUnique,
          concurrently,
          method,
          where,
          idxWith
        ] = input.split(";");
        const columnString = columnsString.split(",,");
        const columns = [];
        for (const column11 of columnString) {
          const [expression, isExpression, asc, nulls, opclass] = column11.split("--");
          columns.push({
            nulls,
            isExpression: isExpression === "true",
            asc: asc === "true",
            expression,
            opclass: opclass === "undefined" ? void 0 : opclass
          });
        }
        const result = index2.parse({
          name,
          columns,
          isUnique: isUnique === "true",
          concurrently: concurrently === "true",
          method,
          where: where === "undefined" ? void 0 : where,
          with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashIdxPush: (idx) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.map((c3) => `${c3.isExpression ? "" : c3.expression}--${c3.asc}--${c3.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
      },
      unsquashIdxPush: (input) => {
        const [name, columnsString, isUnique, method, idxWith] = input.split(";");
        const columnString = columnsString.split("--");
        const columns = [];
        for (const column11 of columnString) {
          const [expression, asc, nulls, opclass] = column11.split(",");
          columns.push({
            nulls,
            isExpression: expression === "",
            asc: asc === "true",
            expression
          });
        }
        const result = index2.parse({
          name,
          columns,
          isUnique: isUnique === "true",
          concurrently: false,
          method,
          with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`;
      },
      squashPolicy: (policy5) => {
        var _a2;
        return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`;
      },
      unsquashPolicy: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          using: splitted[4] !== "undefined" ? splitted[4] : void 0,
          withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
          on: splitted[6] !== "undefined" ? splitted[6] : void 0
        };
      },
      squashPolicyPush: (policy5) => {
        var _a2;
        return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.on}`;
      },
      unsquashPolicyPush: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          on: splitted[4] !== "undefined" ? splitted[4] : void 0
        };
      },
      squashPK: (pk) => {
        return `${pk.columns.join(",")};${pk.name}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[1], columns: splitted[0].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns, nullsNotDistinct] = unq.split(";");
        return {
          name,
          columns: columns.split(","),
          nullsNotDistinct: nullsNotDistinct === "true"
        };
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete,
          schemaTo
        ] = input.split(";");
        const result = fk2.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          schemaTo,
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashSequence: (seq) => {
        return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashSequence: (seq) => {
        const splitted = seq.split(";");
        return {
          minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
          maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
          increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
          startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
          cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
          cycle: splitted[5] === "true"
        };
      },
      squashIdentity: (seq) => {
        return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashIdentity: (seq) => {
        const splitted = seq.split(";");
        return {
          name: splitted[0],
          type: splitted[1],
          minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
          maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
          increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
          startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
          cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
          cycle: splitted[7] === "true"
        };
      },
      squashCheck: (check2) => {
        return `${check2.name};${check2.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name,
          value
        ] = input.split(";");
        return { name, value };
      }
    };
    squashPgScheme = (json, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return PgSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return PgSquasher.squashPK(pk);
          });
          const mappedColumns = Object.fromEntries(
            Object.entries(it[1].columns).map((it2) => {
              const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
              return [
                it2[0],
                {
                  ...it2[1],
                  identity: mappedIdentity
                }
              ];
            })
          );
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return PgSquasher.squashUnique(unq);
            }
          );
          const squashedPolicies = mapValues(it[1].policies, (policy5) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5);
          });
          const squashedChecksContraints = mapValues(
            it[1].checkConstraints,
            (check2) => {
              return PgSquasher.squashCheck(check2);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              columns: mappedColumns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              policies: squashedPolicies,
              checkConstraints: squashedChecksContraints,
              isRLSEnabled: it[1].isRLSEnabled ?? false
            }
          ];
        })
      );
      const mappedSequences = Object.fromEntries(
        Object.entries(json.sequences).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              values: PgSquasher.squashSequence(it[1])
            }
          ];
        })
      );
      const mappedPolicies = Object.fromEntries(
        Object.entries(json.policies).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
            }
          ];
        })
      );
      return {
        version: "7",
        dialect: json.dialect,
        tables: mappedTables,
        enums: json.enums,
        schemas: json.schemas,
        views: json.views,
        policies: mappedPolicies,
        sequences: mappedSequences,
        roles: json.roles
      };
    };
    dryPg = pgSchema.parse({
      version: snapshotVersion,
      dialect: "postgresql",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/singlestoreSchema.ts
var index3, column3, compositePK3, uniqueConstraint3, table3, viewMeta2, kitInternals3, dialect2, schemaHash3, schemaInternal2, schema2, tableSquashed3, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
var init_singlestoreSchema = __esm({
  "src/serializer/singlestoreSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index3 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    column3 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    compositePK3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    table3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    viewMeta2 = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    kitInternals3 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect2 = literalType("singlestore");
    schemaHash3 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternal2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), table3),
      /* views: record(string(), view).default({}), */
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    schema2 = schemaInternal2.merge(schemaHash3);
    tableSquashed3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), tableSquashed3)
      /* views: record(string(), viewSquashed), */
    }).strict();
    SingleStoreSquasher = {
      squashIdx: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index3.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      }
      /* squashView: (view: View): string => {
      		return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
      	},
      	unsquashView: (meta: string): SquasherViewMeta => {
      		const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
      		const toReturn = {
      			algorithm: algorithm,
      			sqlSecurity: sqlSecurity,
      			withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
      		};
      
      		return viewMeta.parse(toReturn);
      	}, */
    };
    squashSingleStoreScheme = (json) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SingleStoreSquasher.squashIdx(index6);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SingleStoreSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SingleStoreSquasher.squashUnique(unq);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints
            }
          ];
        })
      );
      return {
        version: "1",
        dialect: json.dialect,
        tables: mappedTables
        /* views: mappedViews, */
      };
    };
    singlestoreSchema = schema2;
    singlestoreSchemaSquashed = schemaSquashed2;
    backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
    drySingleStore = singlestoreSchema.parse({
      version: "1",
      dialect: "singlestore",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      /* views: {}, */
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/sqliteSchema.ts
var index4, fk3, compositePK4, column4, tableV33, uniqueConstraint4, checkConstraint3, table4, view3, dialect3, schemaHash4, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals4, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed4, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
  "src/serializer/sqliteSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      where: stringType().optional(),
      isUnique: booleanType()
    }).strict();
    fk3 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    compositePK4 = objectType({
      columns: stringType().array(),
      name: stringType().optional()
    }).strict();
    column4 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV33 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), index4),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    uniqueConstraint4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint3 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    table4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), index4),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK4),
      uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({}),
      checkConstraints: recordType(stringType(), checkConstraint3).default({})
    }).strict();
    view3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict();
    dialect3 = enumType(["sqlite"]);
    schemaHash4 = objectType({
      id: stringType(),
      prevId: stringType()
    }).strict();
    schemaInternalV32 = objectType({
      version: literalType("3"),
      dialect: dialect3,
      tables: recordType(stringType(), tableV33),
      enums: objectType({})
    }).strict();
    schemaInternalV42 = objectType({
      version: literalType("4"),
      dialect: dialect3,
      tables: recordType(stringType(), table4),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({})
    }).strict();
    schemaInternalV52 = objectType({
      version: literalType("5"),
      dialect: dialect3,
      tables: recordType(stringType(), table4),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    kitInternals4 = objectType({
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    latestVersion = literalType("6");
    schemaInternal3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), table4),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals4
    }).strict();
    schemaV32 = schemaInternalV32.merge(schemaHash4).strict();
    schemaV42 = schemaInternalV42.merge(schemaHash4).strict();
    schemaV52 = schemaInternalV52.merge(schemaHash4).strict();
    schema3 = schemaInternal3.merge(schemaHash4).strict();
    tableSquashed4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), tableSquashed4),
      views: recordType(stringType(), view3),
      enums: anyType()
    }).strict();
    SQLiteSquasher = {
      squashIdx: (idx) => {
        index4.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, where] = input.split(";");
        const result = index4.parse({
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          where: where ?? void 0
        });
        return result;
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk3.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPushFK: (fk5) => {
        return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashPushFK: (input) => {
        const [
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk3.parse({
          name: "",
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPK: (pk) => {
        return pk.columns.join(",");
      },
      unsquashPK: (pk) => {
        return pk.split(",");
      },
      squashCheck: (check2) => {
        return `${check2.name};${check2.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name,
          value
        ] = input.split(";");
        return { name, value };
      }
    };
    squashSqliteScheme = (json, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SQLiteSquasher.squashIdx(index6);
          });
          const squashedFKs = customMapEntries(
            it[1].foreignKeys,
            (key, value) => {
              return action === "push" ? [
                SQLiteSquasher.squashPushFK(value),
                SQLiteSquasher.squashPushFK(value)
              ] : [key, SQLiteSquasher.squashFK(value)];
            }
          );
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SQLiteSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SQLiteSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(
            it[1].checkConstraints,
            (check2) => {
              return SQLiteSquasher.squashCheck(check2);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      return {
        version: "6",
        dialect: json.dialect,
        tables: mappedTables,
        views: json.views,
        enums: json.enums
      };
    };
    drySQLite = schema3.parse({
      version: "6",
      dialect: "sqlite",
      id: originUUID,
      prevId: "",
      tables: {},
      views: {},
      enums: {},
      _meta: {
        tables: {},
        columns: {}
      }
    });
    sqliteSchemaV5 = schemaV52;
    sqliteSchema = schema3;
    SQLiteSchemaSquashed = schemaSquashed3;
    backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  }
});

// src/schemaValidator.ts
var dialects, dialect4, commonSquashedSchema, commonSchema;
var init_schemaValidator = __esm({
  "src/schemaValidator.ts"() {
    "use strict";
    init_esm();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"];
    dialect4 = enumType(dialects);
    commonSquashedSchema = unionType([
      pgSchemaSquashed,
      mysqlSchemaSquashed,
      SQLiteSchemaSquashed,
      singlestoreSchemaSquashed
    ]);
    commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  }
});

// ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
function camelCase(input, options) {
  if (!(typeof input === "string" || Array.isArray(input))) {
    throw new TypeError("Expected the input to be `string | string[]`");
  }
  options = {
    pascalCase: false,
    preserveConsecutiveUppercase: false,
    ...options
  };
  if (Array.isArray(input)) {
    input = input.map((x4) => x4.trim()).filter((x4) => x4.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options.locale === false ? (string2) => string2.toLowerCase() : (string2) => string2.toLocaleLowerCase(options.locale);
  const toUpperCase = options.locale === false ? (string2) => string2.toUpperCase() : (string2) => string2.toLocaleUpperCase(options.locale);
  if (input.length === 1) {
    if (SEPARATORS.test(input)) {
      return "";
    }
    return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  }
  const hasUpperCase = input !== toLowerCase(input);
  if (hasUpperCase) {
    input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  }
  input = input.replace(LEADING_SEPARATORS, "");
  input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  if (options.pascalCase) {
    input = toUpperCase(input.charAt(0)) + input.slice(1);
  }
  return postProcess(input, toUpperCase);
}
var UPPERCASE, LOWERCASE, LEADING_CAPITAL, IDENTIFIER, SEPARATORS, LEADING_SEPARATORS, SEPARATORS_AND_IDENTIFIER, NUMBERS_AND_IDENTIFIER, preserveCamelCase, preserveConsecutiveUppercase, postProcess;
var init_camelcase = __esm({
  "../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js"() {
    UPPERCASE = /[\p{Lu}]/u;
    LOWERCASE = /[\p{Ll}]/u;
    LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
    IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
    SEPARATORS = /[_.\- ]+/;
    LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
    SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
    NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
    preserveCamelCase = (string2, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
      let isLastCharLower = false;
      let isLastCharUpper = false;
      let isLastLastCharUpper = false;
      let isLastLastCharPreserved = false;
      for (let index6 = 0; index6 < string2.length; index6++) {
        const character = string2[index6];
        isLastLastCharPreserved = index6 > 2 ? string2[index6 - 3] === "-" : true;
        if (isLastCharLower && UPPERCASE.test(character)) {
          string2 = string2.slice(0, index6) + "-" + string2.slice(index6);
          isLastCharLower = false;
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = true;
          index6++;
        } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
          string2 = string2.slice(0, index6 - 1) + "-" + string2.slice(index6 - 1);
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = false;
          isLastCharLower = true;
        } else {
          isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
        }
      }
      return string2;
    };
    preserveConsecutiveUppercase = (input, toLowerCase) => {
      LEADING_CAPITAL.lastIndex = 0;
      return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
    };
    postProcess = (input, toUpperCase) => {
      SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
      NUMBERS_AND_IDENTIFIER.lastIndex = 0;
      return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m4) => toUpperCase(m4));
    };
  }
});

// src/@types/utils.ts
var init_utils = __esm({
  "src/@types/utils.ts"() {
    "use strict";
    init_camelcase();
    String.prototype.trimChar = function(char) {
      let start = 0;
      let end = this.length;
      while (start < end && this[start] === char) ++start;
      while (end > start && this[end - 1] === char) --end;
      return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
    };
    String.prototype.squashSpaces = function() {
      return this.replace(/  +/g, " ").trim();
    };
    String.prototype.camelCase = function() {
      return camelCase(String(this));
    };
    String.prototype.capitalise = function() {
      return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
    };
    String.prototype.concatIf = function(it, condition) {
      return condition ? `${this}${it}` : String(this);
    };
    String.prototype.snake_case = function() {
      return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
    };
    Array.prototype.random = function() {
      return this[~~(Math.random() * this.length)];
    };
  }
});

// src/cli/views.ts
var import_hanji, warning, err, info, grey, error, schema4, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
var init_views = __esm({
  "src/cli/views.ts"() {
    "use strict";
    init_source();
    import_hanji = __toESM(require_hanji());
    init_utils2();
    warning = (msg) => {
      (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
    };
    err = (msg) => {
      (0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
    };
    info = (msg, greyMsg = "") => {
      return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    grey = (msg) => {
      return source_default.grey(msg);
    };
    error = (error2, greyMsg = "") => {
      return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    schema4 = (schema6) => {
      const tables = Object.values(schema6.tables);
      let msg = source_default.bold(`${tables.length} tables
`);
      msg += tables.map((t4) => {
        const columnsCount = Object.values(t4.columns).length;
        const indexesCount = Object.values(t4.indexes).length;
        let foreignKeys = 0;
        if (schema6.dialect !== "singlestore") {
          foreignKeys = Object.values(t4.foreignKeys).length;
        }
        return `${source_default.bold.blue(t4.name)} ${source_default.gray(
          `${columnsCount} columns ${indexesCount} indexes ${foreignKeys} fks`
        )}`;
      }).join("\n");
      msg += "\n";
      const enums = objectValues(
        "enums" in schema6 ? "values" in schema6["enums"] ? schema6["enums"] : {} : {}
      );
      if (enums.length > 0) {
        msg += "\n";
        msg += source_default.bold(`${enums.length} enums
`);
        msg += enums.map((it) => {
          return `${source_default.bold.blue(it.name)} ${source_default.gray(
            `[${Object.values(it.values).join(", ")}]`
          )}`;
        }).join("\n");
        msg += "\n";
      }
      return msg;
    };
    isRenamePromptItem = (item) => {
      return "from" in item && "to" in item;
    };
    ResolveColumnSelect = class extends import_hanji.Prompt {
      constructor(tableName, base, data) {
        super();
        this.tableName = tableName;
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.data = new import_hanji.SelectState(data);
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "\n";
        }
        let text = `
Is ${source_default.bold.blue(
          this.base.name
        )} column in ${source_default.bold.blue(
          this.tableName
        )} table created or renamed from another column?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.data.items[this.data.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a3, b3) => {
          if (a3 > b3) {
            return a3;
          }
          return b3;
        }, 0);
        this.data.items.forEach((it, idx) => {
          const isSelected = idx === this.data.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.data.items[this.data.selectedIdx];
      }
    };
    tableKey = (it) => {
      return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
    };
    ResolveSelectNamed = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = this.base.name;
        let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
          const it = _3;
          const keyFrom = it.from.name;
          return key.length + 3 + keyFrom.length;
        }).reduce((a3, b3) => {
          if (a3 > b3) {
            return a3;
          }
          return b3;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSelect = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = tableKey(this.base);
        let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
          const it = _3;
          const keyFrom = tableKey(it.from);
          return key.length + 3 + keyFrom.length;
        }).reduce((a3, b3) => {
          if (a3 > b3) {
            return a3;
          }
          return b3;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSchemasSelect = class extends import_hanji.Prompt {
      constructor(base, data) {
        super();
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        let text = `
Is ${source_default.bold.blue(
          this.base.name
        )} schema created or renamed from another schema?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a3, b3) => {
          if (a3 > b3) {
            return a3;
          }
          return b3;
        }, 0);
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    Spinner = class {
      constructor(frames) {
        this.frames = frames;
        this.offset = 0;
        this.tick = () => {
          this.iterator();
        };
        this.value = () => {
          return this.frames[this.offset];
        };
        this.iterator = () => {
          this.offset += 1;
          this.offset %= frames.length - 1;
        };
      }
    };
    IntrospectProgress = class extends import_hanji.TaskView {
      constructor(hasEnums = false) {
        super();
        this.hasEnums = hasEnums;
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.state = {
          tables: {
            count: 0,
            name: "tables",
            status: "fetching"
          },
          columns: {
            count: 0,
            name: "columns",
            status: "fetching"
          },
          enums: {
            count: 0,
            name: "enums",
            status: "fetching"
          },
          indexes: {
            count: 0,
            name: "indexes",
            status: "fetching"
          },
          fks: {
            count: 0,
            name: "foreign keys",
            status: "fetching"
          },
          policies: {
            count: 0,
            name: "policies",
            status: "fetching"
          },
          checks: {
            count: 0,
            name: "check constraints",
            status: "fetching"
          },
          views: {
            count: 0,
            name: "views",
            status: "fetching"
          }
        };
        this.formatCount = (count) => {
          const width = Math.max.apply(
            null,
            Object.values(this.state).map((it) => it.count.toFixed(0).length)
          );
          return count.toFixed(0).padEnd(width, " ");
        };
        this.statusText = (spinner, stage) => {
          const { name, count } = stage;
          const isDone = stage.status === "done";
          const prefix2 = isDone ? `[${source_default.green("\u2713")}]` : `[${spinner}]`;
          const formattedCount = this.formatCount(count);
          const suffix = isDone ? `${formattedCount} ${name} fetched` : `${formattedCount} ${name} fetching`;
          return `${prefix2} ${suffix}
`;
        };
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      update(stage, count, status) {
        this.state[stage].count = count;
        this.state[stage].status = status;
        this.requestLayout();
      }
      render() {
        let info2 = "";
        const spin = this.spinner.value();
        info2 += this.statusText(spin, this.state.tables);
        info2 += this.statusText(spin, this.state.columns);
        info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
        info2 += this.statusText(spin, this.state.indexes);
        info2 += this.statusText(spin, this.state.fks);
        info2 += this.statusText(spin, this.state.policies);
        info2 += this.statusText(spin, this.state.checks);
        info2 += this.statusText(spin, this.state.views);
        return info2;
      }
    };
    MigrateProgress = class extends import_hanji.TaskView {
      constructor() {
        super();
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      render(status) {
        if (status === "pending") {
          const spin = this.spinner.value();
          return `[${spin}] applying migrations...`;
        }
        return `[${source_default.green("\u2713")}] migrations applied successfully!`;
      }
    };
    ProgressView = class extends import_hanji.TaskView {
      constructor(progressText, successText) {
        super();
        this.progressText = progressText;
        this.successText = successText;
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      render(status) {
        if (status === "pending") {
          const spin = this.spinner.value();
          return `[${spin}] ${this.progressText}
`;
        }
        return `[${source_default.green("\u2713")}] ${this.successText}
`;
      }
    };
    DropMigrationView = class extends import_hanji.Prompt {
      constructor(data) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.data = new import_hanji.SelectState(data);
        this.data.selectedIdx = data.length - 1;
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "\n";
        }
        let text = source_default.bold("Please select migration to drop:\n");
        const selectedPrefix = source_default.yellow("\u276F ");
        const data = trimmedRange(this.data.items, this.data.selectedIdx, 9);
        const labelLength = data.trimmed.map((it) => it.tag.length).reduce((a3, b3) => {
          if (a3 > b3) {
            return a3;
          }
          return b3;
        }, 0);
        text += data.startTrimmed ? "  ...\n" : "";
        data.trimmed.forEach((it, idx) => {
          const isSelected = idx === this.data.selectedIdx - data.offset;
          let title = it.tag.padEnd(labelLength, " ");
          title = isSelected ? source_default.yellow(title) : title;
          text += isSelected ? `${selectedPrefix}${title}` : `  ${title}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        text += data.endTrimmed ? "  ...\n" : "";
        return text;
      }
      result() {
        return this.data.items[this.data.selectedIdx];
      }
    };
    trimmedRange = (arr, index6, limitLines) => {
      const limit = limitLines - 2;
      const sideLimit = Math.round(limit / 2);
      const endTrimmed = arr.length - sideLimit > index6;
      const startTrimmed = index6 > sideLimit - 1;
      const paddingStart = Math.max(index6 + sideLimit - arr.length, 0);
      const paddingEnd = Math.min(index6 - sideLimit + 1, 0);
      const d1 = endTrimmed ? 1 : 0;
      const d22 = startTrimmed ? 0 : 1;
      const start = Math.max(0, index6 - sideLimit + d1 - paddingStart);
      const end = Math.min(arr.length, index6 + sideLimit + d22 - paddingEnd);
      return {
        trimmed: arr.slice(start, end),
        offset: start,
        startTrimmed,
        endTrimmed
      };
    };
  }
});

// src/serializer/gelSchema.ts
var enumSchema2, enumSchemaV12, indexColumn2, index5, fk4, sequenceSchema2, roleSchema2, sequenceSquashed2, column5, checkConstraint4, columnSquashed2, compositePK5, uniqueConstraint5, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view4, table5, schemaHash5, kitInternals5, gelSchemaExternal, gelSchemaInternal, tableSquashed5, gelSchemaSquashed, gelSchema, backwardCompatibleGelSchema, dryGel;
var init_gelSchema = __esm({
  "src/serializer/gelSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    enumSchema2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    enumSchemaV12 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    indexColumn2 = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index5 = objectType({
      name: stringType(),
      columns: indexColumn2.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk4 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema2 = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema2 = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    column5 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint4 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed2 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    compositePK5 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy2 = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed2 = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption2 = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption2 = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
    view4 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column5),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption2.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    table5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), index5),
      foreignKeys: recordType(stringType(), fk4),
      compositePrimaryKeys: recordType(stringType(), compositePK5),
      uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
      policies: recordType(stringType(), policy2).default({}),
      checkConstraints: recordType(stringType(), checkConstraint4).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash5 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals5 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    gelSchemaExternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: arrayType(table5),
      enums: arrayType(enumSchemaV12),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    gelSchemaInternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), table5),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view4).default({}),
      sequences: recordType(stringType(), sequenceSchema2).default({}),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policy2).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals5
    }).strict();
    tableSquashed5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    gelSchemaSquashed = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), tableSquashed5),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view4),
      sequences: recordType(stringType(), sequenceSquashed2),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policySquashed2).default({})
    }).strict();
    gelSchema = gelSchemaInternal.merge(schemaHash5);
    backwardCompatibleGelSchema = gelSchema;
    dryGel = gelSchema.parse({
      version: "1",
      dialect: "gel",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/utils.ts
function isPgArrayType(sqlType) {
  return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
}
function findAddedAndRemoved(columnNames1, columnNames2) {
  const set1 = new Set(columnNames1);
  const set2 = new Set(columnNames2);
  const addedColumns = columnNames2.filter((it) => !set1.has(it));
  const removedColumns = columnNames1.filter((it) => !set2.has(it));
  return { addedColumns, removedColumns };
}
function escapeSingleQuotes(str) {
  return str.replace(/'/g, "''");
}
function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
  const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
  return str.replace(/''/g, "'").replace(regex, "\\'");
}
var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
var init_utils2 = __esm({
  "src/utils.ts"() {
    "use strict";
    init_source();
    import_fs = require("fs");
    import_path = require("path");
    import_url = require("url");
    init_views();
    init_global();
    init_gelSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    copy = (it) => {
      return JSON.parse(JSON.stringify(it));
    };
    objectValues = (obj) => {
      return Object.values(obj);
    };
    assertV1OutFolder = (out) => {
      if (!(0, import_fs.existsSync)(out)) return;
      const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
        (it) => it.length === 14 && /^\d+$/.test(it)
      );
      if (oldMigrationFolders.length > 0) {
        console.log(
          `Your migrations folder format is outdated, please run ${source_default.green.bold(
            `drizzle-kit up`
          )}`
        );
        process.exit(1);
      }
    };
    dryJournal = (dialect6) => {
      return {
        version: snapshotVersion,
        dialect: dialect6,
        entries: []
      };
    };
    prepareOutFolder = (out, dialect6) => {
      const meta = (0, import_path.join)(out, "meta");
      const journalPath = (0, import_path.join)(meta, "_journal.json");
      if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
        (0, import_fs.mkdirSync)(meta, { recursive: true });
        (0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
      }
      const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
      const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
      snapshots.sort();
      return { meta, snapshots, journal };
    };
    validatorForDialect = (dialect6) => {
      switch (dialect6) {
        case "postgresql":
          return { validator: backwardCompatiblePgSchema, version: 7 };
        case "sqlite":
          return { validator: backwardCompatibleSqliteSchema, version: 6 };
        case "turso":
          return { validator: backwardCompatibleSqliteSchema, version: 6 };
        case "mysql":
          return { validator: backwardCompatibleMysqlSchema, version: 5 };
        case "singlestore":
          return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
        case "gel":
          return { validator: backwardCompatibleGelSchema, version: 1 };
      }
    };
    validateWithReport = (snapshots, dialect6) => {
      const { validator: validator2, version: version3 } = validatorForDialect(dialect6);
      const result = snapshots.reduce(
        (accum, it) => {
          const raw2 = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
          accum.rawMap[it] = raw2;
          if (raw2["version"] && Number(raw2["version"]) > version3) {
            console.log(
              info(
                `${it} snapshot is of unsupported version, please update drizzle-kit`
              )
            );
            process.exit(0);
          }
          const result2 = validator2.safeParse(raw2);
          if (!result2.success) {
            accum.malformed.push(it);
            return accum;
          }
          const snapshot = result2.data;
          if (snapshot.version !== String(version3)) {
            accum.nonLatest.push(it);
            return accum;
          }
          const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
            parent: it,
            snapshots: []
          };
          idEntry.snapshots.push(it);
          accum.idsMap[snapshot["prevId"]] = idEntry;
          return accum;
        },
        {
          malformed: [],
          nonLatest: [],
          idToNameMap: {},
          idsMap: {},
          rawMap: {}
        }
      );
      return result;
    };
    prepareMigrationFolder = (outFolder = "drizzle", dialect6) => {
      const { snapshots, journal } = prepareOutFolder(outFolder, dialect6);
      const report = validateWithReport(snapshots, dialect6);
      if (report.nonLatest.length > 0) {
        console.log(
          report.nonLatest.map((it) => {
            return `${it}/snapshot.json is not of the latest version`;
          }).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
        );
        process.exit(0);
      }
      if (report.malformed.length) {
        const message2 = report.malformed.map((it) => {
          return `${it} data is malformed`;
        }).join("\n");
        console.log(message2);
      }
      const collisionEntries = Object.entries(report.idsMap).filter(
        (it) => it[1].snapshots.length > 1
      );
      const message = collisionEntries.map((it) => {
        const data = it[1];
        return `[${data.snapshots.join(
          ", "
        )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
      }).join("\n").trim();
      if (message) {
        console.log(source_default.red.bold("Error:"), message);
      }
      const abort = report.malformed.length || collisionEntries.length > 0;
      if (abort) {
        process.exit(0);
      }
      return { snapshots, journal };
    };
    prepareMigrationMeta = (schemas, tables, columns) => {
      const _meta = {
        schemas: {},
        tables: {},
        columns: {}
      };
      schemas.forEach((it) => {
        const from = schemaRenameKey(it.from);
        const to = schemaRenameKey(it.to);
        _meta.schemas[from] = to;
      });
      tables.forEach((it) => {
        const from = tableRenameKey(it.from);
        const to = tableRenameKey(it.to);
        _meta.tables[from] = to;
      });
      columns.forEach((it) => {
        const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
        const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
        _meta.columns[from] = to;
      });
      return _meta;
    };
    schemaRenameKey = (it) => {
      return it;
    };
    tableRenameKey = (it) => {
      const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
      return out;
    };
    columnRenameKey = (table6, schema6, column11) => {
      const out = schema6 ? `"${schema6}"."${table6}"."${column11}"` : `"${table6}"."${column11}"`;
      return out;
    };
    normaliseSQLiteUrl = (it, type) => {
      if (type === "libsql") {
        if (it.startsWith("file:")) {
          return it;
        }
        try {
          const url = (0, import_url.parse)(it);
          if (url.protocol === null) {
            return `file:${it}`;
          }
          return it;
        } catch (e4) {
          return `file:${it}`;
        }
      }
      if (type === "better-sqlite") {
        if (it.startsWith("file:")) {
          return it.substring(5);
        }
        return it;
      }
      assertUnreachable(type);
    };
    normalisePGliteUrl = (it) => {
      if (it.startsWith("file:")) {
        return it.substring(5);
      }
      return it;
    };
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
var require_old = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports2) {
    var pathModule = require("path");
    var isWindows = process.platform === "win32";
    var fs7 = require("fs");
    var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
    function rethrow() {
      var callback;
      if (DEBUG) {
        var backtrace = new Error();
        callback = debugCallback;
      } else
        callback = missingCallback;
      return callback;
      function debugCallback(err2) {
        if (err2) {
          backtrace.message = err2.message;
          err2 = backtrace;
          missingCallback(err2);
        }
      }
      function missingCallback(err2) {
        if (err2) {
          if (process.throwDeprecation)
            throw err2;
          else if (!process.noDeprecation) {
            var msg = "fs: missing callback " + (err2.stack || err2.message);
            if (process.traceDeprecation)
              console.trace(msg);
            else
              console.error(msg);
          }
        }
      }
    }
    function maybeCallback(cb) {
      return typeof cb === "function" ? cb : rethrow();
    }
    var normalize = pathModule.normalize;
    if (isWindows) {
      nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
    } else {
      nextPartRe = /(.*?)(?:[\/]+|$)/g;
    }
    var nextPartRe;
    if (isWindows) {
      splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
    } else {
      splitRootRe = /^[\/]*/;
    }
    var splitRootRe;
    exports2.realpathSync = function realpathSync(p3, cache3) {
      p3 = pathModule.resolve(p3);
      if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) {
        return cache3[p3];
      }
      var original = p3, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m4 = splitRootRe.exec(p3);
        pos = m4[0].length;
        current = m4[0];
        base = m4[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs7.lstatSync(base);
          knownHard[base] = true;
        }
      }
      while (pos < p3.length) {
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p3);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache3 && cache3[base] === base) {
          continue;
        }
        var resolvedLink;
        if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) {
          resolvedLink = cache3[base];
        } else {
          var stat2 = fs7.lstatSync(base);
          if (!stat2.isSymbolicLink()) {
            knownHard[base] = true;
            if (cache3) cache3[base] = base;
            continue;
          }
          var linkTarget = null;
          if (!isWindows) {
            var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
            if (seenLinks.hasOwnProperty(id)) {
              linkTarget = seenLinks[id];
            }
          }
          if (linkTarget === null) {
            fs7.statSync(base);
            linkTarget = fs7.readlinkSync(base);
          }
          resolvedLink = pathModule.resolve(previous, linkTarget);
          if (cache3) cache3[base] = resolvedLink;
          if (!isWindows) seenLinks[id] = linkTarget;
        }
        p3 = pathModule.resolve(resolvedLink, p3.slice(pos));
        start();
      }
      if (cache3) cache3[original] = p3;
      return p3;
    };
    exports2.realpath = function realpath(p3, cache3, cb) {
      if (typeof cb !== "function") {
        cb = maybeCallback(cache3);
        cache3 = null;
      }
      p3 = pathModule.resolve(p3);
      if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) {
        return process.nextTick(cb.bind(null, null, cache3[p3]));
      }
      var original = p3, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m4 = splitRootRe.exec(p3);
        pos = m4[0].length;
        current = m4[0];
        base = m4[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs7.lstat(base, function(err2) {
            if (err2) return cb(err2);
            knownHard[base] = true;
            LOOP();
          });
        } else {
          process.nextTick(LOOP);
        }
      }
      function LOOP() {
        if (pos >= p3.length) {
          if (cache3) cache3[original] = p3;
          return cb(null, p3);
        }
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p3);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache3 && cache3[base] === base) {
          return process.nextTick(LOOP);
        }
        if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) {
          return gotResolvedLink(cache3[base]);
        }
        return fs7.lstat(base, gotStat);
      }
      function gotStat(err2, stat2) {
        if (err2) return cb(err2);
        if (!stat2.isSymbolicLink()) {
          knownHard[base] = true;
          if (cache3) cache3[base] = base;
          return process.nextTick(LOOP);
        }
        if (!isWindows) {
          var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
          if (seenLinks.hasOwnProperty(id)) {
            return gotTarget(null, seenLinks[id], base);
          }
        }
        fs7.stat(base, function(err3) {
          if (err3) return cb(err3);
          fs7.readlink(base, function(err4, target) {
            if (!isWindows) seenLinks[id] = target;
            gotTarget(err4, target);
          });
        });
      }
      function gotTarget(err2, target, base2) {
        if (err2) return cb(err2);
        var resolvedLink = pathModule.resolve(previous, target);
        if (cache3) cache3[base2] = resolvedLink;
        gotResolvedLink(resolvedLink);
      }
      function gotResolvedLink(resolvedLink) {
        p3 = pathModule.resolve(resolvedLink, p3.slice(pos));
        start();
      }
    };
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
var require_fs = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports2, module2) {
    module2.exports = realpath;
    realpath.realpath = realpath;
    realpath.sync = realpathSync;
    realpath.realpathSync = realpathSync;
    realpath.monkeypatch = monkeypatch;
    realpath.unmonkeypatch = unmonkeypatch;
    var fs7 = require("fs");
    var origRealpath = fs7.realpath;
    var origRealpathSync = fs7.realpathSync;
    var version3 = process.version;
    var ok = /^v[0-5]\./.test(version3);
    var old = require_old();
    function newError(er) {
      return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
    }
    function realpath(p3, cache3, cb) {
      if (ok) {
        return origRealpath(p3, cache3, cb);
      }
      if (typeof cache3 === "function") {
        cb = cache3;
        cache3 = null;
      }
      origRealpath(p3, cache3, function(er, result) {
        if (newError(er)) {
          old.realpath(p3, cache3, cb);
        } else {
          cb(er, result);
        }
      });
    }
    function realpathSync(p3, cache3) {
      if (ok) {
        return origRealpathSync(p3, cache3);
      }
      try {
        return origRealpathSync(p3, cache3);
      } catch (er) {
        if (newError(er)) {
          return old.realpathSync(p3, cache3);
        } else {
          throw er;
        }
      }
    }
    function monkeypatch() {
      fs7.realpath = realpath;
      fs7.realpathSync = realpathSync;
    }
    function unmonkeypatch() {
      fs7.realpath = origRealpath;
      fs7.realpathSync = origRealpathSync;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
var require_path = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports2, module2) {
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  }
});

// ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    module2.exports = balanced;
    function balanced(a3, b3, str) {
      if (a3 instanceof RegExp) a3 = maybeMatch(a3, str);
      if (b3 instanceof RegExp) b3 = maybeMatch(b3, str);
      var r4 = range(a3, b3, str);
      return r4 && {
        start: r4[0],
        end: r4[1],
        pre: str.slice(0, r4[0]),
        body: str.slice(r4[0] + a3.length, r4[1]),
        post: str.slice(r4[1] + b3.length)
      };
    }
    function maybeMatch(reg, str) {
      var m4 = str.match(reg);
      return m4 ? m4[0] : null;
    }
    balanced.range = range;
    function range(a3, b3, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a3);
      var bi = str.indexOf(b3, ai + 1);
      var i4 = ai;
      if (ai >= 0 && bi > 0) {
        if (a3 === b3) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i4 >= 0 && !result) {
          if (i4 == ai) {
            begs.push(i4);
            ai = str.indexOf(a3, i4 + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b3, i4 + 1);
          }
          i4 = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module2) {
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m4 = balanced("{", "}", str);
      if (!m4)
        return str.split(",");
      var pre = m4.pre;
      var body = m4.body;
      var post = m4.post;
      var p3 = pre.split(",");
      p3[p3.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p3[p3.length - 1] += postParts.shift();
        p3.push.apply(p3, postParts);
      }
      parts.push.apply(parts, p3);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand2(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte(i4, y2) {
      return i4 <= y2;
    }
    function gte(i4, y2) {
      return i4 >= y2;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m4 = balanced("{", "}", str);
      if (!m4) return [str];
      var pre = m4.pre;
      var post = m4.post.length ? expand2(m4.post, false) : [""];
      if (/\$$/.test(m4.pre)) {
        for (var k3 = 0; k3 < post.length; k3++) {
          var expansion = pre + "{" + m4.body + "}" + post[k3];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m4.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m4.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m4.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m4.post.match(/,.*\}/)) {
            str = m4.pre + "{" + m4.body + escClose + m4.post;
            return expand2(str);
          }
          return [str];
        }
        var n3;
        if (isSequence) {
          n3 = m4.body.split(/\.\./);
        } else {
          n3 = parseCommaParts(m4.body);
          if (n3.length === 1) {
            n3 = expand2(n3[0], false).map(embrace);
            if (n3.length === 1) {
              return post.map(function(p3) {
                return m4.pre + n3[0] + p3;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x4 = numeric(n3[0]);
          var y2 = numeric(n3[1]);
          var width = Math.max(n3[0].length, n3[1].length);
          var incr = n3.length == 3 ? Math.abs(numeric(n3[2])) : 1;
          var test = lte;
          var reverse = y2 < x4;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n3.some(isPadded);
          N = [];
          for (var i4 = x4; test(i4, y2); i4 += incr) {
            var c3;
            if (isAlphaSequence) {
              c3 = String.fromCharCode(i4);
              if (c3 === "\\")
                c3 = "";
            } else {
              c3 = String(i4);
              if (pad) {
                var need = width - c3.length;
                if (need > 0) {
                  var z2 = new Array(need + 1).join("0");
                  if (i4 < 0)
                    c3 = "-" + z2 + c3.slice(1);
                  else
                    c3 = z2 + c3;
                }
              }
            }
            N.push(c3);
          }
        } else {
          N = [];
          for (var j3 = 0; j3 < n3.length; j3++) {
            N.push.apply(N, expand2(n3[j3], false));
          }
        }
        for (var j3 = 0; j3 < N.length; j3++) {
          for (var k3 = 0; k3 < post.length; k3++) {
            var expansion = pre + N[j3] + post[k3];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports2, module2) {
    var minimatch2 = module2.exports = (p3, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p3);
    };
    module2.exports = minimatch2;
    var path4 = require_path();
    minimatch2.sep = path4.sep;
    var GLOBSTAR2 = Symbol("globstar **");
    minimatch2.GLOBSTAR = GLOBSTAR2;
    var expand2 = require_brace_expansion();
    var plTypes2 = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    var qmark2 = "[^/]";
    var star2 = qmark2 + "*?";
    var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
    var charSet2 = (s4) => s4.split("").reduce((set, c3) => {
      set[c3] = true;
      return set;
    }, {});
    var reSpecials2 = charSet2("().*{}+?[]^$\\!");
    var addPatternStartSet2 = charSet2("[.(");
    var slashSplit = /\/+/;
    minimatch2.filter = (pattern, options = {}) => (p3, i4, list) => minimatch2(p3, pattern, options);
    var ext2 = (a3, b3 = {}) => {
      const t4 = {};
      Object.keys(a3).forEach((k3) => t4[k3] = a3[k3]);
      Object.keys(b3).forEach((k3) => t4[k3] = b3[k3]);
      return t4;
    };
    minimatch2.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch2;
      }
      const orig = minimatch2;
      const m4 = (p3, pattern, options) => orig(p3, pattern, ext2(def, options));
      m4.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m4.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m4.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m4.defaults = (options) => orig.defaults(ext2(def, options));
      m4.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m4.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m4.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m4;
    };
    minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
    var braceExpand2 = (pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return expand2(pattern);
    };
    var MAX_PATTERN_LENGTH2 = 1024 * 64;
    var assertValidPattern2 = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH2) {
        throw new TypeError("pattern is too long");
      }
    };
    var SUBPARSE = Symbol("subparse");
    minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
    minimatch2.match = (list, pattern, options = {}) => {
      const mm = new Minimatch2(pattern, options);
      list = list.filter((f5) => mm.match(f5));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape2 = (s4) => s4.replace(/\\(.)/g, "$1");
    var charUnescape = (s4) => s4.replace(/\\([^-\]])/g, "$1");
    var regExpEscape2 = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s4) => s4.replace(/[[\]\\]/g, "\\$&");
    var Minimatch2 = class {
      constructor(pattern, options) {
        assertValidPattern2(pattern);
        if (!options) options = {};
        this.options = options;
        this.set = [];
        this.pattern = pattern;
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.regexp = null;
        this.negate = false;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.make();
      }
      debug() {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        let set = this.globSet = this.braceExpand();
        if (options.debug) this.debug = (...args) => console.error(...args);
        this.debug(this.pattern, set);
        set = this.globParts = set.map((s4) => s4.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s4, si, set2) => s4.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s4) => s4.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate) return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset) this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial) {
        var options = this.options;
        this.debug(
          "matchOne",
          { "this": this, file, pattern }
        );
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p3 = pattern[pi];
          var f5 = file[fi];
          this.debug(pattern, p3, f5);
          if (p3 === false) return false;
          if (p3 === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p3, f5]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) return true;
            }
            return false;
          }
          var hit;
          if (typeof p3 === "string") {
            hit = f5 === p3;
            this.debug("string match", p3, f5, hit);
          } else {
            hit = f5.match(p3);
            this.debug("pattern match", p3, f5, hit);
          }
          if (!hit) return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        }
        throw new Error("wtf?");
      }
      braceExpand() {
        return braceExpand2(this.pattern, this.options);
      }
      parse(pattern, isSub) {
        assertValidPattern2(pattern);
        const options = this.options;
        if (pattern === "**") {
          if (!options.noglobstar)
            return GLOBSTAR2;
          else
            pattern = "*";
        }
        if (pattern === "") return "";
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar;
        let inClass = false;
        let reClassStart = -1;
        let classStart = -1;
        let cs;
        let pl;
        let sp;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p3) => p3.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star2;
                hasMagic = true;
                break;
              case "?":
                re += qmark2;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i4 = 0, c3; i4 < pattern.length && (c3 = pattern.charAt(i4)); i4++) {
          this.debug("%s	%s %s %j", pattern, i4, re, c3);
          if (escaping) {
            if (c3 === "/") {
              return false;
            }
            if (reSpecials2[c3]) {
              re += "\\";
            }
            re += c3;
            escaping = false;
            continue;
          }
          switch (c3) {
            /* istanbul ignore next */
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i4 + 1) === "-") {
                re += c3;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i4, re, c3);
              if (inClass) {
                this.debug("  in class");
                if (c3 === "!" && i4 === classStart + 1) c3 = "^";
                re += c3;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c3;
              if (options.noext) clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i4 - 1,
                reStart: re.length,
                open: plTypes2[stateChar].open,
                close: plTypes2[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i4 + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i4 + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c3;
                continue;
              }
              inClass = true;
              classStart = i4;
              reClassStart = re.length;
              re += c3;
              continue;
            case "]":
              if (i4 === classStart + 1 || !inClass) {
                re += "\\" + c3;
                continue;
              }
              cs = pattern.substring(classStart + 1, i4);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c3;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c3] && !(c3 === "^" && inClass)) {
                re += "\\";
              }
              re += c3;
              break;
          }
        }
        if (inClass) {
          cs = pattern.slice(classStart + 1);
          sp = this.parse(cs, SUBPARSE);
          re = re.substring(0, reClassStart) + "\\[" + sp[0];
          hasMagic = hasMagic || sp[1];
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug("setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t4 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t4 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet2[re.charAt(0)];
        for (let n3 = negativeLists.length - 1; n3 > -1; n3--) {
          const nl = negativeLists[n3];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i4 = 0; i4 < openParensBefore; i4++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (isSub === SUBPARSE) {
          return [re, hasMagic];
        }
        if (options.nocase && !hasMagic) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape2(pattern);
        }
        const flags = options.nocase ? "i" : "";
        try {
          return Object.assign(new RegExp("^" + re + "$", flags), {
            _glob: pattern,
            _src: re
          });
        } catch (er) {
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false) return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          pattern = pattern.map(
            (p3) => typeof p3 === "string" ? regExpEscape2(p3) : p3 === GLOBSTAR2 ? GLOBSTAR2 : p3._src
          ).reduce((set2, p3) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p3 === GLOBSTAR2)) {
              set2.push(p3);
            }
            return set2;
          }, []);
          pattern.forEach((p3, i4) => {
            if (p3 !== GLOBSTAR2 || pattern[i4 - 1] === GLOBSTAR2) {
              return;
            }
            if (i4 === 0) {
              if (pattern.length > 1) {
                pattern[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i4 + 1];
              } else {
                pattern[i4] = twoStar;
              }
            } else if (i4 === pattern.length - 1) {
              pattern[i4 - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i4 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i4 + 1];
              pattern[i4 + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p3) => p3 !== GLOBSTAR2).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate) re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      match(f5, partial = this.partial) {
        this.debug("match", f5, this.pattern);
        if (this.comment) return false;
        if (this.empty) return f5 === "";
        if (f5 === "/" && partial) return true;
        const options = this.options;
        if (path4.sep !== "/") {
          f5 = f5.split(path4.sep).join("/");
        }
        f5 = f5.split(slashSplit);
        this.debug(this.pattern, "split", f5);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i4 = f5.length - 1; i4 >= 0; i4--) {
          filename = f5[i4];
          if (filename) break;
        }
        for (let i4 = 0; i4 < set.length; i4++) {
          const pattern = set[i4];
          let file = f5;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) return true;
            return !this.negate;
          }
        }
        if (options.flipNegate) return false;
        return this.negate;
      }
      static defaults(def) {
        return minimatch2.defaults(def).Minimatch;
      }
    };
    minimatch2.Minimatch = Minimatch2;
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports2, module2) {
    if (typeof Object.create === "function") {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
var require_inherits = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports2, module2) {
    try {
      util2 = require("util");
      if (typeof util2.inherits !== "function") throw "";
      module2.exports = util2.inherits;
    } catch (e4) {
      module2.exports = require_inherits_browser();
    }
    var util2;
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
var require_common = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports2) {
    exports2.setopts = setopts;
    exports2.ownProp = ownProp;
    exports2.makeAbs = makeAbs;
    exports2.finish = finish;
    exports2.mark = mark;
    exports2.isIgnored = isIgnored;
    exports2.childrenIgnored = childrenIgnored;
    function ownProp(obj, field) {
      return Object.prototype.hasOwnProperty.call(obj, field);
    }
    var fs7 = require("fs");
    var path4 = require("path");
    var minimatch2 = require_minimatch();
    var isAbsolute = require("path").isAbsolute;
    var Minimatch2 = minimatch2.Minimatch;
    function alphasort(a3, b3) {
      return a3.localeCompare(b3, "en");
    }
    function setupIgnores(self2, options) {
      self2.ignore = options.ignore || [];
      if (!Array.isArray(self2.ignore))
        self2.ignore = [self2.ignore];
      if (self2.ignore.length) {
        self2.ignore = self2.ignore.map(ignoreMap);
      }
    }
    function ignoreMap(pattern) {
      var gmatcher = null;
      if (pattern.slice(-3) === "/**") {
        var gpattern = pattern.replace(/(\/\*\*)+$/, "");
        gmatcher = new Minimatch2(gpattern, { dot: true });
      }
      return {
        matcher: new Minimatch2(pattern, { dot: true }),
        gmatcher
      };
    }
    function setopts(self2, pattern, options) {
      if (!options)
        options = {};
      if (options.matchBase && -1 === pattern.indexOf("/")) {
        if (options.noglobstar) {
          throw new Error("base matching requires globstar");
        }
        pattern = "**/" + pattern;
      }
      self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
      if (self2.windowsPathsNoEscape) {
        pattern = pattern.replace(/\\/g, "/");
      }
      self2.silent = !!options.silent;
      self2.pattern = pattern;
      self2.strict = options.strict !== false;
      self2.realpath = !!options.realpath;
      self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
      self2.follow = !!options.follow;
      self2.dot = !!options.dot;
      self2.mark = !!options.mark;
      self2.nodir = !!options.nodir;
      if (self2.nodir)
        self2.mark = true;
      self2.sync = !!options.sync;
      self2.nounique = !!options.nounique;
      self2.nonull = !!options.nonull;
      self2.nosort = !!options.nosort;
      self2.nocase = !!options.nocase;
      self2.stat = !!options.stat;
      self2.noprocess = !!options.noprocess;
      self2.absolute = !!options.absolute;
      self2.fs = options.fs || fs7;
      self2.maxLength = options.maxLength || Infinity;
      self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
      self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
      self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
      setupIgnores(self2, options);
      self2.changedCwd = false;
      var cwd = process.cwd();
      if (!ownProp(options, "cwd"))
        self2.cwd = path4.resolve(cwd);
      else {
        self2.cwd = path4.resolve(options.cwd);
        self2.changedCwd = self2.cwd !== cwd;
      }
      self2.root = options.root || path4.resolve(self2.cwd, "/");
      self2.root = path4.resolve(self2.root);
      self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
      self2.nomount = !!options.nomount;
      if (process.platform === "win32") {
        self2.root = self2.root.replace(/\\/g, "/");
        self2.cwd = self2.cwd.replace(/\\/g, "/");
        self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
      }
      options.nonegate = true;
      options.nocomment = true;
      self2.minimatch = new Minimatch2(pattern, options);
      self2.options = self2.minimatch.options;
    }
    function finish(self2) {
      var nou = self2.nounique;
      var all = nou ? [] : /* @__PURE__ */ Object.create(null);
      for (var i4 = 0, l3 = self2.matches.length; i4 < l3; i4++) {
        var matches = self2.matches[i4];
        if (!matches || Object.keys(matches).length === 0) {
          if (self2.nonull) {
            var literal = self2.minimatch.globSet[i4];
            if (nou)
              all.push(literal);
            else
              all[literal] = true;
          }
        } else {
          var m4 = Object.keys(matches);
          if (nou)
            all.push.apply(all, m4);
          else
            m4.forEach(function(m5) {
              all[m5] = true;
            });
        }
      }
      if (!nou)
        all = Object.keys(all);
      if (!self2.nosort)
        all = all.sort(alphasort);
      if (self2.mark) {
        for (var i4 = 0; i4 < all.length; i4++) {
          all[i4] = self2._mark(all[i4]);
        }
        if (self2.nodir) {
          all = all.filter(function(e4) {
            var notDir = !/\/$/.test(e4);
            var c3 = self2.cache[e4] || self2.cache[makeAbs(self2, e4)];
            if (notDir && c3)
              notDir = c3 !== "DIR" && !Array.isArray(c3);
            return notDir;
          });
        }
      }
      if (self2.ignore.length)
        all = all.filter(function(m5) {
          return !isIgnored(self2, m5);
        });
      self2.found = all;
    }
    function mark(self2, p3) {
      var abs = makeAbs(self2, p3);
      var c3 = self2.cache[abs];
      var m4 = p3;
      if (c3) {
        var isDir = c3 === "DIR" || Array.isArray(c3);
        var slash = p3.slice(-1) === "/";
        if (isDir && !slash)
          m4 += "/";
        else if (!isDir && slash)
          m4 = m4.slice(0, -1);
        if (m4 !== p3) {
          var mabs = makeAbs(self2, m4);
          self2.statCache[mabs] = self2.statCache[abs];
          self2.cache[mabs] = self2.cache[abs];
        }
      }
      return m4;
    }
    function makeAbs(self2, f5) {
      var abs = f5;
      if (f5.charAt(0) === "/") {
        abs = path4.join(self2.root, f5);
      } else if (isAbsolute(f5) || f5 === "") {
        abs = f5;
      } else if (self2.changedCwd) {
        abs = path4.resolve(self2.cwd, f5);
      } else {
        abs = path4.resolve(f5);
      }
      if (process.platform === "win32")
        abs = abs.replace(/\\/g, "/");
      return abs;
    }
    function isIgnored(self2, path5) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return item.matcher.match(path5) || !!(item.gmatcher && item.gmatcher.match(path5));
      });
    }
    function childrenIgnored(self2, path5) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return !!(item.gmatcher && item.gmatcher.match(path5));
      });
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
var require_sync = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports2, module2) {
    module2.exports = globSync;
    globSync.GlobSync = GlobSync;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var Glob = require_glob().Glob;
    var util2 = require("util");
    var path4 = require("path");
    var assert = require("assert");
    var isAbsolute = require("path").isAbsolute;
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    function globSync(pattern, options) {
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      return new GlobSync(pattern, options).found;
    }
    function GlobSync(pattern, options) {
      if (!pattern)
        throw new Error("must provide pattern");
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      if (!(this instanceof GlobSync))
        return new GlobSync(pattern, options);
      setopts(this, pattern, options);
      if (this.noprocess)
        return this;
      var n3 = this.minimatch.set.length;
      this.matches = new Array(n3);
      for (var i4 = 0; i4 < n3; i4++) {
        this._process(this.minimatch.set[i4], i4, false);
      }
      this._finish();
    }
    GlobSync.prototype._finish = function() {
      assert.ok(this instanceof GlobSync);
      if (this.realpath) {
        var self2 = this;
        this.matches.forEach(function(matchset, index6) {
          var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null);
          for (var p3 in matchset) {
            try {
              p3 = self2._makeAbs(p3);
              var real = rp.realpathSync(p3, self2.realpathCache);
              set[real] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p3)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index6, inGlobStar) {
      assert.ok(this instanceof GlobSync);
      var n3 = 0;
      while (typeof pattern[n3] === "string") {
        n3++;
      }
      var prefix2;
      switch (n3) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n3).join("/");
          break;
      }
      var remain = pattern.slice(n3);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) {
        return typeof p3 === "string" ? p3 : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return;
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i4 = 0; i4 < entries.length; i4++) {
        var e4 = entries[i4];
        if (e4.charAt(0) !== "." || dotOk) {
          var m4;
          if (negate && !prefix2) {
            m4 = !e4.match(pn);
          } else {
            m4 = e4.match(pn);
          }
          if (m4)
            matchedEntries.push(e4);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return;
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i4 = 0; i4 < len; i4++) {
          var e4 = matchedEntries[i4];
          if (prefix2) {
            if (prefix2.slice(-1) !== "/")
              e4 = prefix2 + "/" + e4;
            else
              e4 = prefix2 + e4;
          }
          if (e4.charAt(0) === "/" && !this.nomount) {
            e4 = path4.join(this.root, e4);
          }
          this._emitMatch(index6, e4);
        }
        return;
      }
      remain.shift();
      for (var i4 = 0; i4 < len; i4++) {
        var e4 = matchedEntries[i4];
        var newPattern;
        if (prefix2)
          newPattern = [prefix2, e4];
        else
          newPattern = [e4];
        this._process(newPattern.concat(remain), index6, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index6, e4) {
      if (isIgnored(this, e4))
        return;
      var abs = this._makeAbs(e4);
      if (this.mark)
        e4 = this._mark(e4);
      if (this.absolute) {
        e4 = abs;
      }
      if (this.matches[index6][e4])
        return;
      if (this.nodir) {
        var c3 = this.cache[abs];
        if (c3 === "DIR" || Array.isArray(c3))
          return;
      }
      this.matches[index6][e4] = true;
      if (this.stat)
        this._stat(e4);
    };
    GlobSync.prototype._readdirInGlobStar = function(abs) {
      if (this.follow)
        return this._readdir(abs, false);
      var entries;
      var lstat;
      var stat2;
      try {
        lstat = this.fs.lstatSync(abs);
      } catch (er) {
        if (er.code === "ENOENT") {
          return null;
        }
      }
      var isSym = lstat && lstat.isSymbolicLink();
      this.symlinks[abs] = isSym;
      if (!isSym && lstat && !lstat.isDirectory())
        this.cache[abs] = "FILE";
      else
        entries = this._readdir(abs, false);
      return entries;
    };
    GlobSync.prototype._readdir = function(abs, inGlobStar) {
      var entries;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs);
      if (ownProp(this.cache, abs)) {
        var c3 = this.cache[abs];
        if (!c3 || c3 === "FILE")
          return null;
        if (Array.isArray(c3))
          return c3;
      }
      try {
        return this._readdirEntries(abs, this.fs.readdirSync(abs));
      } catch (er) {
        this._readdirError(abs, er);
        return null;
      }
    };
    GlobSync.prototype._readdirEntries = function(abs, entries) {
      if (!this.mark && !this.stat) {
        for (var i4 = 0; i4 < entries.length; i4++) {
          var e4 = entries[i4];
          if (abs === "/")
            e4 = abs + e4;
          else
            e4 = abs + "/" + e4;
          this.cache[e4] = true;
        }
      }
      this.cache[abs] = entries;
      return entries;
    };
    GlobSync.prototype._readdirError = function(f5, er) {
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f5);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            throw error2;
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f5)] = false;
          break;
        default:
          this.cache[this._makeAbs(f5)] = false;
          if (this.strict)
            throw er;
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
    };
    GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false);
      var len = entries.length;
      var isSym = this.symlinks[abs];
      if (isSym && inGlobStar)
        return;
      for (var i4 = 0; i4 < len; i4++) {
        var e4 = entries[i4];
        if (e4.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i4], remainWithoutGlobStar);
        this._process(instead, index6, true);
        var below = gspref.concat(entries[i4], remain);
        this._process(below, index6, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index6) {
      var exists = this._stat(prefix2);
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return;
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path4.join(this.root, prefix2);
        } else {
          prefix2 = path4.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
    };
    GlobSync.prototype._stat = function(f5) {
      var abs = this._makeAbs(f5);
      var needDir = f5.slice(-1) === "/";
      if (f5.length > this.maxLength)
        return false;
      if (!this.stat && ownProp(this.cache, abs)) {
        var c3 = this.cache[abs];
        if (Array.isArray(c3))
          c3 = "DIR";
        if (!needDir || c3 === "DIR")
          return c3;
        if (needDir && c3 === "FILE")
          return false;
      }
      var exists;
      var stat2 = this.statCache[abs];
      if (!stat2) {
        var lstat;
        try {
          lstat = this.fs.lstatSync(abs);
        } catch (er) {
          if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
            this.statCache[abs] = false;
            return false;
          }
        }
        if (lstat && lstat.isSymbolicLink()) {
          try {
            stat2 = this.fs.statSync(abs);
          } catch (er) {
            stat2 = lstat;
          }
        } else {
          stat2 = lstat;
        }
      }
      this.statCache[abs] = stat2;
      var c3 = true;
      if (stat2)
        c3 = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c3;
      if (needDir && c3 === "FILE")
        return false;
      return c3;
    };
    GlobSync.prototype._mark = function(p3) {
      return common.mark(this, p3);
    };
    GlobSync.prototype._makeAbs = function(f5) {
      return common.makeAbs(this, f5);
    };
  }
});

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

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

// ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
var require_inflight = __commonJS({
  "../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports2, module2) {
    var wrappy = require_wrappy();
    var reqs = /* @__PURE__ */ Object.create(null);
    var once = require_once();
    module2.exports = wrappy(inflight);
    function inflight(key, cb) {
      if (reqs[key]) {
        reqs[key].push(cb);
        return null;
      } else {
        reqs[key] = [cb];
        return makeres(key);
      }
    }
    function makeres(key) {
      return once(function RES() {
        var cbs = reqs[key];
        var len = cbs.length;
        var args = slice(arguments);
        try {
          for (var i4 = 0; i4 < len; i4++) {
            cbs[i4].apply(null, args);
          }
        } finally {
          if (cbs.length > len) {
            cbs.splice(0, len);
            process.nextTick(function() {
              RES.apply(null, args);
            });
          } else {
            delete reqs[key];
          }
        }
      });
    }
    function slice(args) {
      var length = args.length;
      var array2 = [];
      for (var i4 = 0; i4 < length; i4++) array2[i4] = args[i4];
      return array2;
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
var require_glob = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports2, module2) {
    module2.exports = glob2;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var inherits = require_inherits();
    var EE = require("events").EventEmitter;
    var path4 = require("path");
    var assert = require("assert");
    var isAbsolute = require("path").isAbsolute;
    var globSync = require_sync();
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var inflight = require_inflight();
    var util2 = require("util");
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    var once = require_once();
    function glob2(pattern, options, cb) {
      if (typeof options === "function") cb = options, options = {};
      if (!options) options = {};
      if (options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return globSync(pattern, options);
      }
      return new Glob(pattern, options, cb);
    }
    glob2.sync = globSync;
    var GlobSync = glob2.GlobSync = globSync.GlobSync;
    glob2.glob = glob2;
    function extend(origin, add) {
      if (add === null || typeof add !== "object") {
        return origin;
      }
      var keys = Object.keys(add);
      var i4 = keys.length;
      while (i4--) {
        origin[keys[i4]] = add[keys[i4]];
      }
      return origin;
    }
    glob2.hasMagic = function(pattern, options_) {
      var options = extend({}, options_);
      options.noprocess = true;
      var g3 = new Glob(pattern, options);
      var set = g3.minimatch.set;
      if (!pattern)
        return false;
      if (set.length > 1)
        return true;
      for (var j3 = 0; j3 < set[0].length; j3++) {
        if (typeof set[0][j3] !== "string")
          return true;
      }
      return false;
    };
    glob2.Glob = Glob;
    inherits(Glob, EE);
    function Glob(pattern, options, cb) {
      if (typeof options === "function") {
        cb = options;
        options = null;
      }
      if (options && options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return new GlobSync(pattern, options);
      }
      if (!(this instanceof Glob))
        return new Glob(pattern, options, cb);
      setopts(this, pattern, options);
      this._didRealPath = false;
      var n3 = this.minimatch.set.length;
      this.matches = new Array(n3);
      if (typeof cb === "function") {
        cb = once(cb);
        this.on("error", cb);
        this.on("end", function(matches) {
          cb(null, matches);
        });
      }
      var self2 = this;
      this._processing = 0;
      this._emitQueue = [];
      this._processQueue = [];
      this.paused = false;
      if (this.noprocess)
        return this;
      if (n3 === 0)
        return done();
      var sync2 = true;
      for (var i4 = 0; i4 < n3; i4++) {
        this._process(this.minimatch.set[i4], i4, false, done);
      }
      sync2 = false;
      function done() {
        --self2._processing;
        if (self2._processing <= 0) {
          if (sync2) {
            process.nextTick(function() {
              self2._finish();
            });
          } else {
            self2._finish();
          }
        }
      }
    }
    Glob.prototype._finish = function() {
      assert(this instanceof Glob);
      if (this.aborted)
        return;
      if (this.realpath && !this._didRealpath)
        return this._realpath();
      common.finish(this);
      this.emit("end", this.found);
    };
    Glob.prototype._realpath = function() {
      if (this._didRealpath)
        return;
      this._didRealpath = true;
      var n3 = this.matches.length;
      if (n3 === 0)
        return this._finish();
      var self2 = this;
      for (var i4 = 0; i4 < this.matches.length; i4++)
        this._realpathSet(i4, next);
      function next() {
        if (--n3 === 0)
          self2._finish();
      }
    };
    Glob.prototype._realpathSet = function(index6, cb) {
      var matchset = this.matches[index6];
      if (!matchset)
        return cb();
      var found = Object.keys(matchset);
      var self2 = this;
      var n3 = found.length;
      if (n3 === 0)
        return cb();
      var set = this.matches[index6] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p3, i4) {
        p3 = self2._makeAbs(p3);
        rp.realpath(p3, self2.realpathCache, function(er, real) {
          if (!er)
            set[real] = true;
          else if (er.syscall === "stat")
            set[p3] = true;
          else
            self2.emit("error", er);
          if (--n3 === 0) {
            self2.matches[index6] = set;
            cb();
          }
        });
      });
    };
    Glob.prototype._mark = function(p3) {
      return common.mark(this, p3);
    };
    Glob.prototype._makeAbs = function(f5) {
      return common.makeAbs(this, f5);
    };
    Glob.prototype.abort = function() {
      this.aborted = true;
      this.emit("abort");
    };
    Glob.prototype.pause = function() {
      if (!this.paused) {
        this.paused = true;
        this.emit("pause");
      }
    };
    Glob.prototype.resume = function() {
      if (this.paused) {
        this.emit("resume");
        this.paused = false;
        if (this._emitQueue.length) {
          var eq = this._emitQueue.slice(0);
          this._emitQueue.length = 0;
          for (var i4 = 0; i4 < eq.length; i4++) {
            var e4 = eq[i4];
            this._emitMatch(e4[0], e4[1]);
          }
        }
        if (this._processQueue.length) {
          var pq = this._processQueue.slice(0);
          this._processQueue.length = 0;
          for (var i4 = 0; i4 < pq.length; i4++) {
            var p3 = pq[i4];
            this._processing--;
            this._process(p3[0], p3[1], p3[2], p3[3]);
          }
        }
      }
    };
    Glob.prototype._process = function(pattern, index6, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index6, inGlobStar, cb]);
        return;
      }
      var n3 = 0;
      while (typeof pattern[n3] === "string") {
        n3++;
      }
      var prefix2;
      switch (n3) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6, cb);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n3).join("/");
          break;
      }
      var remain = pattern.slice(n3);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) {
        return typeof p3 === "string" ? p3 : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return cb();
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i4 = 0; i4 < entries.length; i4++) {
        var e4 = entries[i4];
        if (e4.charAt(0) !== "." || dotOk) {
          var m4;
          if (negate && !prefix2) {
            m4 = !e4.match(pn);
          } else {
            m4 = e4.match(pn);
          }
          if (m4)
            matchedEntries.push(e4);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return cb();
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i4 = 0; i4 < len; i4++) {
          var e4 = matchedEntries[i4];
          if (prefix2) {
            if (prefix2 !== "/")
              e4 = prefix2 + "/" + e4;
            else
              e4 = prefix2 + e4;
          }
          if (e4.charAt(0) === "/" && !this.nomount) {
            e4 = path4.join(this.root, e4);
          }
          this._emitMatch(index6, e4);
        }
        return cb();
      }
      remain.shift();
      for (var i4 = 0; i4 < len; i4++) {
        var e4 = matchedEntries[i4];
        var newPattern;
        if (prefix2) {
          if (prefix2 !== "/")
            e4 = prefix2 + "/" + e4;
          else
            e4 = prefix2 + e4;
        }
        this._process([e4].concat(remain), index6, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index6, e4) {
      if (this.aborted)
        return;
      if (isIgnored(this, e4))
        return;
      if (this.paused) {
        this._emitQueue.push([index6, e4]);
        return;
      }
      var abs = isAbsolute(e4) ? e4 : this._makeAbs(e4);
      if (this.mark)
        e4 = this._mark(e4);
      if (this.absolute)
        e4 = abs;
      if (this.matches[index6][e4])
        return;
      if (this.nodir) {
        var c3 = this.cache[abs];
        if (c3 === "DIR" || Array.isArray(c3))
          return;
      }
      this.matches[index6][e4] = true;
      var st = this.statCache[abs];
      if (st)
        this.emit("stat", e4, st);
      this.emit("match", e4);
    };
    Glob.prototype._readdirInGlobStar = function(abs, cb) {
      if (this.aborted)
        return;
      if (this.follow)
        return this._readdir(abs, false, cb);
      var lstatkey = "lstat\0" + abs;
      var self2 = this;
      var lstatcb = inflight(lstatkey, lstatcb_);
      if (lstatcb)
        self2.fs.lstat(abs, lstatcb);
      function lstatcb_(er, lstat) {
        if (er && er.code === "ENOENT")
          return cb();
        var isSym = lstat && lstat.isSymbolicLink();
        self2.symlinks[abs] = isSym;
        if (!isSym && lstat && !lstat.isDirectory()) {
          self2.cache[abs] = "FILE";
          cb();
        } else
          self2._readdir(abs, false, cb);
      }
    };
    Glob.prototype._readdir = function(abs, inGlobStar, cb) {
      if (this.aborted)
        return;
      cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
      if (!cb)
        return;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs, cb);
      if (ownProp(this.cache, abs)) {
        var c3 = this.cache[abs];
        if (!c3 || c3 === "FILE")
          return cb();
        if (Array.isArray(c3))
          return cb(null, c3);
      }
      var self2 = this;
      self2.fs.readdir(abs, readdirCb(this, abs, cb));
    };
    function readdirCb(self2, abs, cb) {
      return function(er, entries) {
        if (er)
          self2._readdirError(abs, er, cb);
        else
          self2._readdirEntries(abs, entries, cb);
      };
    }
    Glob.prototype._readdirEntries = function(abs, entries, cb) {
      if (this.aborted)
        return;
      if (!this.mark && !this.stat) {
        for (var i4 = 0; i4 < entries.length; i4++) {
          var e4 = entries[i4];
          if (abs === "/")
            e4 = abs + e4;
          else
            e4 = abs + "/" + e4;
          this.cache[e4] = true;
        }
      }
      this.cache[abs] = entries;
      return cb(null, entries);
    };
    Glob.prototype._readdirError = function(f5, er, cb) {
      if (this.aborted)
        return;
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f5);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            this.emit("error", error2);
            this.abort();
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f5)] = false;
          break;
        default:
          this.cache[this._makeAbs(f5)] = false;
          if (this.strict) {
            this.emit("error", er);
            this.abort();
          }
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
      return cb();
    };
    Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false, cb);
      var isSym = this.symlinks[abs];
      var len = entries.length;
      if (isSym && inGlobStar)
        return cb();
      for (var i4 = 0; i4 < len; i4++) {
        var e4 = entries[i4];
        if (e4.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i4], remainWithoutGlobStar);
        this._process(instead, index6, true, cb);
        var below = gspref.concat(entries[i4], remain);
        this._process(below, index6, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index6, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists) {
        self2._processSimple2(prefix2, index6, er, exists, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) {
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return cb();
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path4.join(this.root, prefix2);
        } else {
          prefix2 = path4.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
      cb();
    };
    Glob.prototype._stat = function(f5, cb) {
      var abs = this._makeAbs(f5);
      var needDir = f5.slice(-1) === "/";
      if (f5.length > this.maxLength)
        return cb();
      if (!this.stat && ownProp(this.cache, abs)) {
        var c3 = this.cache[abs];
        if (Array.isArray(c3))
          c3 = "DIR";
        if (!needDir || c3 === "DIR")
          return cb(null, c3);
        if (needDir && c3 === "FILE")
          return cb();
      }
      var exists;
      var stat2 = this.statCache[abs];
      if (stat2 !== void 0) {
        if (stat2 === false)
          return cb(null, stat2);
        else {
          var type = stat2.isDirectory() ? "DIR" : "FILE";
          if (needDir && type === "FILE")
            return cb();
          else
            return cb(null, type, stat2);
        }
      }
      var self2 = this;
      var statcb = inflight("stat\0" + abs, lstatcb_);
      if (statcb)
        self2.fs.lstat(abs, statcb);
      function lstatcb_(er, lstat) {
        if (lstat && lstat.isSymbolicLink()) {
          return self2.fs.stat(abs, function(er2, stat3) {
            if (er2)
              self2._stat2(f5, abs, null, lstat, cb);
            else
              self2._stat2(f5, abs, er2, stat3, cb);
          });
        } else {
          self2._stat2(f5, abs, er, lstat, cb);
        }
      }
    };
    Glob.prototype._stat2 = function(f5, abs, er, stat2, cb) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return cb();
      }
      var needDir = f5.slice(-1) === "/";
      this.statCache[abs] = stat2;
      if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
        return cb(null, false, stat2);
      var c3 = true;
      if (stat2)
        c3 = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c3;
      if (needDir && c3 === "FILE")
        return cb();
      return cb(null, c3, stat2);
    };
  }
});

// src/extensions/getTablesFilterByExtensions.ts
var getTablesFilterByExtensions;
var init_getTablesFilterByExtensions = __esm({
  "src/extensions/getTablesFilterByExtensions.ts"() {
    "use strict";
    getTablesFilterByExtensions = ({
      extensionsFilters,
      dialect: dialect6
    }) => {
      if (extensionsFilters) {
        if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
          return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
        }
      }
      return [];
    };
  }
});

// src/cli/validations/outputs.ts
var withStyle, outputs;
var init_outputs = __esm({
  "src/cli/validations/outputs.ts"() {
    "use strict";
    init_source();
    init_common();
    withStyle = {
      error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
      warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
      errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
      fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
      suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
      info: (str) => `${source_default.grey(str)}`
    };
    outputs = {
      studio: {
        drivers: (param) => withStyle.error(
          `"${param}" is not a valid driver. Available drivers: "pg", "mysql2", "better-sqlite", "libsql", "turso". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noCredentials: () => withStyle.error(
          `Please specify a 'dbCredentials' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noDriver: () => withStyle.error(
          `Please specify a 'driver' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noDialect: () => withStyle.error(
          `Please specify 'dialect' param in config, either of 'postgresql', 'mysql', 'sqlite', turso or singlestore`
        )
      },
      common: {
        ambiguousParams: (command) => withStyle.error(
          `You can't use both --config and other cli options for ${command} command`
        ),
        schema: (command) => withStyle.error(`"--schema" is a required field for ${command} command`)
      },
      postgres: {
        connection: {
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          ),
          awsDataApi: () => withStyle.error(
            "You need to provide 'database', 'secretArn' and 'resourceArn' for Drizzle Kit to connect to AWS Data API"
          )
        }
      },
      mysql: {
        connection: {
          driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          )
        }
      },
      sqlite: {
        connection: {
          driver: () => {
            const listOfDrivers = sqliteDriversLiterals.map((it) => `'${it.value}'`).join(", ");
            return withStyle.error(
              `Either ${listOfDrivers} are available options for 'driver' param`
            );
          },
          url: (driver2) => withStyle.error(
            `"url" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
          ),
          authToken: (driver2) => withStyle.error(
            `"authToken" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
          )
        },
        introspect: {},
        push: {}
      },
      singlestore: {
        connection: {
          driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          )
        }
      }
    };
  }
});

// src/cli/validations/common.ts
var assertCollisions, sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
var init_common = __esm({
  "src/cli/validations/common.ts"() {
    "use strict";
    init_source();
    init_esm();
    init_schemaValidator();
    init_outputs();
    assertCollisions = (command, options, whitelist, remainingKeys) => {
      const { config, ...rest } = options;
      let atLeastOneParam = false;
      for (const key of Object.keys(rest)) {
        if (whitelist.includes(key)) continue;
        atLeastOneParam = atLeastOneParam || rest[key] !== void 0;
      }
      if (!config && atLeastOneParam) {
        return "cli";
      }
      if (!atLeastOneParam) {
        return "config";
      }
      console.log(outputs.common.ambiguousParams(command));
      process.exit(1);
    };
    sqliteDriversLiterals = [
      literalType("d1-http"),
      literalType("expo"),
      literalType("durable-sqlite")
    ];
    postgresqlDriversLiterals = [
      literalType("aws-data-api"),
      literalType("pglite")
    ];
    prefixes = [
      "index",
      "timestamp",
      "supabase",
      "unix",
      "none"
    ];
    prefix = enumType(prefixes);
    {
      const _3 = "";
    }
    casingTypes = ["snake_case", "camelCase"];
    casingType = enumType(casingTypes);
    sqliteDriver = unionType(sqliteDriversLiterals);
    postgresDriver = unionType(postgresqlDriversLiterals);
    driver = unionType([sqliteDriver, postgresDriver]);
    configMigrations = objectType({
      table: stringType().optional(),
      schema: stringType().optional(),
      prefix: prefix.optional().default("index")
    }).optional();
    configCommonSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional(),
      breakpoints: booleanType().optional().default(true),
      verbose: booleanType().optional().default(false),
      driver: driver.optional(),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      migrations: configMigrations,
      dbCredentials: anyType().optional(),
      casing: casingType.optional(),
      sql: booleanType().default(true)
    }).passthrough();
    casing = unionType([literalType("camel"), literalType("preserve")]).default(
      "camel"
    );
    introspectParams = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspect: objectType({
        casing
      }).default({ casing: "camel" })
    });
    configIntrospectCliSchema = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
        "camel"
      )
    });
    configGenerateSchema = objectType({
      schema: unionType([stringType(), stringType().array()]),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true)
    });
    configPushSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      verbose: booleanType().default(false),
      strict: booleanType().default(false),
      out: stringType().optional()
    });
    drivers = ["d1-http", "expo", "aws-data-api", "pglite", "durable-sqlite"];
    wrapParam = (name, param, optional = false, type) => {
      const check2 = `[${source_default.green("\u2713")}]`;
      const cross = `[${source_default.red("x")}]`;
      if (typeof param === "string") {
        if (param.length === 0) {
          return `    ${cross} ${name}: ''`;
        }
        if (type === "secret") {
          return `    ${check2} ${name}: '*****'`;
        } else if (type === "url") {
          return `    ${check2} ${name}: '${param.replace(/(?<=:\/\/[^:\n]*:)([^@]*)/, "****")}'`;
        }
        return `    ${check2} ${name}: '${param}'`;
      }
      if (optional) {
        return source_default.gray(`        ${name}?: `);
      }
      return `    ${cross} ${name}: ${source_default.gray("undefined")}`;
    };
  }
});

// src/cli/validations/cli.ts
var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
var init_cli = __esm({
  "src/cli/validations/cli.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_common();
    cliConfigGenerate = objectType({
      dialect: dialect4.optional(),
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      config: stringType().optional(),
      name: stringType().optional(),
      prefix: prefix.optional(),
      breakpoints: booleanType().optional().default(true),
      custom: booleanType().optional().default(false)
    }).strict();
    pushParams = objectType({
      dialect: dialect4,
      casing: casingType.optional(),
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      verbose: booleanType().optional(),
      strict: booleanType().optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    pullParams = objectType({
      config: stringType().optional(),
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      casing,
      breakpoints: booleanType().optional().default(true),
      migrations: objectType({
        prefix: prefix.optional().default("index")
      }).optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    configCheck = objectType({
      dialect: dialect4.optional(),
      out: stringType().optional()
    });
    cliConfigCheck = intersectionType(
      objectType({
        config: stringType().optional()
      }),
      configCheck
    );
  }
});

// src/cli/validations/gel.ts
var gelCredentials, printConfigConnectionIssues;
var init_gel = __esm({
  "src/cli/validations/gel.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    gelCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o3) => {
        delete o3.driver;
        return o3;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o3) => {
        delete o3.driver;
        return o3;
      }),
      objectType({
        driver: undefinedType()
      }).transform((o3) => {
        return void 0;
      })
    ]);
    printConfigConnectionIssues = (options) => {
      if ("url" in options) {
        let text = `Please provide required params for Gel driver:
`;
        console.log(error(text));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      if ("host" in options || "database" in options) {
        let text = `Please provide required params for Gel driver:
`;
        console.log(error(text));
        console.log(wrapParam("host", options.host));
        console.log(wrapParam("port", options.port, true));
        console.log(wrapParam("user", options.user, true));
        console.log(wrapParam("password", options.password, true, "secret"));
        console.log(wrapParam("database", options.database));
        console.log(wrapParam("tlsSecurity", options.tlsSecurity, true));
        process.exit(1);
      }
      console.log(
        error(
          `Either connection "url" or "host", "database" are required for Gel database connection`
        )
      );
      process.exit(1);
    };
  }
});

// src/cli/validations/libsql.ts
var libSQLCredentials, printConfigConnectionIssues2;
var init_libsql = __esm({
  "src/cli/validations/libsql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    libSQLCredentials = objectType({
      url: stringType().min(1),
      authToken: stringType().min(1).optional()
    });
    printConfigConnectionIssues2 = (options, command) => {
      let text = `Please provide required params for 'turso' dialect:
`;
      console.log(error(text));
      console.log(wrapParam("url", options.url));
      console.log(wrapParam("authToken", options.authToken, true, "secret"));
      process.exit(1);
    };
  }
});

// src/cli/validations/mysql.ts
var mysqlCredentials, printConfigConnectionIssues3;
var init_mysql = __esm({
  "src/cli/validations/mysql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    mysqlCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
    printConfigConnectionIssues3 = (options) => {
      if ("url" in options) {
        let text2 = `Please provide required params for MySQL driver:
`;
        console.log(error(text2));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      let text = `Please provide required params for MySQL driver:
`;
      console.log(error(text));
      console.log(wrapParam("host", options.host));
      console.log(wrapParam("port", options.port, true));
      console.log(wrapParam("user", options.user, true));
      console.log(wrapParam("password", options.password, true, "secret"));
      console.log(wrapParam("database", options.database));
      console.log(wrapParam("ssl", options.ssl, true));
      process.exit(1);
    };
  }
});

// src/cli/validations/postgres.ts
var postgresCredentials, printConfigConnectionIssues4;
var init_postgres = __esm({
  "src/cli/validations/postgres.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    postgresCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          literalType("require"),
          literalType("allow"),
          literalType("prefer"),
          literalType("verify-full"),
          booleanType(),
          objectType({}).passthrough()
        ]).optional()
      }).transform((o3) => {
        delete o3.driver;
        return o3;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o3) => {
        delete o3.driver;
        return o3;
      }),
      objectType({
        driver: literalType("aws-data-api"),
        database: stringType().min(1),
        secretArn: stringType().min(1),
        resourceArn: stringType().min(1)
      }),
      objectType({
        driver: literalType("pglite"),
        url: stringType().min(1)
      })
    ]);
    printConfigConnectionIssues4 = (options) => {
      if (options.driver === "aws-data-api") {
        let text = `Please provide required params for AWS Data API driver:
`;
        console.log(error(text));
        console.log(wrapParam("database", options.database));
        console.log(wrapParam("secretArn", options.secretArn, false, "secret"));
        console.log(wrapParam("resourceArn", options.resourceArn, false, "secret"));
        process.exit(1);
      }
      if ("url" in options) {
        let text = `Please provide required params for Postgres driver:
`;
        console.log(error(text));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      if ("host" in options || "database" in options) {
        let text = `Please provide required params for Postgres driver:
`;
        console.log(error(text));
        console.log(wrapParam("host", options.host));
        console.log(wrapParam("port", options.port, true));
        console.log(wrapParam("user", options.user, true));
        console.log(wrapParam("password", options.password, true, "secret"));
        console.log(wrapParam("database", options.database));
        console.log(wrapParam("ssl", options.ssl, true));
        process.exit(1);
      }
      console.log(
        error(
          `Either connection "url" or "host", "database" are required for PostgreSQL database connection`
        )
      );
      process.exit(1);
    };
  }
});

// src/cli/validations/singlestore.ts
var singlestoreCredentials, printConfigConnectionIssues5;
var init_singlestore = __esm({
  "src/cli/validations/singlestore.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    singlestoreCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
    printConfigConnectionIssues5 = (options) => {
      if ("url" in options) {
        let text2 = `Please provide required params for SingleStore driver:
`;
        console.log(error(text2));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      let text = `Please provide required params for SingleStore driver:
`;
      console.log(error(text));
      console.log(wrapParam("host", options.host));
      console.log(wrapParam("port", options.port, true));
      console.log(wrapParam("user", options.user, true));
      console.log(wrapParam("password", options.password, true, "secret"));
      console.log(wrapParam("database", options.database));
      console.log(wrapParam("ssl", options.ssl, true));
      process.exit(1);
    };
  }
});

// src/cli/validations/sqlite.ts
var sqliteCredentials, printConfigConnectionIssues6;
var init_sqlite = __esm({
  "src/cli/validations/sqlite.ts"() {
    "use strict";
    init_global();
    init_esm();
    init_views();
    init_common();
    sqliteCredentials = unionType([
      objectType({
        driver: literalType("turso"),
        url: stringType().min(1),
        authToken: stringType().min(1).optional()
      }),
      objectType({
        driver: literalType("d1-http"),
        accountId: stringType().min(1),
        databaseId: stringType().min(1),
        token: stringType().min(1)
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o3) => {
        delete o3.driver;
        return o3;
      })
    ]);
    printConfigConnectionIssues6 = (options, command) => {
      const parsedDriver = sqliteDriver.safeParse(options.driver);
      const driver2 = parsedDriver.success ? parsedDriver.data : "";
      if (driver2 === "expo") {
        if (command === "migrate") {
          console.log(
            error(
              `You can't use 'migrate' command with Expo SQLite, please follow migration instructions in our docs - https://orm.drizzle.team/docs/get-started-sqlite#expo-sqlite`
            )
          );
        } else if (command === "studio") {
          console.log(
            error(
              `You can't use 'studio' command with Expo SQLite, please use Expo Plugin https://www.npmjs.com/package/expo-drizzle-studio-plugin`
            )
          );
        } else if (command === "pull") {
          console.log(error("You can't use 'pull' command with Expo SQLite"));
        } else if (command === "push") {
          console.log(error("You can't use 'push' command with Expo SQLite"));
        } else {
          console.log(error("Unexpected error with expo driver \u{1F914}"));
        }
        process.exit(1);
      } else if (driver2 === "d1-http") {
        let text2 = `Please provide required params for D1 HTTP driver:
`;
        console.log(error(text2));
        console.log(wrapParam("accountId", options.accountId));
        console.log(wrapParam("databaseId", options.databaseId));
        console.log(wrapParam("token", options.token, false, "secret"));
        process.exit(1);
      } else if (driver2 === "durable-sqlite") {
        if (command === "migrate") {
          console.log(
            error(
              `You can't use 'migrate' command with SQLite Durable Objects`
            )
          );
        } else if (command === "studio") {
          console.log(
            error(
              `You can't use 'studio' command with SQLite Durable Objects`
            )
          );
        } else if (command === "pull") {
          console.log(error("You can't use 'pull' command with SQLite Durable Objects"));
        } else if (command === "push") {
          console.log(error("You can't use 'push' command with SQLite Durable Objects"));
        } else {
          console.log(error("Unexpected error with SQLite Durable Object driver \u{1F914}"));
        }
        process.exit(1);
      } else {
        softAssertUnreachable(driver2);
      }
      let text = `Please provide required params:
`;
      console.log(error(text));
      console.log(wrapParam("url", options.url));
      process.exit(1);
    };
  }
});

// src/cli/validations/studio.ts
var credentials, studioCliParams, studioConfig;
var init_studio = __esm({
  "src/cli/validations/studio.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_mysql();
    init_postgres();
    init_sqlite();
    credentials = intersectionType(
      postgresCredentials,
      mysqlCredentials,
      sqliteCredentials
    );
    studioCliParams = objectType({
      port: coerce.number().optional().default(4983),
      host: stringType().optional().default("127.0.0.1"),
      config: stringType().optional()
    });
    studioConfig = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional()
    });
  }
});

// src/cli/commands/_es5.ts
var es5_exports = {};
__export(es5_exports, {
  default: () => es5_default
});
var _, es5_default;
var init_es5 = __esm({
  "src/cli/commands/_es5.ts"() {
    "use strict";
    _ = "";
    es5_default = _;
  }
});

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

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

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

// ../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
var require_has_flag = __commonJS({
  "../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports2, module2) {
    "use strict";
    module2.exports = (flag, argv = process.argv) => {
      const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
      const position = argv.indexOf(prefix2 + flag);
      const terminatorPosition = argv.indexOf("--");
      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
    };
  }
});

// ../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js
var require_supports_color = __commonJS({
  "../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    var os3 = require("os");
    var tty2 = require("tty");
    var hasFlag2 = require_has_flag();
    var { env: env3 } = process;
    var flagForceColor2;
    if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
      flagForceColor2 = 0;
    } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
      flagForceColor2 = 1;
    }
    function envForceColor2() {
      if ("FORCE_COLOR" in env3) {
        if (env3.FORCE_COLOR === "true") {
          return 1;
        }
        if (env3.FORCE_COLOR === "false") {
          return 0;
        }
        return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel2(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
      const noFlagForceColor = envForceColor2();
      if (noFlagForceColor !== void 0) {
        flagForceColor2 = noFlagForceColor;
      }
      const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
      if (forceColor === 0) {
        return 0;
      }
      if (sniffFlags) {
        if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
          return 3;
        }
        if (hasFlag2("color=256")) {
          return 2;
        }
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env3.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os3.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env3) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env3) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env3.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env3) {
        const version3 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env3.TERM_PROGRAM) {
          case "iTerm.app":
            return version3 >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env3.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env3) {
        return 1;
      }
      return min;
    }
    function getSupportLevel(stream, options = {}) {
      const level = supportsColor2(stream, {
        streamIsTTY: stream && stream.isTTY,
        ...options
      });
      return translateLevel2(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel({ isTTY: tty2.isatty(1) }),
      stderr: getSupportLevel({ isTTY: tty2.isatty(2) })
    };
  }
});

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

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

// ../node_modules/.pnpm/esbuild-register@3.6.0_esbuild@0.25.5/node_modules/esbuild-register/dist/node.js
var require_node2 = __commonJS({
  "../node_modules/.pnpm/esbuild-register@3.6.0_esbuild@0.25.5/node_modules/esbuild-register/dist/node.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopRequireDefault2(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __markAsModule = (target) => __defProp3(target, "__esModule", { value: true });
    var __commonJS3 = (callback, module22) => () => {
      if (!module22) {
        module22 = { exports: {} };
        callback(module22.exports, module22);
      }
      return module22.exports;
    };
    var __exportStar2 = (target, module22, desc) => {
      if (module22 && typeof module22 === "object" || typeof module22 === "function") {
        for (let key of __getOwnPropNames3(module22))
          if (!__hasOwnProp3.call(target, key) && key !== "default")
            __defProp3(target, key, { get: () => module22[key], enumerable: !(desc = __getOwnPropDesc3(module22, key)) || desc.enumerable });
      }
      return target;
    };
    var __toModule = (module22) => {
      return __exportStar2(__markAsModule(__defProp3(module22 != null ? __create3(__getProtoOf3(module22)) : {}, "default", module22 && module22.__esModule && "default" in module22 ? { get: () => module22.default, enumerable: true } : { value: module22, enumerable: true })), module22);
    };
    var require_base64 = __commonJS3((exports3) => {
      var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
      exports3.encode = function(number2) {
        if (0 <= number2 && number2 < intToCharMap.length) {
          return intToCharMap[number2];
        }
        throw new TypeError("Must be between 0 and 63: " + number2);
      };
      exports3.decode = function(charCode) {
        var bigA = 65;
        var bigZ = 90;
        var littleA = 97;
        var littleZ = 122;
        var zero = 48;
        var nine = 57;
        var plus = 43;
        var slash = 47;
        var littleOffset = 26;
        var numberOffset = 52;
        if (bigA <= charCode && charCode <= bigZ) {
          return charCode - bigA;
        }
        if (littleA <= charCode && charCode <= littleZ) {
          return charCode - littleA + littleOffset;
        }
        if (zero <= charCode && charCode <= nine) {
          return charCode - zero + numberOffset;
        }
        if (charCode == plus) {
          return 62;
        }
        if (charCode == slash) {
          return 63;
        }
        return -1;
      };
    });
    var require_base64_vlq = __commonJS3((exports3) => {
      var base64 = require_base64();
      var VLQ_BASE_SHIFT = 5;
      var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
      var VLQ_BASE_MASK = VLQ_BASE - 1;
      var VLQ_CONTINUATION_BIT = VLQ_BASE;
      function toVLQSigned(aValue) {
        return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
      }
      function fromVLQSigned(aValue) {
        var isNegative = (aValue & 1) === 1;
        var shifted = aValue >> 1;
        return isNegative ? -shifted : shifted;
      }
      exports3.encode = function base64VLQ_encode(aValue) {
        var encoded = "";
        var digit;
        var vlq = toVLQSigned(aValue);
        do {
          digit = vlq & VLQ_BASE_MASK;
          vlq >>>= VLQ_BASE_SHIFT;
          if (vlq > 0) {
            digit |= VLQ_CONTINUATION_BIT;
          }
          encoded += base64.encode(digit);
        } while (vlq > 0);
        return encoded;
      };
      exports3.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
        var strLen = aStr.length;
        var result = 0;
        var shift = 0;
        var continuation, digit;
        do {
          if (aIndex >= strLen) {
            throw new Error("Expected more digits in base 64 VLQ value.");
          }
          digit = base64.decode(aStr.charCodeAt(aIndex++));
          if (digit === -1) {
            throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
          }
          continuation = !!(digit & VLQ_CONTINUATION_BIT);
          digit &= VLQ_BASE_MASK;
          result = result + (digit << shift);
          shift += VLQ_BASE_SHIFT;
        } while (continuation);
        aOutParam.value = fromVLQSigned(result);
        aOutParam.rest = aIndex;
      };
    });
    var require_util4 = __commonJS3((exports3) => {
      function getArg(aArgs, aName, aDefaultValue) {
        if (aName in aArgs) {
          return aArgs[aName];
        } else if (arguments.length === 3) {
          return aDefaultValue;
        } else {
          throw new Error('"' + aName + '" is a required argument.');
        }
      }
      exports3.getArg = getArg;
      var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
      var dataUrlRegexp = /^data:.+\,.+$/;
      function urlParse(aUrl) {
        var match2 = aUrl.match(urlRegexp);
        if (!match2) {
          return null;
        }
        return {
          scheme: match2[1],
          auth: match2[2],
          host: match2[3],
          port: match2[4],
          path: match2[5]
        };
      }
      exports3.urlParse = urlParse;
      function urlGenerate(aParsedUrl) {
        var url = "";
        if (aParsedUrl.scheme) {
          url += aParsedUrl.scheme + ":";
        }
        url += "//";
        if (aParsedUrl.auth) {
          url += aParsedUrl.auth + "@";
        }
        if (aParsedUrl.host) {
          url += aParsedUrl.host;
        }
        if (aParsedUrl.port) {
          url += ":" + aParsedUrl.port;
        }
        if (aParsedUrl.path) {
          url += aParsedUrl.path;
        }
        return url;
      }
      exports3.urlGenerate = urlGenerate;
      function normalize(aPath) {
        var path4 = aPath;
        var url = urlParse(aPath);
        if (url) {
          if (!url.path) {
            return aPath;
          }
          path4 = url.path;
        }
        var isAbsolute = exports3.isAbsolute(path4);
        var parts = path4.split(/\/+/);
        for (var part, up2 = 0, i4 = parts.length - 1; i4 >= 0; i4--) {
          part = parts[i4];
          if (part === ".") {
            parts.splice(i4, 1);
          } else if (part === "..") {
            up2++;
          } else if (up2 > 0) {
            if (part === "") {
              parts.splice(i4 + 1, up2);
              up2 = 0;
            } else {
              parts.splice(i4, 2);
              up2--;
            }
          }
        }
        path4 = parts.join("/");
        if (path4 === "") {
          path4 = isAbsolute ? "/" : ".";
        }
        if (url) {
          url.path = path4;
          return urlGenerate(url);
        }
        return path4;
      }
      exports3.normalize = normalize;
      function join22(aRoot, aPath) {
        if (aRoot === "") {
          aRoot = ".";
        }
        if (aPath === "") {
          aPath = ".";
        }
        var aPathUrl = urlParse(aPath);
        var aRootUrl = urlParse(aRoot);
        if (aRootUrl) {
          aRoot = aRootUrl.path || "/";
        }
        if (aPathUrl && !aPathUrl.scheme) {
          if (aRootUrl) {
            aPathUrl.scheme = aRootUrl.scheme;
          }
          return urlGenerate(aPathUrl);
        }
        if (aPathUrl || aPath.match(dataUrlRegexp)) {
          return aPath;
        }
        if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
          aRootUrl.host = aPath;
          return urlGenerate(aRootUrl);
        }
        var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
        if (aRootUrl) {
          aRootUrl.path = joined;
          return urlGenerate(aRootUrl);
        }
        return joined;
      }
      exports3.join = join22;
      exports3.isAbsolute = function(aPath) {
        return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
      };
      function relative(aRoot, aPath) {
        if (aRoot === "") {
          aRoot = ".";
        }
        aRoot = aRoot.replace(/\/$/, "");
        var level = 0;
        while (aPath.indexOf(aRoot + "/") !== 0) {
          var index6 = aRoot.lastIndexOf("/");
          if (index6 < 0) {
            return aPath;
          }
          aRoot = aRoot.slice(0, index6);
          if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
            return aPath;
          }
          ++level;
        }
        return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
      }
      exports3.relative = relative;
      var supportsNullProto = function() {
        var obj = /* @__PURE__ */ Object.create(null);
        return !("__proto__" in obj);
      }();
      function identity(s4) {
        return s4;
      }
      function toSetString(aStr) {
        if (isProtoString(aStr)) {
          return "$" + aStr;
        }
        return aStr;
      }
      exports3.toSetString = supportsNullProto ? identity : toSetString;
      function fromSetString(aStr) {
        if (isProtoString(aStr)) {
          return aStr.slice(1);
        }
        return aStr;
      }
      exports3.fromSetString = supportsNullProto ? identity : fromSetString;
      function isProtoString(s4) {
        if (!s4) {
          return false;
        }
        var length = s4.length;
        if (length < 9) {
          return false;
        }
        if (s4.charCodeAt(length - 1) !== 95 || s4.charCodeAt(length - 2) !== 95 || s4.charCodeAt(length - 3) !== 111 || s4.charCodeAt(length - 4) !== 116 || s4.charCodeAt(length - 5) !== 111 || s4.charCodeAt(length - 6) !== 114 || s4.charCodeAt(length - 7) !== 112 || s4.charCodeAt(length - 8) !== 95 || s4.charCodeAt(length - 9) !== 95) {
          return false;
        }
        for (var i4 = length - 10; i4 >= 0; i4--) {
          if (s4.charCodeAt(i4) !== 36) {
            return false;
          }
        }
        return true;
      }
      function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
        var cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0 || onlyCompareOriginal) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByOriginalPositions = compareByOriginalPositions;
      function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
        var cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0 || onlyCompareGenerated) {
          return cmp;
        }
        cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
      function strcmp(aStr1, aStr2) {
        if (aStr1 === aStr2) {
          return 0;
        }
        if (aStr1 === null) {
          return 1;
        }
        if (aStr2 === null) {
          return -1;
        }
        if (aStr1 > aStr2) {
          return 1;
        }
        return -1;
      }
      function compareByGeneratedPositionsInflated(mappingA, mappingB) {
        var cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
      function parseSourceMapInput(str) {
        return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
      }
      exports3.parseSourceMapInput = parseSourceMapInput;
      function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
        sourceURL = sourceURL || "";
        if (sourceRoot) {
          if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
            sourceRoot += "/";
          }
          sourceURL = sourceRoot + sourceURL;
        }
        if (sourceMapURL) {
          var parsed = urlParse(sourceMapURL);
          if (!parsed) {
            throw new Error("sourceMapURL could not be parsed");
          }
          if (parsed.path) {
            var index6 = parsed.path.lastIndexOf("/");
            if (index6 >= 0) {
              parsed.path = parsed.path.substring(0, index6 + 1);
            }
          }
          sourceURL = join22(urlGenerate(parsed), sourceURL);
        }
        return normalize(sourceURL);
      }
      exports3.computeSourceURL = computeSourceURL;
    });
    var require_array_set = __commonJS3((exports3) => {
      var util2 = require_util4();
      var has = Object.prototype.hasOwnProperty;
      var hasNativeMap = typeof Map !== "undefined";
      function ArraySet() {
        this._array = [];
        this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
      }
      ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
        var set = new ArraySet();
        for (var i4 = 0, len = aArray.length; i4 < len; i4++) {
          set.add(aArray[i4], aAllowDuplicates);
        }
        return set;
      };
      ArraySet.prototype.size = function ArraySet_size() {
        return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
      };
      ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
        var sStr = hasNativeMap ? aStr : util2.toSetString(aStr);
        var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
        var idx = this._array.length;
        if (!isDuplicate || aAllowDuplicates) {
          this._array.push(aStr);
        }
        if (!isDuplicate) {
          if (hasNativeMap) {
            this._set.set(aStr, idx);
          } else {
            this._set[sStr] = idx;
          }
        }
      };
      ArraySet.prototype.has = function ArraySet_has(aStr) {
        if (hasNativeMap) {
          return this._set.has(aStr);
        } else {
          var sStr = util2.toSetString(aStr);
          return has.call(this._set, sStr);
        }
      };
      ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
        if (hasNativeMap) {
          var idx = this._set.get(aStr);
          if (idx >= 0) {
            return idx;
          }
        } else {
          var sStr = util2.toSetString(aStr);
          if (has.call(this._set, sStr)) {
            return this._set[sStr];
          }
        }
        throw new Error('"' + aStr + '" is not in the set.');
      };
      ArraySet.prototype.at = function ArraySet_at(aIdx) {
        if (aIdx >= 0 && aIdx < this._array.length) {
          return this._array[aIdx];
        }
        throw new Error("No element indexed by " + aIdx);
      };
      ArraySet.prototype.toArray = function ArraySet_toArray() {
        return this._array.slice();
      };
      exports3.ArraySet = ArraySet;
    });
    var require_mapping_list = __commonJS3((exports3) => {
      var util2 = require_util4();
      function generatedPositionAfter(mappingA, mappingB) {
        var lineA = mappingA.generatedLine;
        var lineB = mappingB.generatedLine;
        var columnA = mappingA.generatedColumn;
        var columnB = mappingB.generatedColumn;
        return lineB > lineA || lineB == lineA && columnB >= columnA || util2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
      }
      function MappingList() {
        this._array = [];
        this._sorted = true;
        this._last = { generatedLine: -1, generatedColumn: 0 };
      }
      MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
        this._array.forEach(aCallback, aThisArg);
      };
      MappingList.prototype.add = function MappingList_add(aMapping) {
        if (generatedPositionAfter(this._last, aMapping)) {
          this._last = aMapping;
          this._array.push(aMapping);
        } else {
          this._sorted = false;
          this._array.push(aMapping);
        }
      };
      MappingList.prototype.toArray = function MappingList_toArray() {
        if (!this._sorted) {
          this._array.sort(util2.compareByGeneratedPositionsInflated);
          this._sorted = true;
        }
        return this._array;
      };
      exports3.MappingList = MappingList;
    });
    var require_source_map_generator = __commonJS3((exports3) => {
      var base64VLQ = require_base64_vlq();
      var util2 = require_util4();
      var ArraySet = require_array_set().ArraySet;
      var MappingList = require_mapping_list().MappingList;
      function SourceMapGenerator(aArgs) {
        if (!aArgs) {
          aArgs = {};
        }
        this._file = util2.getArg(aArgs, "file", null);
        this._sourceRoot = util2.getArg(aArgs, "sourceRoot", null);
        this._skipValidation = util2.getArg(aArgs, "skipValidation", false);
        this._sources = new ArraySet();
        this._names = new ArraySet();
        this._mappings = new MappingList();
        this._sourcesContents = null;
      }
      SourceMapGenerator.prototype._version = 3;
      SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
        var sourceRoot = aSourceMapConsumer.sourceRoot;
        var generator = new SourceMapGenerator({
          file: aSourceMapConsumer.file,
          sourceRoot
        });
        aSourceMapConsumer.eachMapping(function(mapping) {
          var newMapping = {
            generated: {
              line: mapping.generatedLine,
              column: mapping.generatedColumn
            }
          };
          if (mapping.source != null) {
            newMapping.source = mapping.source;
            if (sourceRoot != null) {
              newMapping.source = util2.relative(sourceRoot, newMapping.source);
            }
            newMapping.original = {
              line: mapping.originalLine,
              column: mapping.originalColumn
            };
            if (mapping.name != null) {
              newMapping.name = mapping.name;
            }
          }
          generator.addMapping(newMapping);
        });
        aSourceMapConsumer.sources.forEach(function(sourceFile) {
          var sourceRelative = sourceFile;
          if (sourceRoot !== null) {
            sourceRelative = util2.relative(sourceRoot, sourceFile);
          }
          if (!generator._sources.has(sourceRelative)) {
            generator._sources.add(sourceRelative);
          }
          var content = aSourceMapConsumer.sourceContentFor(sourceFile);
          if (content != null) {
            generator.setSourceContent(sourceFile, content);
          }
        });
        return generator;
      };
      SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
        var generated = util2.getArg(aArgs, "generated");
        var original = util2.getArg(aArgs, "original", null);
        var source = util2.getArg(aArgs, "source", null);
        var name = util2.getArg(aArgs, "name", null);
        if (!this._skipValidation) {
          this._validateMapping(generated, original, source, name);
        }
        if (source != null) {
          source = String(source);
          if (!this._sources.has(source)) {
            this._sources.add(source);
          }
        }
        if (name != null) {
          name = String(name);
          if (!this._names.has(name)) {
            this._names.add(name);
          }
        }
        this._mappings.add({
          generatedLine: generated.line,
          generatedColumn: generated.column,
          originalLine: original != null && original.line,
          originalColumn: original != null && original.column,
          source,
          name
        });
      };
      SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
        var source = aSourceFile;
        if (this._sourceRoot != null) {
          source = util2.relative(this._sourceRoot, source);
        }
        if (aSourceContent != null) {
          if (!this._sourcesContents) {
            this._sourcesContents = /* @__PURE__ */ Object.create(null);
          }
          this._sourcesContents[util2.toSetString(source)] = aSourceContent;
        } else if (this._sourcesContents) {
          delete this._sourcesContents[util2.toSetString(source)];
          if (Object.keys(this._sourcesContents).length === 0) {
            this._sourcesContents = null;
          }
        }
      };
      SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
        var sourceFile = aSourceFile;
        if (aSourceFile == null) {
          if (aSourceMapConsumer.file == null) {
            throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);
          }
          sourceFile = aSourceMapConsumer.file;
        }
        var sourceRoot = this._sourceRoot;
        if (sourceRoot != null) {
          sourceFile = util2.relative(sourceRoot, sourceFile);
        }
        var newSources = new ArraySet();
        var newNames = new ArraySet();
        this._mappings.unsortedForEach(function(mapping) {
          if (mapping.source === sourceFile && mapping.originalLine != null) {
            var original = aSourceMapConsumer.originalPositionFor({
              line: mapping.originalLine,
              column: mapping.originalColumn
            });
            if (original.source != null) {
              mapping.source = original.source;
              if (aSourceMapPath != null) {
                mapping.source = util2.join(aSourceMapPath, mapping.source);
              }
              if (sourceRoot != null) {
                mapping.source = util2.relative(sourceRoot, mapping.source);
              }
              mapping.originalLine = original.line;
              mapping.originalColumn = original.column;
              if (original.name != null) {
                mapping.name = original.name;
              }
            }
          }
          var source = mapping.source;
          if (source != null && !newSources.has(source)) {
            newSources.add(source);
          }
          var name = mapping.name;
          if (name != null && !newNames.has(name)) {
            newNames.add(name);
          }
        }, this);
        this._sources = newSources;
        this._names = newNames;
        aSourceMapConsumer.sources.forEach(function(sourceFile2) {
          var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
          if (content != null) {
            if (aSourceMapPath != null) {
              sourceFile2 = util2.join(aSourceMapPath, sourceFile2);
            }
            if (sourceRoot != null) {
              sourceFile2 = util2.relative(sourceRoot, sourceFile2);
            }
            this.setSourceContent(sourceFile2, content);
          }
        }, this);
      };
      SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
        if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
          throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");
        }
        if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
          return;
        } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
          return;
        } else {
          throw new Error("Invalid mapping: " + JSON.stringify({
            generated: aGenerated,
            source: aSource,
            original: aOriginal,
            name: aName
          }));
        }
      };
      SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
        var previousGeneratedColumn = 0;
        var previousGeneratedLine = 1;
        var previousOriginalColumn = 0;
        var previousOriginalLine = 0;
        var previousName = 0;
        var previousSource = 0;
        var result = "";
        var next;
        var mapping;
        var nameIdx;
        var sourceIdx;
        var mappings = this._mappings.toArray();
        for (var i4 = 0, len = mappings.length; i4 < len; i4++) {
          mapping = mappings[i4];
          next = "";
          if (mapping.generatedLine !== previousGeneratedLine) {
            previousGeneratedColumn = 0;
            while (mapping.generatedLine !== previousGeneratedLine) {
              next += ";";
              previousGeneratedLine++;
            }
          } else {
            if (i4 > 0) {
              if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i4 - 1])) {
                continue;
              }
              next += ",";
            }
          }
          next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
          previousGeneratedColumn = mapping.generatedColumn;
          if (mapping.source != null) {
            sourceIdx = this._sources.indexOf(mapping.source);
            next += base64VLQ.encode(sourceIdx - previousSource);
            previousSource = sourceIdx;
            next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
            previousOriginalLine = mapping.originalLine - 1;
            next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
            previousOriginalColumn = mapping.originalColumn;
            if (mapping.name != null) {
              nameIdx = this._names.indexOf(mapping.name);
              next += base64VLQ.encode(nameIdx - previousName);
              previousName = nameIdx;
            }
          }
          result += next;
        }
        return result;
      };
      SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
        return aSources.map(function(source) {
          if (!this._sourcesContents) {
            return null;
          }
          if (aSourceRoot != null) {
            source = util2.relative(aSourceRoot, source);
          }
          var key = util2.toSetString(source);
          return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
        }, this);
      };
      SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
        var map22 = {
          version: this._version,
          sources: this._sources.toArray(),
          names: this._names.toArray(),
          mappings: this._serializeMappings()
        };
        if (this._file != null) {
          map22.file = this._file;
        }
        if (this._sourceRoot != null) {
          map22.sourceRoot = this._sourceRoot;
        }
        if (this._sourcesContents) {
          map22.sourcesContent = this._generateSourcesContent(map22.sources, map22.sourceRoot);
        }
        return map22;
      };
      SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
        return JSON.stringify(this.toJSON());
      };
      exports3.SourceMapGenerator = SourceMapGenerator;
    });
    var require_binary_search = __commonJS3((exports3) => {
      exports3.GREATEST_LOWER_BOUND = 1;
      exports3.LEAST_UPPER_BOUND = 2;
      function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
        var mid = Math.floor((aHigh - aLow) / 2) + aLow;
        var cmp = aCompare(aNeedle, aHaystack[mid], true);
        if (cmp === 0) {
          return mid;
        } else if (cmp > 0) {
          if (aHigh - mid > 1) {
            return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
          }
          if (aBias == exports3.LEAST_UPPER_BOUND) {
            return aHigh < aHaystack.length ? aHigh : -1;
          } else {
            return mid;
          }
        } else {
          if (mid - aLow > 1) {
            return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
          }
          if (aBias == exports3.LEAST_UPPER_BOUND) {
            return mid;
          } else {
            return aLow < 0 ? -1 : aLow;
          }
        }
      }
      exports3.search = function search(aNeedle, aHaystack, aCompare, aBias) {
        if (aHaystack.length === 0) {
          return -1;
        }
        var index6 = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports3.GREATEST_LOWER_BOUND);
        if (index6 < 0) {
          return -1;
        }
        while (index6 - 1 >= 0) {
          if (aCompare(aHaystack[index6], aHaystack[index6 - 1], true) !== 0) {
            break;
          }
          --index6;
        }
        return index6;
      };
    });
    var require_quick_sort = __commonJS3((exports3) => {
      function swap(ary, x4, y2) {
        var temp = ary[x4];
        ary[x4] = ary[y2];
        ary[y2] = temp;
      }
      function randomIntInRange(low, high) {
        return Math.round(low + Math.random() * (high - low));
      }
      function doQuickSort(ary, comparator, p3, r4) {
        if (p3 < r4) {
          var pivotIndex = randomIntInRange(p3, r4);
          var i4 = p3 - 1;
          swap(ary, pivotIndex, r4);
          var pivot = ary[r4];
          for (var j3 = p3; j3 < r4; j3++) {
            if (comparator(ary[j3], pivot) <= 0) {
              i4 += 1;
              swap(ary, i4, j3);
            }
          }
          swap(ary, i4 + 1, j3);
          var q3 = i4 + 1;
          doQuickSort(ary, comparator, p3, q3 - 1);
          doQuickSort(ary, comparator, q3 + 1, r4);
        }
      }
      exports3.quickSort = function(ary, comparator) {
        doQuickSort(ary, comparator, 0, ary.length - 1);
      };
    });
    var require_source_map_consumer = __commonJS3((exports3) => {
      var util2 = require_util4();
      var binarySearch = require_binary_search();
      var ArraySet = require_array_set().ArraySet;
      var base64VLQ = require_base64_vlq();
      var quickSort = require_quick_sort().quickSort;
      function SourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
      }
      SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
        return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
      };
      SourceMapConsumer.prototype._version = 3;
      SourceMapConsumer.prototype.__generatedMappings = null;
      Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
        configurable: true,
        enumerable: true,
        get: function() {
          if (!this.__generatedMappings) {
            this._parseMappings(this._mappings, this.sourceRoot);
          }
          return this.__generatedMappings;
        }
      });
      SourceMapConsumer.prototype.__originalMappings = null;
      Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
        configurable: true,
        enumerable: true,
        get: function() {
          if (!this.__originalMappings) {
            this._parseMappings(this._mappings, this.sourceRoot);
          }
          return this.__originalMappings;
        }
      });
      SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index6) {
        var c3 = aStr.charAt(index6);
        return c3 === ";" || c3 === ",";
      };
      SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        throw new Error("Subclasses must implement _parseMappings");
      };
      SourceMapConsumer.GENERATED_ORDER = 1;
      SourceMapConsumer.ORIGINAL_ORDER = 2;
      SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
      SourceMapConsumer.LEAST_UPPER_BOUND = 2;
      SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
        var context = aContext || null;
        var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
        var mappings;
        switch (order) {
          case SourceMapConsumer.GENERATED_ORDER:
            mappings = this._generatedMappings;
            break;
          case SourceMapConsumer.ORIGINAL_ORDER:
            mappings = this._originalMappings;
            break;
          default:
            throw new Error("Unknown order of iteration.");
        }
        var sourceRoot = this.sourceRoot;
        mappings.map(function(mapping) {
          var source = mapping.source === null ? null : this._sources.at(mapping.source);
          source = util2.computeSourceURL(sourceRoot, source, this._sourceMapURL);
          return {
            source,
            generatedLine: mapping.generatedLine,
            generatedColumn: mapping.generatedColumn,
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            name: mapping.name === null ? null : this._names.at(mapping.name)
          };
        }, this).forEach(aCallback, context);
      };
      SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
        var line = util2.getArg(aArgs, "line");
        var needle = {
          source: util2.getArg(aArgs, "source"),
          originalLine: line,
          originalColumn: util2.getArg(aArgs, "column", 0)
        };
        needle.source = this._findSourceIndex(needle.source);
        if (needle.source < 0) {
          return [];
        }
        var mappings = [];
        var index6 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
        if (index6 >= 0) {
          var mapping = this._originalMappings[index6];
          if (aArgs.column === void 0) {
            var originalLine = mapping.originalLine;
            while (mapping && mapping.originalLine === originalLine) {
              mappings.push({
                line: util2.getArg(mapping, "generatedLine", null),
                column: util2.getArg(mapping, "generatedColumn", null),
                lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
              });
              mapping = this._originalMappings[++index6];
            }
          } else {
            var originalColumn = mapping.originalColumn;
            while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
              mappings.push({
                line: util2.getArg(mapping, "generatedLine", null),
                column: util2.getArg(mapping, "generatedColumn", null),
                lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
              });
              mapping = this._originalMappings[++index6];
            }
          }
        }
        return mappings;
      };
      exports3.SourceMapConsumer = SourceMapConsumer;
      function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        var version3 = util2.getArg(sourceMap, "version");
        var sources = util2.getArg(sourceMap, "sources");
        var names = util2.getArg(sourceMap, "names", []);
        var sourceRoot = util2.getArg(sourceMap, "sourceRoot", null);
        var sourcesContent = util2.getArg(sourceMap, "sourcesContent", null);
        var mappings = util2.getArg(sourceMap, "mappings");
        var file = util2.getArg(sourceMap, "file", null);
        if (version3 != this._version) {
          throw new Error("Unsupported version: " + version3);
        }
        if (sourceRoot) {
          sourceRoot = util2.normalize(sourceRoot);
        }
        sources = sources.map(String).map(util2.normalize).map(function(source) {
          return sourceRoot && util2.isAbsolute(sourceRoot) && util2.isAbsolute(source) ? util2.relative(sourceRoot, source) : source;
        });
        this._names = ArraySet.fromArray(names.map(String), true);
        this._sources = ArraySet.fromArray(sources, true);
        this._absoluteSources = this._sources.toArray().map(function(s4) {
          return util2.computeSourceURL(sourceRoot, s4, aSourceMapURL);
        });
        this.sourceRoot = sourceRoot;
        this.sourcesContent = sourcesContent;
        this._mappings = mappings;
        this._sourceMapURL = aSourceMapURL;
        this.file = file;
      }
      BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
      BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
      BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
        var relativeSource = aSource;
        if (this.sourceRoot != null) {
          relativeSource = util2.relative(this.sourceRoot, relativeSource);
        }
        if (this._sources.has(relativeSource)) {
          return this._sources.indexOf(relativeSource);
        }
        var i4;
        for (i4 = 0; i4 < this._absoluteSources.length; ++i4) {
          if (this._absoluteSources[i4] == aSource) {
            return i4;
          }
        }
        return -1;
      };
      BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
        var smc = Object.create(BasicSourceMapConsumer.prototype);
        var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
        var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
        smc.sourceRoot = aSourceMap._sourceRoot;
        smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
        smc.file = aSourceMap._file;
        smc._sourceMapURL = aSourceMapURL;
        smc._absoluteSources = smc._sources.toArray().map(function(s4) {
          return util2.computeSourceURL(smc.sourceRoot, s4, aSourceMapURL);
        });
        var generatedMappings = aSourceMap._mappings.toArray().slice();
        var destGeneratedMappings = smc.__generatedMappings = [];
        var destOriginalMappings = smc.__originalMappings = [];
        for (var i4 = 0, length = generatedMappings.length; i4 < length; i4++) {
          var srcMapping = generatedMappings[i4];
          var destMapping = new Mapping();
          destMapping.generatedLine = srcMapping.generatedLine;
          destMapping.generatedColumn = srcMapping.generatedColumn;
          if (srcMapping.source) {
            destMapping.source = sources.indexOf(srcMapping.source);
            destMapping.originalLine = srcMapping.originalLine;
            destMapping.originalColumn = srcMapping.originalColumn;
            if (srcMapping.name) {
              destMapping.name = names.indexOf(srcMapping.name);
            }
            destOriginalMappings.push(destMapping);
          }
          destGeneratedMappings.push(destMapping);
        }
        quickSort(smc.__originalMappings, util2.compareByOriginalPositions);
        return smc;
      };
      BasicSourceMapConsumer.prototype._version = 3;
      Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
        get: function() {
          return this._absoluteSources.slice();
        }
      });
      function Mapping() {
        this.generatedLine = 0;
        this.generatedColumn = 0;
        this.source = null;
        this.originalLine = null;
        this.originalColumn = null;
        this.name = null;
      }
      BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        var generatedLine = 1;
        var previousGeneratedColumn = 0;
        var previousOriginalLine = 0;
        var previousOriginalColumn = 0;
        var previousSource = 0;
        var previousName = 0;
        var length = aStr.length;
        var index6 = 0;
        var cachedSegments = {};
        var temp = {};
        var originalMappings = [];
        var generatedMappings = [];
        var mapping, str, segment, end, value;
        while (index6 < length) {
          if (aStr.charAt(index6) === ";") {
            generatedLine++;
            index6++;
            previousGeneratedColumn = 0;
          } else if (aStr.charAt(index6) === ",") {
            index6++;
          } else {
            mapping = new Mapping();
            mapping.generatedLine = generatedLine;
            for (end = index6; end < length; end++) {
              if (this._charIsMappingSeparator(aStr, end)) {
                break;
              }
            }
            str = aStr.slice(index6, end);
            segment = cachedSegments[str];
            if (segment) {
              index6 += str.length;
            } else {
              segment = [];
              while (index6 < end) {
                base64VLQ.decode(aStr, index6, temp);
                value = temp.value;
                index6 = temp.rest;
                segment.push(value);
              }
              if (segment.length === 2) {
                throw new Error("Found a source, but no line and column");
              }
              if (segment.length === 3) {
                throw new Error("Found a source and line, but no column");
              }
              cachedSegments[str] = segment;
            }
            mapping.generatedColumn = previousGeneratedColumn + segment[0];
            previousGeneratedColumn = mapping.generatedColumn;
            if (segment.length > 1) {
              mapping.source = previousSource + segment[1];
              previousSource += segment[1];
              mapping.originalLine = previousOriginalLine + segment[2];
              previousOriginalLine = mapping.originalLine;
              mapping.originalLine += 1;
              mapping.originalColumn = previousOriginalColumn + segment[3];
              previousOriginalColumn = mapping.originalColumn;
              if (segment.length > 4) {
                mapping.name = previousName + segment[4];
                previousName += segment[4];
              }
            }
            generatedMappings.push(mapping);
            if (typeof mapping.originalLine === "number") {
              originalMappings.push(mapping);
            }
          }
        }
        quickSort(generatedMappings, util2.compareByGeneratedPositionsDeflated);
        this.__generatedMappings = generatedMappings;
        quickSort(originalMappings, util2.compareByOriginalPositions);
        this.__originalMappings = originalMappings;
      };
      BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
        if (aNeedle[aLineName] <= 0) {
          throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
        }
        if (aNeedle[aColumnName] < 0) {
          throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
        }
        return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
      };
      BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
        for (var index6 = 0; index6 < this._generatedMappings.length; ++index6) {
          var mapping = this._generatedMappings[index6];
          if (index6 + 1 < this._generatedMappings.length) {
            var nextMapping = this._generatedMappings[index6 + 1];
            if (mapping.generatedLine === nextMapping.generatedLine) {
              mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
              continue;
            }
          }
          mapping.lastGeneratedColumn = Infinity;
        }
      };
      BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
        var needle = {
          generatedLine: util2.getArg(aArgs, "line"),
          generatedColumn: util2.getArg(aArgs, "column")
        };
        var index6 = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
        if (index6 >= 0) {
          var mapping = this._generatedMappings[index6];
          if (mapping.generatedLine === needle.generatedLine) {
            var source = util2.getArg(mapping, "source", null);
            if (source !== null) {
              source = this._sources.at(source);
              source = util2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
            }
            var name = util2.getArg(mapping, "name", null);
            if (name !== null) {
              name = this._names.at(name);
            }
            return {
              source,
              line: util2.getArg(mapping, "originalLine", null),
              column: util2.getArg(mapping, "originalColumn", null),
              name
            };
          }
        }
        return {
          source: null,
          line: null,
          column: null,
          name: null
        };
      };
      BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
        if (!this.sourcesContent) {
          return false;
        }
        return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
          return sc == null;
        });
      };
      BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
        if (!this.sourcesContent) {
          return null;
        }
        var index6 = this._findSourceIndex(aSource);
        if (index6 >= 0) {
          return this.sourcesContent[index6];
        }
        var relativeSource = aSource;
        if (this.sourceRoot != null) {
          relativeSource = util2.relative(this.sourceRoot, relativeSource);
        }
        var url;
        if (this.sourceRoot != null && (url = util2.urlParse(this.sourceRoot))) {
          var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
          if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
            return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
          }
          if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) {
            return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
          }
        }
        if (nullOnMissing) {
          return null;
        } else {
          throw new Error('"' + relativeSource + '" is not in the SourceMap.');
        }
      };
      BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
        var source = util2.getArg(aArgs, "source");
        source = this._findSourceIndex(source);
        if (source < 0) {
          return {
            line: null,
            column: null,
            lastColumn: null
          };
        }
        var needle = {
          source,
          originalLine: util2.getArg(aArgs, "line"),
          originalColumn: util2.getArg(aArgs, "column")
        };
        var index6 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
        if (index6 >= 0) {
          var mapping = this._originalMappings[index6];
          if (mapping.source === needle.source) {
            return {
              line: util2.getArg(mapping, "generatedLine", null),
              column: util2.getArg(mapping, "generatedColumn", null),
              lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
            };
          }
        }
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      };
      exports3.BasicSourceMapConsumer = BasicSourceMapConsumer;
      function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        var version3 = util2.getArg(sourceMap, "version");
        var sections = util2.getArg(sourceMap, "sections");
        if (version3 != this._version) {
          throw new Error("Unsupported version: " + version3);
        }
        this._sources = new ArraySet();
        this._names = new ArraySet();
        var lastOffset = {
          line: -1,
          column: 0
        };
        this._sections = sections.map(function(s4) {
          if (s4.url) {
            throw new Error("Support for url field in sections not implemented.");
          }
          var offset = util2.getArg(s4, "offset");
          var offsetLine = util2.getArg(offset, "line");
          var offsetColumn = util2.getArg(offset, "column");
          if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
            throw new Error("Section offsets must be ordered and non-overlapping.");
          }
          lastOffset = offset;
          return {
            generatedOffset: {
              generatedLine: offsetLine + 1,
              generatedColumn: offsetColumn + 1
            },
            consumer: new SourceMapConsumer(util2.getArg(s4, "map"), aSourceMapURL)
          };
        });
      }
      IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
      IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
      IndexedSourceMapConsumer.prototype._version = 3;
      Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
        get: function() {
          var sources = [];
          for (var i4 = 0; i4 < this._sections.length; i4++) {
            for (var j3 = 0; j3 < this._sections[i4].consumer.sources.length; j3++) {
              sources.push(this._sections[i4].consumer.sources[j3]);
            }
          }
          return sources;
        }
      });
      IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
        var needle = {
          generatedLine: util2.getArg(aArgs, "line"),
          generatedColumn: util2.getArg(aArgs, "column")
        };
        var sectionIndex = binarySearch.search(needle, this._sections, function(needle2, section2) {
          var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine;
          if (cmp) {
            return cmp;
          }
          return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
        });
        var section = this._sections[sectionIndex];
        if (!section) {
          return {
            source: null,
            line: null,
            column: null,
            name: null
          };
        }
        return section.consumer.originalPositionFor({
          line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
          column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
          bias: aArgs.bias
        });
      };
      IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
        return this._sections.every(function(s4) {
          return s4.consumer.hasContentsOfAllSources();
        });
      };
      IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
        for (var i4 = 0; i4 < this._sections.length; i4++) {
          var section = this._sections[i4];
          var content = section.consumer.sourceContentFor(aSource, true);
          if (content) {
            return content;
          }
        }
        if (nullOnMissing) {
          return null;
        } else {
          throw new Error('"' + aSource + '" is not in the SourceMap.');
        }
      };
      IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
        for (var i4 = 0; i4 < this._sections.length; i4++) {
          var section = this._sections[i4];
          if (section.consumer._findSourceIndex(util2.getArg(aArgs, "source")) === -1) {
            continue;
          }
          var generatedPosition = section.consumer.generatedPositionFor(aArgs);
          if (generatedPosition) {
            var ret = {
              line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
              column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
            };
            return ret;
          }
        }
        return {
          line: null,
          column: null
        };
      };
      IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        this.__generatedMappings = [];
        this.__originalMappings = [];
        for (var i4 = 0; i4 < this._sections.length; i4++) {
          var section = this._sections[i4];
          var sectionMappings = section.consumer._generatedMappings;
          for (var j3 = 0; j3 < sectionMappings.length; j3++) {
            var mapping = sectionMappings[j3];
            var source = section.consumer._sources.at(mapping.source);
            source = util2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
            this._sources.add(source);
            source = this._sources.indexOf(source);
            var name = null;
            if (mapping.name) {
              name = section.consumer._names.at(mapping.name);
              this._names.add(name);
              name = this._names.indexOf(name);
            }
            var adjustedMapping = {
              source,
              generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
              generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
              originalLine: mapping.originalLine,
              originalColumn: mapping.originalColumn,
              name
            };
            this.__generatedMappings.push(adjustedMapping);
            if (typeof adjustedMapping.originalLine === "number") {
              this.__originalMappings.push(adjustedMapping);
            }
          }
        }
        quickSort(this.__generatedMappings, util2.compareByGeneratedPositionsDeflated);
        quickSort(this.__originalMappings, util2.compareByOriginalPositions);
      };
      exports3.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
    });
    var require_source_node = __commonJS3((exports3) => {
      var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
      var util2 = require_util4();
      var REGEX_NEWLINE = /(\r?\n)/;
      var NEWLINE_CODE = 10;
      var isSourceNode = "$$$isSourceNode$$$";
      function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
        this.children = [];
        this.sourceContents = {};
        this.line = aLine == null ? null : aLine;
        this.column = aColumn == null ? null : aColumn;
        this.source = aSource == null ? null : aSource;
        this.name = aName == null ? null : aName;
        this[isSourceNode] = true;
        if (aChunks != null)
          this.add(aChunks);
      }
      SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
        var node = new SourceNode();
        var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
        var remainingLinesIndex = 0;
        var shiftNextLine = function() {
          var lineContents = getNextLine();
          var newLine = getNextLine() || "";
          return lineContents + newLine;
          function getNextLine() {
            return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
          }
        };
        var lastGeneratedLine = 1, lastGeneratedColumn = 0;
        var lastMapping = null;
        aSourceMapConsumer.eachMapping(function(mapping) {
          if (lastMapping !== null) {
            if (lastGeneratedLine < mapping.generatedLine) {
              addMappingWithCode(lastMapping, shiftNextLine());
              lastGeneratedLine++;
              lastGeneratedColumn = 0;
            } else {
              var nextLine = remainingLines[remainingLinesIndex] || "";
              var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
              remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
              lastGeneratedColumn = mapping.generatedColumn;
              addMappingWithCode(lastMapping, code);
              lastMapping = mapping;
              return;
            }
          }
          while (lastGeneratedLine < mapping.generatedLine) {
            node.add(shiftNextLine());
            lastGeneratedLine++;
          }
          if (lastGeneratedColumn < mapping.generatedColumn) {
            var nextLine = remainingLines[remainingLinesIndex] || "";
            node.add(nextLine.substr(0, mapping.generatedColumn));
            remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
            lastGeneratedColumn = mapping.generatedColumn;
          }
          lastMapping = mapping;
        }, this);
        if (remainingLinesIndex < remainingLines.length) {
          if (lastMapping) {
            addMappingWithCode(lastMapping, shiftNextLine());
          }
          node.add(remainingLines.splice(remainingLinesIndex).join(""));
        }
        aSourceMapConsumer.sources.forEach(function(sourceFile) {
          var content = aSourceMapConsumer.sourceContentFor(sourceFile);
          if (content != null) {
            if (aRelativePath != null) {
              sourceFile = util2.join(aRelativePath, sourceFile);
            }
            node.setSourceContent(sourceFile, content);
          }
        });
        return node;
        function addMappingWithCode(mapping, code) {
          if (mapping === null || mapping.source === void 0) {
            node.add(code);
          } else {
            var source = aRelativePath ? util2.join(aRelativePath, mapping.source) : mapping.source;
            node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
          }
        }
      };
      SourceNode.prototype.add = function SourceNode_add(aChunk) {
        if (Array.isArray(aChunk)) {
          aChunk.forEach(function(chunk) {
            this.add(chunk);
          }, this);
        } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
          if (aChunk) {
            this.children.push(aChunk);
          }
        } else {
          throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
        }
        return this;
      };
      SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
        if (Array.isArray(aChunk)) {
          for (var i4 = aChunk.length - 1; i4 >= 0; i4--) {
            this.prepend(aChunk[i4]);
          }
        } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
          this.children.unshift(aChunk);
        } else {
          throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
        }
        return this;
      };
      SourceNode.prototype.walk = function SourceNode_walk(aFn) {
        var chunk;
        for (var i4 = 0, len = this.children.length; i4 < len; i4++) {
          chunk = this.children[i4];
          if (chunk[isSourceNode]) {
            chunk.walk(aFn);
          } else {
            if (chunk !== "") {
              aFn(chunk, {
                source: this.source,
                line: this.line,
                column: this.column,
                name: this.name
              });
            }
          }
        }
      };
      SourceNode.prototype.join = function SourceNode_join(aSep) {
        var newChildren;
        var i4;
        var len = this.children.length;
        if (len > 0) {
          newChildren = [];
          for (i4 = 0; i4 < len - 1; i4++) {
            newChildren.push(this.children[i4]);
            newChildren.push(aSep);
          }
          newChildren.push(this.children[i4]);
          this.children = newChildren;
        }
        return this;
      };
      SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
        var lastChild = this.children[this.children.length - 1];
        if (lastChild[isSourceNode]) {
          lastChild.replaceRight(aPattern, aReplacement);
        } else if (typeof lastChild === "string") {
          this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
        } else {
          this.children.push("".replace(aPattern, aReplacement));
        }
        return this;
      };
      SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
        this.sourceContents[util2.toSetString(aSourceFile)] = aSourceContent;
      };
      SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
        for (var i4 = 0, len = this.children.length; i4 < len; i4++) {
          if (this.children[i4][isSourceNode]) {
            this.children[i4].walkSourceContents(aFn);
          }
        }
        var sources = Object.keys(this.sourceContents);
        for (var i4 = 0, len = sources.length; i4 < len; i4++) {
          aFn(util2.fromSetString(sources[i4]), this.sourceContents[sources[i4]]);
        }
      };
      SourceNode.prototype.toString = function SourceNode_toString() {
        var str = "";
        this.walk(function(chunk) {
          str += chunk;
        });
        return str;
      };
      SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
        var generated = {
          code: "",
          line: 1,
          column: 0
        };
        var map22 = new SourceMapGenerator(aArgs);
        var sourceMappingActive = false;
        var lastOriginalSource = null;
        var lastOriginalLine = null;
        var lastOriginalColumn = null;
        var lastOriginalName = null;
        this.walk(function(chunk, original) {
          generated.code += chunk;
          if (original.source !== null && original.line !== null && original.column !== null) {
            if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
              map22.addMapping({
                source: original.source,
                original: {
                  line: original.line,
                  column: original.column
                },
                generated: {
                  line: generated.line,
                  column: generated.column
                },
                name: original.name
              });
            }
            lastOriginalSource = original.source;
            lastOriginalLine = original.line;
            lastOriginalColumn = original.column;
            lastOriginalName = original.name;
            sourceMappingActive = true;
          } else if (sourceMappingActive) {
            map22.addMapping({
              generated: {
                line: generated.line,
                column: generated.column
              }
            });
            lastOriginalSource = null;
            sourceMappingActive = false;
          }
          for (var idx = 0, length = chunk.length; idx < length; idx++) {
            if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
              generated.line++;
              generated.column = 0;
              if (idx + 1 === length) {
                lastOriginalSource = null;
                sourceMappingActive = false;
              } else if (sourceMappingActive) {
                map22.addMapping({
                  source: original.source,
                  original: {
                    line: original.line,
                    column: original.column
                  },
                  generated: {
                    line: generated.line,
                    column: generated.column
                  },
                  name: original.name
                });
              }
            } else {
              generated.column++;
            }
          }
        });
        this.walkSourceContents(function(sourceFile, sourceContent) {
          map22.setSourceContent(sourceFile, sourceContent);
        });
        return { code: generated.code, map: map22 };
      };
      exports3.SourceNode = SourceNode;
    });
    var require_source_map = __commonJS3((exports3) => {
      exports3.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
      exports3.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
      exports3.SourceNode = require_source_node().SourceNode;
    });
    var require_buffer_from = __commonJS3((exports3, module22) => {
      var toString = Object.prototype.toString;
      var isModern = typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function";
      function isArrayBuffer(input) {
        return toString.call(input).slice(8, -1) === "ArrayBuffer";
      }
      function fromArrayBuffer(obj, byteOffset, length) {
        byteOffset >>>= 0;
        var maxLength = obj.byteLength - byteOffset;
        if (maxLength < 0) {
          throw new RangeError("'offset' is out of bounds");
        }
        if (length === void 0) {
          length = maxLength;
        } else {
          length >>>= 0;
          if (length > maxLength) {
            throw new RangeError("'length' is out of bounds");
          }
        }
        return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)));
      }
      function fromString(string2, encoding) {
        if (typeof encoding !== "string" || encoding === "") {
          encoding = "utf8";
        }
        if (!Buffer.isEncoding(encoding)) {
          throw new TypeError('"encoding" must be a valid string encoding');
        }
        return isModern ? Buffer.from(string2, encoding) : new Buffer(string2, encoding);
      }
      function bufferFrom(value, encodingOrOffset, length) {
        if (typeof value === "number") {
          throw new TypeError('"value" argument must not be a number');
        }
        if (isArrayBuffer(value)) {
          return fromArrayBuffer(value, encodingOrOffset, length);
        }
        if (typeof value === "string") {
          return fromString(value, encodingOrOffset);
        }
        return isModern ? Buffer.from(value) : new Buffer(value);
      }
      module22.exports = bufferFrom;
    });
    var require_source_map_support = __commonJS3((exports3, module22) => {
      var SourceMapConsumer = require_source_map().SourceMapConsumer;
      var path4 = require("path");
      var fs32;
      try {
        fs32 = require("fs");
        if (!fs32.existsSync || !fs32.readFileSync) {
          fs32 = null;
        }
      } catch (err2) {
      }
      var bufferFrom = require_buffer_from();
      function dynamicRequire(mod, request) {
        return mod.require(request);
      }
      var errorFormatterInstalled = false;
      var uncaughtShimInstalled = false;
      var emptyCacheBetweenOperations = false;
      var environment = "auto";
      var fileContentsCache = {};
      var sourceMapCache = {};
      var reSourceMap = /^data:application\/json[^,]+base64,/;
      var retrieveFileHandlers = [];
      var retrieveMapHandlers = [];
      function isInBrowser() {
        if (environment === "browser")
          return true;
        if (environment === "node")
          return false;
        return typeof window !== "undefined" && typeof XMLHttpRequest === "function" && !(window.require && window.module && window.process && window.process.type === "renderer");
      }
      function hasGlobalProcessEventEmitter() {
        return typeof process === "object" && process !== null && typeof process.on === "function";
      }
      function handlerExec(list) {
        return function(arg) {
          for (var i4 = 0; i4 < list.length; i4++) {
            var ret = list[i4](arg);
            if (ret) {
              return ret;
            }
          }
          return null;
        };
      }
      var retrieveFile = handlerExec(retrieveFileHandlers);
      retrieveFileHandlers.push(function(path22) {
        path22 = path22.trim();
        if (/^file:/.test(path22)) {
          path22 = path22.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
            return drive ? "" : "/";
          });
        }
        if (path22 in fileContentsCache) {
          return fileContentsCache[path22];
        }
        var contents = "";
        try {
          if (!fs32) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", path22, false);
            xhr.send(null);
            if (xhr.readyState === 4 && xhr.status === 200) {
              contents = xhr.responseText;
            }
          } else if (fs32.existsSync(path22)) {
            contents = fs32.readFileSync(path22, "utf8");
          }
        } catch (er) {
        }
        return fileContentsCache[path22] = contents;
      });
      function supportRelativeURL(file, url) {
        if (!file)
          return url;
        var dir = path4.dirname(file);
        var match2 = /^\w+:\/\/[^\/]*/.exec(dir);
        var protocol = match2 ? match2[0] : "";
        var startPath = dir.slice(protocol.length);
        if (protocol && /^\/\w\:/.test(startPath)) {
          protocol += "/";
          return protocol + path4.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
        }
        return protocol + path4.resolve(dir.slice(protocol.length), url);
      }
      function retrieveSourceMapURL(source) {
        var fileData;
        if (isInBrowser()) {
          try {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", source, false);
            xhr.send(null);
            fileData = xhr.readyState === 4 ? xhr.responseText : null;
            var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap");
            if (sourceMapHeader) {
              return sourceMapHeader;
            }
          } catch (e4) {
          }
        }
        fileData = retrieveFile(source);
        var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
        var lastMatch, match2;
        while (match2 = re.exec(fileData))
          lastMatch = match2;
        if (!lastMatch)
          return null;
        return lastMatch[1];
      }
      var retrieveSourceMap = handlerExec(retrieveMapHandlers);
      retrieveMapHandlers.push(function(source) {
        var sourceMappingURL = retrieveSourceMapURL(source);
        if (!sourceMappingURL)
          return null;
        var sourceMapData;
        if (reSourceMap.test(sourceMappingURL)) {
          var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
          sourceMapData = bufferFrom(rawData, "base64").toString();
          sourceMappingURL = source;
        } else {
          sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
          sourceMapData = retrieveFile(sourceMappingURL);
        }
        if (!sourceMapData) {
          return null;
        }
        return {
          url: sourceMappingURL,
          map: sourceMapData
        };
      });
      function mapSourcePosition(position) {
        var sourceMap = sourceMapCache[position.source];
        if (!sourceMap) {
          var urlAndMap = retrieveSourceMap(position.source);
          if (urlAndMap) {
            sourceMap = sourceMapCache[position.source] = {
              url: urlAndMap.url,
              map: new SourceMapConsumer(urlAndMap.map)
            };
            if (sourceMap.map.sourcesContent) {
              sourceMap.map.sources.forEach(function(source, i4) {
                var contents = sourceMap.map.sourcesContent[i4];
                if (contents) {
                  var url = supportRelativeURL(sourceMap.url, source);
                  fileContentsCache[url] = contents;
                }
              });
            }
          } else {
            sourceMap = sourceMapCache[position.source] = {
              url: null,
              map: null
            };
          }
        }
        if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === "function") {
          var originalPosition = sourceMap.map.originalPositionFor(position);
          if (originalPosition.source !== null) {
            originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
            return originalPosition;
          }
        }
        return position;
      }
      function mapEvalOrigin(origin) {
        var match2 = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
        if (match2) {
          var position = mapSourcePosition({
            source: match2[2],
            line: +match2[3],
            column: match2[4] - 1
          });
          return "eval at " + match2[1] + " (" + position.source + ":" + position.line + ":" + (position.column + 1) + ")";
        }
        match2 = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
        if (match2) {
          return "eval at " + match2[1] + " (" + mapEvalOrigin(match2[2]) + ")";
        }
        return origin;
      }
      function CallSiteToString() {
        var fileName;
        var fileLocation = "";
        if (this.isNative()) {
          fileLocation = "native";
        } else {
          fileName = this.getScriptNameOrSourceURL();
          if (!fileName && this.isEval()) {
            fileLocation = this.getEvalOrigin();
            fileLocation += ", ";
          }
          if (fileName) {
            fileLocation += fileName;
          } else {
            fileLocation += "<anonymous>";
          }
          var lineNumber = this.getLineNumber();
          if (lineNumber != null) {
            fileLocation += ":" + lineNumber;
            var columnNumber = this.getColumnNumber();
            if (columnNumber) {
              fileLocation += ":" + columnNumber;
            }
          }
        }
        var line = "";
        var functionName = this.getFunctionName();
        var addSuffix = true;
        var isConstructor = this.isConstructor();
        var isMethodCall = !(this.isToplevel() || isConstructor);
        if (isMethodCall) {
          var typeName = this.getTypeName();
          if (typeName === "[object Object]") {
            typeName = "null";
          }
          var methodName = this.getMethodName();
          if (functionName) {
            if (typeName && functionName.indexOf(typeName) != 0) {
              line += typeName + ".";
            }
            line += functionName;
            if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
              line += " [as " + methodName + "]";
            }
          } else {
            line += typeName + "." + (methodName || "<anonymous>");
          }
        } else if (isConstructor) {
          line += "new " + (functionName || "<anonymous>");
        } else if (functionName) {
          line += functionName;
        } else {
          line += fileLocation;
          addSuffix = false;
        }
        if (addSuffix) {
          line += " (" + fileLocation + ")";
        }
        return line;
      }
      function cloneCallSite(frame) {
        var object = {};
        Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
          object[name] = /^(?:is|get)/.test(name) ? function() {
            return frame[name].call(frame);
          } : frame[name];
        });
        object.toString = CallSiteToString;
        return object;
      }
      function wrapCallSite(frame, state2) {
        if (state2 === void 0) {
          state2 = { nextPosition: null, curPosition: null };
        }
        if (frame.isNative()) {
          state2.curPosition = null;
          return frame;
        }
        var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
        if (source) {
          var line = frame.getLineNumber();
          var column11 = frame.getColumnNumber() - 1;
          var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
          var headerLength = noHeader.test(process.version) ? 0 : 62;
          if (line === 1 && column11 > headerLength && !isInBrowser() && !frame.isEval()) {
            column11 -= headerLength;
          }
          var position = mapSourcePosition({
            source,
            line,
            column: column11
          });
          state2.curPosition = position;
          frame = cloneCallSite(frame);
          var originalFunctionName = frame.getFunctionName;
          frame.getFunctionName = function() {
            if (state2.nextPosition == null) {
              return originalFunctionName();
            }
            return state2.nextPosition.name || originalFunctionName();
          };
          frame.getFileName = function() {
            return position.source;
          };
          frame.getLineNumber = function() {
            return position.line;
          };
          frame.getColumnNumber = function() {
            return position.column + 1;
          };
          frame.getScriptNameOrSourceURL = function() {
            return position.source;
          };
          return frame;
        }
        var origin = frame.isEval() && frame.getEvalOrigin();
        if (origin) {
          origin = mapEvalOrigin(origin);
          frame = cloneCallSite(frame);
          frame.getEvalOrigin = function() {
            return origin;
          };
          return frame;
        }
        return frame;
      }
      function prepareStackTrace(error2, stack) {
        if (emptyCacheBetweenOperations) {
          fileContentsCache = {};
          sourceMapCache = {};
        }
        var name = error2.name || "Error";
        var message = error2.message || "";
        var errorString = name + ": " + message;
        var state2 = { nextPosition: null, curPosition: null };
        var processedStack = [];
        for (var i4 = stack.length - 1; i4 >= 0; i4--) {
          processedStack.push("\n    at " + wrapCallSite(stack[i4], state2));
          state2.nextPosition = state2.curPosition;
        }
        state2.curPosition = state2.nextPosition = null;
        return errorString + processedStack.reverse().join("");
      }
      function getErrorSource(error2) {
        var match2 = /\n    at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error2.stack);
        if (match2) {
          var source = match2[1];
          var line = +match2[2];
          var column11 = +match2[3];
          var contents = fileContentsCache[source];
          if (!contents && fs32 && fs32.existsSync(source)) {
            try {
              contents = fs32.readFileSync(source, "utf8");
            } catch (er) {
              contents = "";
            }
          }
          if (contents) {
            var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
            if (code) {
              return source + ":" + line + "\n" + code + "\n" + new Array(column11).join(" ") + "^";
            }
          }
        }
        return null;
      }
      function printErrorAndExit(error2) {
        var source = getErrorSource(error2);
        if (process.stderr._handle && process.stderr._handle.setBlocking) {
          process.stderr._handle.setBlocking(true);
        }
        if (source) {
          console.error();
          console.error(source);
        }
        console.error(error2.stack);
        process.exit(1);
      }
      function shimEmitUncaughtException() {
        var origEmit = process.emit;
        process.emit = function(type) {
          if (type === "uncaughtException") {
            var hasStack = arguments[1] && arguments[1].stack;
            var hasListeners = this.listeners(type).length > 0;
            if (hasStack && !hasListeners) {
              return printErrorAndExit(arguments[1]);
            }
          }
          return origEmit.apply(this, arguments);
        };
      }
      var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
      var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
      exports3.wrapCallSite = wrapCallSite;
      exports3.getErrorSource = getErrorSource;
      exports3.mapSourcePosition = mapSourcePosition;
      exports3.retrieveSourceMap = retrieveSourceMap;
      exports3.install = function(options) {
        options = options || {};
        if (options.environment) {
          environment = options.environment;
          if (["node", "browser", "auto"].indexOf(environment) === -1) {
            throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}");
          }
        }
        if (options.retrieveFile) {
          if (options.overrideRetrieveFile) {
            retrieveFileHandlers.length = 0;
          }
          retrieveFileHandlers.unshift(options.retrieveFile);
        }
        if (options.retrieveSourceMap) {
          if (options.overrideRetrieveSourceMap) {
            retrieveMapHandlers.length = 0;
          }
          retrieveMapHandlers.unshift(options.retrieveSourceMap);
        }
        if (options.hookRequire && !isInBrowser()) {
          var Module = dynamicRequire(module22, "module");
          var $compile = Module.prototype._compile;
          if (!$compile.__sourceMapSupport) {
            Module.prototype._compile = function(content, filename) {
              fileContentsCache[filename] = content;
              sourceMapCache[filename] = void 0;
              return $compile.call(this, content, filename);
            };
            Module.prototype._compile.__sourceMapSupport = true;
          }
        }
        if (!emptyCacheBetweenOperations) {
          emptyCacheBetweenOperations = "emptyCacheBetweenOperations" in options ? options.emptyCacheBetweenOperations : false;
        }
        if (!errorFormatterInstalled) {
          errorFormatterInstalled = true;
          Error.prepareStackTrace = prepareStackTrace;
        }
        if (!uncaughtShimInstalled) {
          var installHandler = "handleUncaughtExceptions" in options ? options.handleUncaughtExceptions : true;
          try {
            var worker_threads = dynamicRequire(module22, "worker_threads");
            if (worker_threads.isMainThread === false) {
              installHandler = false;
            }
          } catch (e4) {
          }
          if (installHandler && hasGlobalProcessEventEmitter()) {
            uncaughtShimInstalled = true;
            shimEmitUncaughtException();
          }
        }
      };
      exports3.resetRetrieveHandlers = function() {
        retrieveFileHandlers.length = 0;
        retrieveMapHandlers.length = 0;
        retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
        retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
        retrieveSourceMap = handlerExec(retrieveMapHandlers);
        retrieveFile = handlerExec(retrieveFileHandlers);
      };
    });
    var require_node_modules_regexp = __commonJS3((exports3, module22) => {
      "use strict";
      module22.exports = /^(?:.*[\\\/])?node_modules(?:[\\\/].*)?$/;
    });
    var require_lib3 = __commonJS3((exports3, module22) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", {
        value: true
      });
      exports3.addHook = addHook2;
      var _module = _interopRequireDefault(require("module"));
      var _path = _interopRequireDefault(require("path"));
      var _nodeModulesRegexp = _interopRequireDefault(require_node_modules_regexp());
      function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : { default: obj };
      }
      var Module = module22.constructor.length > 1 ? module22.constructor : _module.default;
      var HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes is easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
      function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
        if (typeof filename !== "string") {
          return false;
        }
        if (exts.indexOf(_path.default.extname(filename)) === -1) {
          return false;
        }
        const resolvedFilename = _path.default.resolve(filename);
        if (ignoreNodeModules && _nodeModulesRegexp.default.test(resolvedFilename)) {
          return false;
        }
        if (matcher && typeof matcher === "function") {
          return !!matcher(resolvedFilename);
        }
        return true;
      }
      function addHook2(hook, opts = {}) {
        let reverted = false;
        const loaders = [];
        const oldLoaders = [];
        let exts;
        const originalJSLoader = Module._extensions[".js"];
        const matcher = opts.matcher || null;
        const ignoreNodeModules = opts.ignoreNodeModules !== false;
        exts = opts.extensions || opts.exts || opts.extension || opts.ext || [".js"];
        if (!Array.isArray(exts)) {
          exts = [exts];
        }
        exts.forEach((ext2) => {
          if (typeof ext2 !== "string") {
            throw new TypeError(`Invalid Extension: ${ext2}`);
          }
          const oldLoader = Module._extensions[ext2] || originalJSLoader;
          oldLoaders[ext2] = oldLoader;
          loaders[ext2] = Module._extensions[ext2] = function newLoader(mod, filename) {
            let compile;
            if (!reverted) {
              if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
                compile = mod._compile;
                mod._compile = function _compile(code) {
                  mod._compile = compile;
                  const newCode = hook(code, filename);
                  if (typeof newCode !== "string") {
                    throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
                  }
                  return mod._compile(newCode, filename);
                };
              }
            }
            oldLoader(mod, filename);
          };
        });
        return function revert() {
          if (reverted)
            return;
          reverted = true;
          exts.forEach((ext2) => {
            if (Module._extensions[ext2] === loaders[ext2]) {
              Module._extensions[ext2] = oldLoaders[ext2];
            }
          });
        };
      }
    });
    var require_lib22 = __commonJS3((exports3, module22) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", {
        value: true
      });
      exports3.default = void 0;
      var _fs = _interopRequireDefault(require("fs"));
      var _path = _interopRequireDefault(require("path"));
      function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : { default: obj };
      }
      function asyncGeneratorStep(gen, resolve2, reject, _next, _throw, key, arg) {
        try {
          var info2 = gen[key](arg);
          var value = info2.value;
        } catch (error2) {
          reject(error2);
          return;
        }
        if (info2.done) {
          resolve2(value);
        } else {
          Promise.resolve(value).then(_next, _throw);
        }
      }
      function _asyncToGenerator(fn) {
        return function() {
          var self2 = this, args = arguments;
          return new Promise(function(resolve2, reject) {
            var gen = fn.apply(self2, args);
            function _next(value) {
              asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "next", value);
            }
            function _throw(err2) {
              asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "throw", err2);
            }
            _next(void 0);
          });
        };
      }
      var readFile2 = (fp) => new Promise((resolve2, reject) => {
        _fs.default.readFile(fp, "utf8", (err2, data) => {
          if (err2)
            return reject(err2);
          resolve2(data);
        });
      });
      var readFileSync3 = (fp) => {
        return _fs.default.readFileSync(fp, "utf8");
      };
      var pathExists = (fp) => new Promise((resolve2) => {
        _fs.default.access(fp, (err2) => {
          resolve2(!err2);
        });
      });
      var pathExistsSync = _fs.default.existsSync;
      var JoyCon2 = class {
        constructor({
          files,
          cwd = process.cwd(),
          stopDir,
          packageKey,
          parseJSON = JSON.parse
        } = {}) {
          this.options = {
            files,
            cwd,
            stopDir,
            packageKey,
            parseJSON
          };
          this.existsCache = /* @__PURE__ */ new Map();
          this.loaders = /* @__PURE__ */ new Set();
          this.packageJsonCache = /* @__PURE__ */ new Map();
        }
        addLoader(loader) {
          this.loaders.add(loader);
          return this;
        }
        removeLoader(name) {
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = void 0;
          try {
            for (var _iterator = this.loaders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              const loader = _step.value;
              if (name && loader.name === name) {
                this.loaders.delete(loader);
              }
            }
          } catch (err2) {
            _didIteratorError = true;
            _iteratorError = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
          return this;
        }
        recusivelyResolve(options) {
          var _this = this;
          return _asyncToGenerator(function* () {
            if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
              return null;
            }
            var _iteratorNormalCompletion4 = true;
            var _didIteratorError4 = false;
            var _iteratorError4 = void 0;
            try {
              for (var _iterator4 = options.files[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                const filename = _step4.value;
                const file = _path.default.resolve(options.cwd, filename);
                const exists = process.env.NODE_ENV !== "test" && _this.existsCache.has(file) ? _this.existsCache.get(file) : yield pathExists(file);
                _this.existsCache.set(file, exists);
                if (exists) {
                  if (!options.packageKey || _path.default.basename(file) !== "package.json") {
                    return file;
                  }
                  const data = require(file);
                  delete require.cache[file];
                  const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
                  if (hasPackageKey) {
                    _this.packageJsonCache.set(file, data);
                    return file;
                  }
                }
                continue;
              }
            } catch (err2) {
              _didIteratorError4 = true;
              _iteratorError4 = err2;
            } finally {
              try {
                if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
                  _iterator4.return();
                }
              } finally {
                if (_didIteratorError4) {
                  throw _iteratorError4;
                }
              }
            }
            return _this.recusivelyResolve(Object.assign({}, options, {
              cwd: _path.default.dirname(options.cwd)
            }));
          })();
        }
        recusivelyResolveSync(options) {
          if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
            return null;
          }
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = void 0;
          try {
            for (var _iterator2 = options.files[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              const filename = _step2.value;
              const file = _path.default.resolve(options.cwd, filename);
              const exists = process.env.NODE_ENV !== "test" && this.existsCache.has(file) ? this.existsCache.get(file) : pathExistsSync(file);
              this.existsCache.set(file, exists);
              if (exists) {
                if (!options.packageKey || _path.default.basename(file) !== "package.json") {
                  return file;
                }
                const data = require(file);
                delete require.cache[file];
                const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
                if (hasPackageKey) {
                  this.packageJsonCache.set(file, data);
                  return file;
                }
              }
              continue;
            }
          } catch (err2) {
            _didIteratorError2 = true;
            _iteratorError2 = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                _iterator2.return();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
          return this.recusivelyResolveSync(Object.assign({}, options, {
            cwd: _path.default.dirname(options.cwd)
          }));
        }
        resolve(...args) {
          var _this2 = this;
          return _asyncToGenerator(function* () {
            const options = _this2.normalizeOptions(args);
            return _this2.recusivelyResolve(options);
          })();
        }
        resolveSync(...args) {
          const options = this.normalizeOptions(args);
          return this.recusivelyResolveSync(options);
        }
        load(...args) {
          var _this3 = this;
          return _asyncToGenerator(function* () {
            const options = _this3.normalizeOptions(args);
            const filepath = yield _this3.recusivelyResolve(options);
            if (filepath) {
              const loader = _this3.findLoader(filepath);
              if (loader) {
                return {
                  path: filepath,
                  data: yield loader.load(filepath)
                };
              }
              const extname2 = _path.default.extname(filepath).slice(1);
              if (extname2 === "js") {
                delete require.cache[filepath];
                return {
                  path: filepath,
                  data: require(filepath)
                };
              }
              if (extname2 === "json") {
                if (_this3.packageJsonCache.has(filepath)) {
                  return {
                    path: filepath,
                    data: _this3.packageJsonCache.get(filepath)[options.packageKey]
                  };
                }
                const data = _this3.options.parseJSON(yield readFile2(filepath));
                return {
                  path: filepath,
                  data
                };
              }
              return {
                path: filepath,
                data: yield readFile2(filepath)
              };
            }
            return {};
          })();
        }
        loadSync(...args) {
          const options = this.normalizeOptions(args);
          const filepath = this.recusivelyResolveSync(options);
          if (filepath) {
            const loader = this.findLoader(filepath);
            if (loader) {
              return {
                path: filepath,
                data: loader.loadSync(filepath)
              };
            }
            const extname2 = _path.default.extname(filepath).slice(1);
            if (extname2 === "js") {
              delete require.cache[filepath];
              return {
                path: filepath,
                data: require(filepath)
              };
            }
            if (extname2 === "json") {
              if (this.packageJsonCache.has(filepath)) {
                return {
                  path: filepath,
                  data: this.packageJsonCache.get(filepath)[options.packageKey]
                };
              }
              const data = this.options.parseJSON(readFileSync3(filepath));
              return {
                path: filepath,
                data
              };
            }
            return {
              path: filepath,
              data: readFileSync3(filepath)
            };
          }
          return {};
        }
        findLoader(filepath) {
          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = void 0;
          try {
            for (var _iterator3 = this.loaders[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              const loader = _step3.value;
              if (loader.test && loader.test.test(filepath)) {
                return loader;
              }
            }
          } catch (err2) {
            _didIteratorError3 = true;
            _iteratorError3 = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
                _iterator3.return();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }
          return null;
        }
        clearCache() {
          this.existsCache.clear();
          this.packageJsonCache.clear();
          return this;
        }
        normalizeOptions(args) {
          const options = Object.assign({}, this.options);
          if (Object.prototype.toString.call(args[0]) === "[object Object]") {
            Object.assign(options, args[0]);
          } else {
            if (args[0]) {
              options.files = args[0];
            }
            if (args[1]) {
              options.cwd = args[1];
            }
            if (args[2]) {
              options.stopDir = args[2];
            }
          }
          options.cwd = _path.default.resolve(options.cwd);
          options.stopDir = options.stopDir ? _path.default.resolve(options.stopDir) : _path.default.parse(options.cwd).root;
          if (!options.files || options.files.length === 0) {
            throw new Error("[joycon] files must be an non-empty array!");
          }
          options.__normalized__ = true;
          return options;
        }
      };
      exports3.default = JoyCon2;
      module22.exports = JoyCon2;
      module22.exports.default = JoyCon2;
    });
    var require_filesystem = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.removeExtension = exports3.fileExistsAsync = exports3.readJsonFromDiskAsync = exports3.readJsonFromDiskSync = exports3.fileExistsSync = void 0;
      var fs32 = require("fs");
      function fileExistsSync(path4) {
        if (!fs32.existsSync(path4)) {
          return false;
        }
        try {
          var stats = fs32.statSync(path4);
          return stats.isFile();
        } catch (err2) {
          return false;
        }
      }
      exports3.fileExistsSync = fileExistsSync;
      function readJsonFromDiskSync(packageJsonPath) {
        if (!fs32.existsSync(packageJsonPath)) {
          return void 0;
        }
        return require(packageJsonPath);
      }
      exports3.readJsonFromDiskSync = readJsonFromDiskSync;
      function readJsonFromDiskAsync(path4, callback) {
        fs32.readFile(path4, "utf8", function(err2, result) {
          if (err2 || !result) {
            return callback();
          }
          var json = JSON.parse(result);
          return callback(void 0, json);
        });
      }
      exports3.readJsonFromDiskAsync = readJsonFromDiskAsync;
      function fileExistsAsync(path22, callback2) {
        fs32.stat(path22, function(err2, stats) {
          if (err2) {
            return callback2(void 0, false);
          }
          callback2(void 0, stats ? stats.isFile() : false);
        });
      }
      exports3.fileExistsAsync = fileExistsAsync;
      function removeExtension(path4) {
        return path4.substring(0, path4.lastIndexOf(".")) || path4;
      }
      exports3.removeExtension = removeExtension;
    });
    var require_mapping_entry = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.getAbsoluteMappingEntries = void 0;
      var path4 = require("path");
      function getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll) {
        var sortedKeys = sortByLongestPrefix(Object.keys(paths));
        var absolutePaths = [];
        for (var _i = 0, sortedKeys_1 = sortedKeys; _i < sortedKeys_1.length; _i++) {
          var key = sortedKeys_1[_i];
          absolutePaths.push({
            pattern: key,
            paths: paths[key].map(function(pathToResolve) {
              return path4.resolve(absoluteBaseUrl, pathToResolve);
            })
          });
        }
        if (!paths["*"] && addMatchAll) {
          absolutePaths.push({
            pattern: "*",
            paths: ["".concat(absoluteBaseUrl.replace(/\/$/, ""), "/*")]
          });
        }
        return absolutePaths;
      }
      exports3.getAbsoluteMappingEntries = getAbsoluteMappingEntries;
      function sortByLongestPrefix(arr) {
        return arr.concat().sort(function(a3, b3) {
          return getPrefixLength(b3) - getPrefixLength(a3);
        });
      }
      function getPrefixLength(pattern) {
        var prefixLength = pattern.indexOf("*");
        return pattern.substr(0, prefixLength).length;
      }
    });
    var require_try_path = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.exhaustiveTypeException = exports3.getStrippedPath = exports3.getPathsToTry = void 0;
      var path4 = require("path");
      var path_1 = require("path");
      var filesystem_1 = require_filesystem();
      function getPathsToTry(extensions, absolutePathMappings, requestedModule) {
        if (!absolutePathMappings || !requestedModule || requestedModule[0] === ".") {
          return void 0;
        }
        var pathsToTry = [];
        for (var _i = 0, absolutePathMappings_1 = absolutePathMappings; _i < absolutePathMappings_1.length; _i++) {
          var entry = absolutePathMappings_1[_i];
          var starMatch = entry.pattern === requestedModule ? "" : matchStar(entry.pattern, requestedModule);
          if (starMatch !== void 0) {
            var _loop_1 = function(physicalPathPattern2) {
              var physicalPath = physicalPathPattern2.replace("*", starMatch);
              pathsToTry.push({ type: "file", path: physicalPath });
              pathsToTry.push.apply(pathsToTry, extensions.map(function(e4) {
                return { type: "extension", path: physicalPath + e4 };
              }));
              pathsToTry.push({
                type: "package",
                path: path4.join(physicalPath, "/package.json")
              });
              var indexPath = path4.join(physicalPath, "/index");
              pathsToTry.push.apply(pathsToTry, extensions.map(function(e4) {
                return { type: "index", path: indexPath + e4 };
              }));
            };
            for (var _a2 = 0, _b = entry.paths; _a2 < _b.length; _a2++) {
              var physicalPathPattern = _b[_a2];
              _loop_1(physicalPathPattern);
            }
          }
        }
        return pathsToTry.length === 0 ? void 0 : pathsToTry;
      }
      exports3.getPathsToTry = getPathsToTry;
      function getStrippedPath(tryPath) {
        return tryPath.type === "index" ? (0, path_1.dirname)(tryPath.path) : tryPath.type === "file" ? tryPath.path : tryPath.type === "extension" ? (0, filesystem_1.removeExtension)(tryPath.path) : tryPath.type === "package" ? tryPath.path : exhaustiveTypeException(tryPath.type);
      }
      exports3.getStrippedPath = getStrippedPath;
      function exhaustiveTypeException(check2) {
        throw new Error("Unknown type ".concat(check2));
      }
      exports3.exhaustiveTypeException = exhaustiveTypeException;
      function matchStar(pattern, search) {
        if (search.length < pattern.length) {
          return void 0;
        }
        if (pattern === "*") {
          return search;
        }
        var star2 = pattern.indexOf("*");
        if (star2 === -1) {
          return void 0;
        }
        var part1 = pattern.substring(0, star2);
        var part2 = pattern.substring(star2 + 1);
        if (search.substr(0, star2) !== part1) {
          return void 0;
        }
        if (search.substr(search.length - part2.length) !== part2) {
          return void 0;
        }
        return search.substr(star2, search.length - part2.length);
      }
    });
    var require_match_path_sync = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.matchFromAbsolutePaths = exports3.createMatchPath = void 0;
      var path4 = require("path");
      var Filesystem = require_filesystem();
      var MappingEntry = require_mapping_entry();
      var TryPath = require_try_path();
      function createMatchPath2(absoluteBaseUrl, paths, mainFields, addMatchAll) {
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        if (addMatchAll === void 0) {
          addMatchAll = true;
        }
        var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
        return function(requestedModule, readJson, fileExists, extensions) {
          return matchFromAbsolutePaths(absolutePaths, requestedModule, readJson, fileExists, extensions, mainFields);
        };
      }
      exports3.createMatchPath = createMatchPath2;
      function matchFromAbsolutePaths(absolutePathMappings, requestedModule, readJson, fileExists, extensions, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskSync;
        }
        if (fileExists === void 0) {
          fileExists = Filesystem.fileExistsSync;
        }
        if (extensions === void 0) {
          extensions = Object.keys(require.extensions);
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
        if (!tryPaths) {
          return void 0;
        }
        return findFirstExistingPath(tryPaths, readJson, fileExists, mainFields);
      }
      exports3.matchFromAbsolutePaths = matchFromAbsolutePaths;
      function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExists) {
        for (var index6 = 0; index6 < mainFields.length; index6++) {
          var mainFieldSelector = mainFields[index6];
          var candidateMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
            return obj[key];
          }, packageJson);
          if (candidateMapping && typeof candidateMapping === "string") {
            var candidateFilePath = path4.join(path4.dirname(packageJsonPath), candidateMapping);
            if (fileExists(candidateFilePath)) {
              return candidateFilePath;
            }
          }
        }
        return void 0;
      }
      function findFirstExistingPath(tryPaths, readJson, fileExists, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskSync;
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        for (var _i = 0, tryPaths_1 = tryPaths; _i < tryPaths_1.length; _i++) {
          var tryPath = tryPaths_1[_i];
          if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
            if (fileExists(tryPath.path)) {
              return TryPath.getStrippedPath(tryPath);
            }
          } else if (tryPath.type === "package") {
            var packageJson = readJson(tryPath.path);
            if (packageJson) {
              var mainFieldMappedFile = findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists);
              if (mainFieldMappedFile) {
                return mainFieldMappedFile;
              }
            }
          } else {
            TryPath.exhaustiveTypeException(tryPath.type);
          }
        }
        return void 0;
      }
    });
    var require_match_path_async = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.matchFromAbsolutePathsAsync = exports3.createMatchPathAsync = void 0;
      var path4 = require("path");
      var TryPath = require_try_path();
      var MappingEntry = require_mapping_entry();
      var Filesystem = require_filesystem();
      function createMatchPathAsync(absoluteBaseUrl, paths, mainFields, addMatchAll) {
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        if (addMatchAll === void 0) {
          addMatchAll = true;
        }
        var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
        return function(requestedModule, readJson, fileExists, extensions, callback) {
          return matchFromAbsolutePathsAsync(absolutePaths, requestedModule, readJson, fileExists, extensions, callback, mainFields);
        };
      }
      exports3.createMatchPathAsync = createMatchPathAsync;
      function matchFromAbsolutePathsAsync(absolutePathMappings, requestedModule, readJson, fileExists, extensions, callback, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskAsync;
        }
        if (fileExists === void 0) {
          fileExists = Filesystem.fileExistsAsync;
        }
        if (extensions === void 0) {
          extensions = Object.keys(require.extensions);
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
        if (!tryPaths) {
          return callback();
        }
        findFirstExistingPath(tryPaths, readJson, fileExists, callback, 0, mainFields);
      }
      exports3.matchFromAbsolutePathsAsync = matchFromAbsolutePathsAsync;
      function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index6) {
        if (index6 === void 0) {
          index6 = 0;
        }
        if (index6 >= mainFields.length) {
          return doneCallback(void 0, void 0);
        }
        var tryNext = function() {
          return findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index6 + 1);
        };
        var mainFieldSelector = mainFields[index6];
        var mainFieldMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
          return obj[key];
        }, packageJson);
        if (typeof mainFieldMapping !== "string") {
          return tryNext();
        }
        var mappedFilePath = path4.join(path4.dirname(packageJsonPath), mainFieldMapping);
        fileExistsAsync(mappedFilePath, function(err2, exists) {
          if (err2) {
            return doneCallback(err2);
          }
          if (exists) {
            return doneCallback(void 0, mappedFilePath);
          }
          return tryNext();
        });
      }
      function findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6, mainFields) {
        if (index6 === void 0) {
          index6 = 0;
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPath = tryPaths[index6];
        if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
          fileExists(tryPath.path, function(err2, exists) {
            if (err2) {
              return doneCallback(err2);
            }
            if (exists) {
              return doneCallback(void 0, TryPath.getStrippedPath(tryPath));
            }
            if (index6 === tryPaths.length - 1) {
              return doneCallback();
            }
            return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6 + 1, mainFields);
          });
        } else if (tryPath.type === "package") {
          readJson(tryPath.path, function(err2, packageJson) {
            if (err2) {
              return doneCallback(err2);
            }
            if (packageJson) {
              return findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists, function(mainFieldErr, mainFieldMappedFile) {
                if (mainFieldErr) {
                  return doneCallback(mainFieldErr);
                }
                if (mainFieldMappedFile) {
                  return doneCallback(void 0, mainFieldMappedFile);
                }
                return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6 + 1, mainFields);
              });
            }
            return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6 + 1, mainFields);
          });
        } else {
          TryPath.exhaustiveTypeException(tryPath.type);
        }
      }
    });
    var require_unicode = __commonJS3((exports3, module22) => {
      module22.exports.Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
      module22.exports.ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
      module22.exports.ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
    });
    var require_util22 = __commonJS3((exports3, module22) => {
      var unicode = require_unicode();
      module22.exports = {
        isSpaceSeparator(c3) {
          return typeof c3 === "string" && unicode.Space_Separator.test(c3);
        },
        isIdStartChar(c3) {
          return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 === "$" || c3 === "_" || unicode.ID_Start.test(c3));
        },
        isIdContinueChar(c3) {
          return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 >= "0" && c3 <= "9" || c3 === "$" || c3 === "_" || c3 === "\u200C" || c3 === "\u200D" || unicode.ID_Continue.test(c3));
        },
        isDigit(c3) {
          return typeof c3 === "string" && /[0-9]/.test(c3);
        },
        isHexDigit(c3) {
          return typeof c3 === "string" && /[0-9A-Fa-f]/.test(c3);
        }
      };
    });
    var require_parse3 = __commonJS3((exports3, module22) => {
      var util2 = require_util22();
      var source;
      var parseState;
      var stack;
      var pos;
      var line;
      var column11;
      var token;
      var key;
      var root;
      module22.exports = function parse4(text, reviver) {
        source = String(text);
        parseState = "start";
        stack = [];
        pos = 0;
        line = 1;
        column11 = 0;
        token = void 0;
        key = void 0;
        root = void 0;
        do {
          token = lex();
          parseStates[parseState]();
        } while (token.type !== "eof");
        if (typeof reviver === "function") {
          return internalize({ "": root }, "", reviver);
        }
        return root;
      };
      function internalize(holder, name, reviver) {
        const value = holder[name];
        if (value != null && typeof value === "object") {
          if (Array.isArray(value)) {
            for (let i4 = 0; i4 < value.length; i4++) {
              const key2 = String(i4);
              const replacement = internalize(value, key2, reviver);
              if (replacement === void 0) {
                delete value[key2];
              } else {
                Object.defineProperty(value, key2, {
                  value: replacement,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          } else {
            for (const key2 in value) {
              const replacement = internalize(value, key2, reviver);
              if (replacement === void 0) {
                delete value[key2];
              } else {
                Object.defineProperty(value, key2, {
                  value: replacement,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          }
        }
        return reviver.call(holder, name, value);
      }
      var lexState;
      var buffer;
      var doubleQuote;
      var sign;
      var c3;
      function lex() {
        lexState = "default";
        buffer = "";
        doubleQuote = false;
        sign = 1;
        for (; ; ) {
          c3 = peek();
          const token2 = lexStates[lexState]();
          if (token2) {
            return token2;
          }
        }
      }
      function peek() {
        if (source[pos]) {
          return String.fromCodePoint(source.codePointAt(pos));
        }
      }
      function read() {
        const c22 = peek();
        if (c22 === "\n") {
          line++;
          column11 = 0;
        } else if (c22) {
          column11 += c22.length;
        } else {
          column11++;
        }
        if (c22) {
          pos += c22.length;
        }
        return c22;
      }
      var lexStates = {
        default() {
          switch (c3) {
            case "	":
            case "\v":
            case "\f":
            case " ":
            case "\xA0":
            case "\uFEFF":
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              return;
            case "/":
              read();
              lexState = "comment";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          if (util2.isSpaceSeparator(c3)) {
            read();
            return;
          }
          return lexStates[parseState]();
        },
        comment() {
          switch (c3) {
            case "*":
              read();
              lexState = "multiLineComment";
              return;
            case "/":
              read();
              lexState = "singleLineComment";
              return;
          }
          throw invalidChar(read());
        },
        multiLineComment() {
          switch (c3) {
            case "*":
              read();
              lexState = "multiLineCommentAsterisk";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
        },
        multiLineCommentAsterisk() {
          switch (c3) {
            case "*":
              read();
              return;
            case "/":
              read();
              lexState = "default";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
          lexState = "multiLineComment";
        },
        singleLineComment() {
          switch (c3) {
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              lexState = "default";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          read();
        },
        value() {
          switch (c3) {
            case "{":
            case "[":
              return newToken("punctuator", read());
            case "n":
              read();
              literal("ull");
              return newToken("null", null);
            case "t":
              read();
              literal("rue");
              return newToken("boolean", true);
            case "f":
              read();
              literal("alse");
              return newToken("boolean", false);
            case "-":
            case "+":
              if (read() === "-") {
                sign = -1;
              }
              lexState = "sign";
              return;
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal("nfinity");
              return newToken("numeric", Infinity);
            case "N":
              read();
              literal("aN");
              return newToken("numeric", NaN);
            case '"':
            case "'":
              doubleQuote = read() === '"';
              buffer = "";
              lexState = "string";
              return;
          }
          throw invalidChar(read());
        },
        identifierNameStartEscape() {
          if (c3 !== "u") {
            throw invalidChar(read());
          }
          read();
          const u3 = unicodeEscape();
          switch (u3) {
            case "$":
            case "_":
              break;
            default:
              if (!util2.isIdStartChar(u3)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u3;
          lexState = "identifierName";
        },
        identifierName() {
          switch (c3) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              buffer += read();
              return;
            case "\\":
              read();
              lexState = "identifierNameEscape";
              return;
          }
          if (util2.isIdContinueChar(c3)) {
            buffer += read();
            return;
          }
          return newToken("identifier", buffer);
        },
        identifierNameEscape() {
          if (c3 !== "u") {
            throw invalidChar(read());
          }
          read();
          const u3 = unicodeEscape();
          switch (u3) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              break;
            default:
              if (!util2.isIdContinueChar(u3)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u3;
          lexState = "identifierName";
        },
        sign() {
          switch (c3) {
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal("nfinity");
              return newToken("numeric", sign * Infinity);
            case "N":
              read();
              literal("aN");
              return newToken("numeric", NaN);
          }
          throw invalidChar(read());
        },
        zero() {
          switch (c3) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
            case "x":
            case "X":
              buffer += read();
              lexState = "hexadecimal";
              return;
          }
          return newToken("numeric", sign * 0);
        },
        decimalInteger() {
          switch (c3) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalPointLeading() {
          if (util2.isDigit(c3)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          throw invalidChar(read());
        },
        decimalPoint() {
          switch (c3) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c3)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalFraction() {
          switch (c3) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalExponent() {
          switch (c3) {
            case "+":
            case "-":
              buffer += read();
              lexState = "decimalExponentSign";
              return;
          }
          if (util2.isDigit(c3)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentSign() {
          if (util2.isDigit(c3)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentInteger() {
          if (util2.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        hexadecimal() {
          if (util2.isHexDigit(c3)) {
            buffer += read();
            lexState = "hexadecimalInteger";
            return;
          }
          throw invalidChar(read());
        },
        hexadecimalInteger() {
          if (util2.isHexDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        string() {
          switch (c3) {
            case "\\":
              read();
              buffer += escape2();
              return;
            case '"':
              if (doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "'":
              if (!doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "\n":
            case "\r":
              throw invalidChar(read());
            case "\u2028":
            case "\u2029":
              separatorChar(c3);
              break;
            case void 0:
              throw invalidChar(read());
          }
          buffer += read();
        },
        start() {
          switch (c3) {
            case "{":
            case "[":
              return newToken("punctuator", read());
          }
          lexState = "value";
        },
        beforePropertyName() {
          switch (c3) {
            case "$":
            case "_":
              buffer = read();
              lexState = "identifierName";
              return;
            case "\\":
              read();
              lexState = "identifierNameStartEscape";
              return;
            case "}":
              return newToken("punctuator", read());
            case '"':
            case "'":
              doubleQuote = read() === '"';
              lexState = "string";
              return;
          }
          if (util2.isIdStartChar(c3)) {
            buffer += read();
            lexState = "identifierName";
            return;
          }
          throw invalidChar(read());
        },
        afterPropertyName() {
          if (c3 === ":") {
            return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforePropertyValue() {
          lexState = "value";
        },
        afterPropertyValue() {
          switch (c3) {
            case ",":
            case "}":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforeArrayValue() {
          if (c3 === "]") {
            return newToken("punctuator", read());
          }
          lexState = "value";
        },
        afterArrayValue() {
          switch (c3) {
            case ",":
            case "]":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        end() {
          throw invalidChar(read());
        }
      };
      function newToken(type, value) {
        return {
          type,
          value,
          line,
          column: column11
        };
      }
      function literal(s4) {
        for (const c22 of s4) {
          const p3 = peek();
          if (p3 !== c22) {
            throw invalidChar(read());
          }
          read();
        }
      }
      function escape2() {
        const c22 = peek();
        switch (c22) {
          case "b":
            read();
            return "\b";
          case "f":
            read();
            return "\f";
          case "n":
            read();
            return "\n";
          case "r":
            read();
            return "\r";
          case "t":
            read();
            return "	";
          case "v":
            read();
            return "\v";
          case "0":
            read();
            if (util2.isDigit(peek())) {
              throw invalidChar(read());
            }
            return "\0";
          case "x":
            read();
            return hexEscape();
          case "u":
            read();
            return unicodeEscape();
          case "\n":
          case "\u2028":
          case "\u2029":
            read();
            return "";
          case "\r":
            read();
            if (peek() === "\n") {
              read();
            }
            return "";
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            throw invalidChar(read());
          case void 0:
            throw invalidChar(read());
        }
        return read();
      }
      function hexEscape() {
        let buffer2 = "";
        let c22 = peek();
        if (!util2.isHexDigit(c22)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        c22 = peek();
        if (!util2.isHexDigit(c22)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      function unicodeEscape() {
        let buffer2 = "";
        let count = 4;
        while (count-- > 0) {
          const c22 = peek();
          if (!util2.isHexDigit(c22)) {
            throw invalidChar(read());
          }
          buffer2 += read();
        }
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      var parseStates = {
        start() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push2();
        },
        beforePropertyName() {
          switch (token.type) {
            case "identifier":
            case "string":
              key = token.value;
              parseState = "afterPropertyName";
              return;
            case "punctuator":
              pop();
              return;
            case "eof":
              throw invalidEOF();
          }
        },
        afterPropertyName() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          parseState = "beforePropertyValue";
        },
        beforePropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push2();
        },
        beforeArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          if (token.type === "punctuator" && token.value === "]") {
            pop();
            return;
          }
          push2();
        },
        afterPropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforePropertyName";
              return;
            case "}":
              pop();
          }
        },
        afterArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforeArrayValue";
              return;
            case "]":
              pop();
          }
        },
        end() {
        }
      };
      function push2() {
        let value;
        switch (token.type) {
          case "punctuator":
            switch (token.value) {
              case "{":
                value = {};
                break;
              case "[":
                value = [];
                break;
            }
            break;
          case "null":
          case "boolean":
          case "numeric":
          case "string":
            value = token.value;
            break;
        }
        if (root === void 0) {
          root = value;
        } else {
          const parent = stack[stack.length - 1];
          if (Array.isArray(parent)) {
            parent.push(value);
          } else {
            Object.defineProperty(parent, key, {
              value,
              writable: true,
              enumerable: true,
              configurable: true
            });
          }
        }
        if (value !== null && typeof value === "object") {
          stack.push(value);
          if (Array.isArray(value)) {
            parseState = "beforeArrayValue";
          } else {
            parseState = "beforePropertyName";
          }
        } else {
          const current = stack[stack.length - 1];
          if (current == null) {
            parseState = "end";
          } else if (Array.isArray(current)) {
            parseState = "afterArrayValue";
          } else {
            parseState = "afterPropertyValue";
          }
        }
      }
      function pop() {
        stack.pop();
        const current = stack[stack.length - 1];
        if (current == null) {
          parseState = "end";
        } else if (Array.isArray(current)) {
          parseState = "afterArrayValue";
        } else {
          parseState = "afterPropertyValue";
        }
      }
      function invalidChar(c22) {
        if (c22 === void 0) {
          return syntaxError(`JSON5: invalid end of input at ${line}:${column11}`);
        }
        return syntaxError(`JSON5: invalid character '${formatChar(c22)}' at ${line}:${column11}`);
      }
      function invalidEOF() {
        return syntaxError(`JSON5: invalid end of input at ${line}:${column11}`);
      }
      function invalidIdentifier() {
        column11 -= 5;
        return syntaxError(`JSON5: invalid identifier character at ${line}:${column11}`);
      }
      function separatorChar(c22) {
        console.warn(`JSON5: '${formatChar(c22)}' in strings is not valid ECMAScript; consider escaping`);
      }
      function formatChar(c22) {
        const replacements = {
          "'": "\\'",
          '"': '\\"',
          "\\": "\\\\",
          "\b": "\\b",
          "\f": "\\f",
          "\n": "\\n",
          "\r": "\\r",
          "	": "\\t",
          "\v": "\\v",
          "\0": "\\0",
          "\u2028": "\\u2028",
          "\u2029": "\\u2029"
        };
        if (replacements[c22]) {
          return replacements[c22];
        }
        if (c22 < " ") {
          const hexString = c22.charCodeAt(0).toString(16);
          return "\\x" + ("00" + hexString).substring(hexString.length);
        }
        return c22;
      }
      function syntaxError(message) {
        const err2 = new SyntaxError(message);
        err2.lineNumber = line;
        err2.columnNumber = column11;
        return err2;
      }
    });
    var require_stringify = __commonJS3((exports3, module22) => {
      var util2 = require_util22();
      module22.exports = function stringify2(value, replacer, space) {
        const stack = [];
        let indent = "";
        let propertyList;
        let replacerFunc;
        let gap = "";
        let quote;
        if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
          space = replacer.space;
          quote = replacer.quote;
          replacer = replacer.replacer;
        }
        if (typeof replacer === "function") {
          replacerFunc = replacer;
        } else if (Array.isArray(replacer)) {
          propertyList = [];
          for (const v6 of replacer) {
            let item;
            if (typeof v6 === "string") {
              item = v6;
            } else if (typeof v6 === "number" || v6 instanceof String || v6 instanceof Number) {
              item = String(v6);
            }
            if (item !== void 0 && propertyList.indexOf(item) < 0) {
              propertyList.push(item);
            }
          }
        }
        if (space instanceof Number) {
          space = Number(space);
        } else if (space instanceof String) {
          space = String(space);
        }
        if (typeof space === "number") {
          if (space > 0) {
            space = Math.min(10, Math.floor(space));
            gap = "          ".substr(0, space);
          }
        } else if (typeof space === "string") {
          gap = space.substr(0, 10);
        }
        return serializeProperty("", { "": value });
        function serializeProperty(key, holder) {
          let value2 = holder[key];
          if (value2 != null) {
            if (typeof value2.toJSON5 === "function") {
              value2 = value2.toJSON5(key);
            } else if (typeof value2.toJSON === "function") {
              value2 = value2.toJSON(key);
            }
          }
          if (replacerFunc) {
            value2 = replacerFunc.call(holder, key, value2);
          }
          if (value2 instanceof Number) {
            value2 = Number(value2);
          } else if (value2 instanceof String) {
            value2 = String(value2);
          } else if (value2 instanceof Boolean) {
            value2 = value2.valueOf();
          }
          switch (value2) {
            case null:
              return "null";
            case true:
              return "true";
            case false:
              return "false";
          }
          if (typeof value2 === "string") {
            return quoteString(value2, false);
          }
          if (typeof value2 === "number") {
            return String(value2);
          }
          if (typeof value2 === "object") {
            return Array.isArray(value2) ? serializeArray(value2) : serializeObject(value2);
          }
          return void 0;
        }
        function quoteString(value2) {
          const quotes = {
            "'": 0.1,
            '"': 0.2
          };
          const replacements = {
            "'": "\\'",
            '"': '\\"',
            "\\": "\\\\",
            "\b": "\\b",
            "\f": "\\f",
            "\n": "\\n",
            "\r": "\\r",
            "	": "\\t",
            "\v": "\\v",
            "\0": "\\0",
            "\u2028": "\\u2028",
            "\u2029": "\\u2029"
          };
          let product = "";
          for (let i4 = 0; i4 < value2.length; i4++) {
            const c3 = value2[i4];
            switch (c3) {
              case "'":
              case '"':
                quotes[c3]++;
                product += c3;
                continue;
              case "\0":
                if (util2.isDigit(value2[i4 + 1])) {
                  product += "\\x00";
                  continue;
                }
            }
            if (replacements[c3]) {
              product += replacements[c3];
              continue;
            }
            if (c3 < " ") {
              let hexString = c3.charCodeAt(0).toString(16);
              product += "\\x" + ("00" + hexString).substring(hexString.length);
              continue;
            }
            product += c3;
          }
          const quoteChar = quote || Object.keys(quotes).reduce((a3, b3) => quotes[a3] < quotes[b3] ? a3 : b3);
          product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
          return quoteChar + product + quoteChar;
        }
        function serializeObject(value2) {
          if (stack.indexOf(value2) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack.push(value2);
          let stepback = indent;
          indent = indent + gap;
          let keys = propertyList || Object.keys(value2);
          let partial = [];
          for (const key of keys) {
            const propertyString = serializeProperty(key, value2);
            if (propertyString !== void 0) {
              let member = serializeKey(key) + ":";
              if (gap !== "") {
                member += " ";
              }
              member += propertyString;
              partial.push(member);
            }
          }
          let final;
          if (partial.length === 0) {
            final = "{}";
          } else {
            let properties;
            if (gap === "") {
              properties = partial.join(",");
              final = "{" + properties + "}";
            } else {
              let separator = ",\n" + indent;
              properties = partial.join(separator);
              final = "{\n" + indent + properties + ",\n" + stepback + "}";
            }
          }
          stack.pop();
          indent = stepback;
          return final;
        }
        function serializeKey(key) {
          if (key.length === 0) {
            return quoteString(key, true);
          }
          const firstChar = String.fromCodePoint(key.codePointAt(0));
          if (!util2.isIdStartChar(firstChar)) {
            return quoteString(key, true);
          }
          for (let i4 = firstChar.length; i4 < key.length; i4++) {
            if (!util2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i4)))) {
              return quoteString(key, true);
            }
          }
          return key;
        }
        function serializeArray(value2) {
          if (stack.indexOf(value2) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack.push(value2);
          let stepback = indent;
          indent = indent + gap;
          let partial = [];
          for (let i4 = 0; i4 < value2.length; i4++) {
            const propertyString = serializeProperty(String(i4), value2);
            partial.push(propertyString !== void 0 ? propertyString : "null");
          }
          let final;
          if (partial.length === 0) {
            final = "[]";
          } else {
            if (gap === "") {
              let properties = partial.join(",");
              final = "[" + properties + "]";
            } else {
              let separator = ",\n" + indent;
              let properties = partial.join(separator);
              final = "[\n" + indent + properties + ",\n" + stepback + "]";
            }
          }
          stack.pop();
          indent = stepback;
          return final;
        }
      };
    });
    var require_lib32 = __commonJS3((exports3, module22) => {
      var parse4 = require_parse3();
      var stringify2 = require_stringify();
      var JSON5 = {
        parse: parse4,
        stringify: stringify2
      };
      module22.exports = JSON5;
    });
    var require_strip_bom = __commonJS3((exports3, module22) => {
      "use strict";
      module22.exports = (x4) => {
        if (typeof x4 !== "string") {
          throw new TypeError("Expected a string, got " + typeof x4);
        }
        if (x4.charCodeAt(0) === 65279) {
          return x4.slice(1);
        }
        return x4;
      };
    });
    var require_tsconfig_loader = __commonJS3((exports3) => {
      "use strict";
      var __assign2 = exports3 && exports3.__assign || function() {
        __assign2 = Object.assign || function(t4) {
          for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) {
            s4 = arguments[i4];
            for (var p3 in s4)
              if (Object.prototype.hasOwnProperty.call(s4, p3))
                t4[p3] = s4[p3];
          }
          return t4;
        };
        return __assign2.apply(this, arguments);
      };
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.loadTsconfig = exports3.walkForTsConfig = exports3.tsConfigLoader = void 0;
      var path4 = require("path");
      var fs32 = require("fs");
      var JSON5 = require_lib32();
      var StripBom = require_strip_bom();
      function tsConfigLoader(_a2) {
        var getEnv = _a2.getEnv, cwd = _a2.cwd, _b = _a2.loadSync, loadSync = _b === void 0 ? loadSyncDefault : _b;
        var TS_NODE_PROJECT = getEnv("TS_NODE_PROJECT");
        var TS_NODE_BASEURL = getEnv("TS_NODE_BASEURL");
        var loadResult = loadSync(cwd, TS_NODE_PROJECT, TS_NODE_BASEURL);
        return loadResult;
      }
      exports3.tsConfigLoader = tsConfigLoader;
      function loadSyncDefault(cwd, filename, baseUrl) {
        var configPath = resolveConfigPath(cwd, filename);
        if (!configPath) {
          return {
            tsConfigPath: void 0,
            baseUrl: void 0,
            paths: void 0
          };
        }
        var config = loadTsconfig(configPath);
        return {
          tsConfigPath: configPath,
          baseUrl: baseUrl || config && config.compilerOptions && config.compilerOptions.baseUrl,
          paths: config && config.compilerOptions && config.compilerOptions.paths
        };
      }
      function resolveConfigPath(cwd, filename) {
        if (filename) {
          var absolutePath = fs32.lstatSync(filename).isDirectory() ? path4.resolve(filename, "./tsconfig.json") : path4.resolve(cwd, filename);
          return absolutePath;
        }
        if (fs32.statSync(cwd).isFile()) {
          return path4.resolve(cwd);
        }
        var configAbsolutePath = walkForTsConfig(cwd);
        return configAbsolutePath ? path4.resolve(configAbsolutePath) : void 0;
      }
      function walkForTsConfig(directory, readdirSync2) {
        if (readdirSync2 === void 0) {
          readdirSync2 = fs32.readdirSync;
        }
        var files = readdirSync2(directory);
        var filesToCheck = ["tsconfig.json", "jsconfig.json"];
        for (var _i = 0, filesToCheck_1 = filesToCheck; _i < filesToCheck_1.length; _i++) {
          var fileToCheck = filesToCheck_1[_i];
          if (files.indexOf(fileToCheck) !== -1) {
            return path4.join(directory, fileToCheck);
          }
        }
        var parentDirectory = path4.dirname(directory);
        if (directory === parentDirectory) {
          return void 0;
        }
        return walkForTsConfig(parentDirectory, readdirSync2);
      }
      exports3.walkForTsConfig = walkForTsConfig;
      function loadTsconfig(configFilePath, existsSync3, readFileSync3) {
        if (existsSync3 === void 0) {
          existsSync3 = fs32.existsSync;
        }
        if (readFileSync3 === void 0) {
          readFileSync3 = function(filename) {
            return fs32.readFileSync(filename, "utf8");
          };
        }
        if (!existsSync3(configFilePath)) {
          return void 0;
        }
        var configString = readFileSync3(configFilePath);
        var cleanedJson = StripBom(configString);
        var config;
        try {
          config = JSON5.parse(cleanedJson);
        } catch (e4) {
          throw new Error("".concat(configFilePath, " is malformed ").concat(e4.message));
        }
        var extendedConfig = config.extends;
        if (extendedConfig) {
          var base = void 0;
          if (Array.isArray(extendedConfig)) {
            base = extendedConfig.reduce(function(currBase, extendedConfigElement) {
              return mergeTsconfigs(currBase, loadTsconfigFromExtends(configFilePath, extendedConfigElement, existsSync3, readFileSync3));
            }, {});
          } else {
            base = loadTsconfigFromExtends(configFilePath, extendedConfig, existsSync3, readFileSync3);
          }
          return mergeTsconfigs(base, config);
        }
        return config;
      }
      exports3.loadTsconfig = loadTsconfig;
      function loadTsconfigFromExtends(configFilePath, extendedConfigValue, existsSync3, readFileSync3) {
        var _a2;
        if (typeof extendedConfigValue === "string" && extendedConfigValue.indexOf(".json") === -1) {
          extendedConfigValue += ".json";
        }
        var currentDir = path4.dirname(configFilePath);
        var extendedConfigPath = path4.join(currentDir, extendedConfigValue);
        if (extendedConfigValue.indexOf("/") !== -1 && extendedConfigValue.indexOf(".") !== -1 && !existsSync3(extendedConfigPath)) {
          extendedConfigPath = path4.join(currentDir, "node_modules", extendedConfigValue);
        }
        var config = loadTsconfig(extendedConfigPath, existsSync3, readFileSync3) || {};
        if ((_a2 = config.compilerOptions) === null || _a2 === void 0 ? void 0 : _a2.baseUrl) {
          var extendsDir = path4.dirname(extendedConfigValue);
          config.compilerOptions.baseUrl = path4.join(extendsDir, config.compilerOptions.baseUrl);
        }
        return config;
      }
      function mergeTsconfigs(base, config) {
        base = base || {};
        config = config || {};
        return __assign2(__assign2(__assign2({}, base), config), { compilerOptions: __assign2(__assign2({}, base.compilerOptions), config.compilerOptions) });
      }
    });
    var require_config_loader = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.configLoader = exports3.loadConfig = void 0;
      var TsConfigLoader2 = require_tsconfig_loader();
      var path4 = require("path");
      function loadConfig2(cwd) {
        if (cwd === void 0) {
          cwd = process.cwd();
        }
        return configLoader({ cwd });
      }
      exports3.loadConfig = loadConfig2;
      function configLoader(_a2) {
        var cwd = _a2.cwd, explicitParams = _a2.explicitParams, _b = _a2.tsConfigLoader, tsConfigLoader = _b === void 0 ? TsConfigLoader2.tsConfigLoader : _b;
        if (explicitParams) {
          var absoluteBaseUrl = path4.isAbsolute(explicitParams.baseUrl) ? explicitParams.baseUrl : path4.join(cwd, explicitParams.baseUrl);
          return {
            resultType: "success",
            configFileAbsolutePath: "",
            baseUrl: explicitParams.baseUrl,
            absoluteBaseUrl,
            paths: explicitParams.paths,
            mainFields: explicitParams.mainFields,
            addMatchAll: explicitParams.addMatchAll
          };
        }
        var loadResult = tsConfigLoader({
          cwd,
          getEnv: function(key) {
            return process.env[key];
          }
        });
        if (!loadResult.tsConfigPath) {
          return {
            resultType: "failed",
            message: "Couldn't find tsconfig.json"
          };
        }
        return {
          resultType: "success",
          configFileAbsolutePath: loadResult.tsConfigPath,
          baseUrl: loadResult.baseUrl,
          absoluteBaseUrl: path4.resolve(path4.dirname(loadResult.tsConfigPath), loadResult.baseUrl || ""),
          paths: loadResult.paths || {},
          addMatchAll: loadResult.baseUrl !== void 0
        };
      }
      exports3.configLoader = configLoader;
    });
    var require_minimist = __commonJS3((exports3, module22) => {
      "use strict";
      function hasKey(obj, keys) {
        var o3 = obj;
        keys.slice(0, -1).forEach(function(key2) {
          o3 = o3[key2] || {};
        });
        var key = keys[keys.length - 1];
        return key in o3;
      }
      function isNumber(x4) {
        if (typeof x4 === "number") {
          return true;
        }
        if (/^0x[0-9a-f]+$/i.test(x4)) {
          return true;
        }
        return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x4);
      }
      function isConstructorOrProto(obj, key) {
        return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
      }
      module22.exports = function(args, opts) {
        if (!opts) {
          opts = {};
        }
        var flags = {
          bools: {},
          strings: {},
          unknownFn: null
        };
        if (typeof opts.unknown === "function") {
          flags.unknownFn = opts.unknown;
        }
        if (typeof opts.boolean === "boolean" && opts.boolean) {
          flags.allBools = true;
        } else {
          [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
            flags.bools[key2] = true;
          });
        }
        var aliases = {};
        function aliasIsBoolean(key2) {
          return aliases[key2].some(function(x4) {
            return flags.bools[x4];
          });
        }
        Object.keys(opts.alias || {}).forEach(function(key2) {
          aliases[key2] = [].concat(opts.alias[key2]);
          aliases[key2].forEach(function(x4) {
            aliases[x4] = [key2].concat(aliases[key2].filter(function(y2) {
              return x4 !== y2;
            }));
          });
        });
        [].concat(opts.string).filter(Boolean).forEach(function(key2) {
          flags.strings[key2] = true;
          if (aliases[key2]) {
            [].concat(aliases[key2]).forEach(function(k3) {
              flags.strings[k3] = true;
            });
          }
        });
        var defaults2 = opts.default || {};
        var argv = { _: [] };
        function argDefined(key2, arg2) {
          return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
        }
        function setKey(obj, keys, value2) {
          var o3 = obj;
          for (var i22 = 0; i22 < keys.length - 1; i22++) {
            var key2 = keys[i22];
            if (isConstructorOrProto(o3, key2)) {
              return;
            }
            if (o3[key2] === void 0) {
              o3[key2] = {};
            }
            if (o3[key2] === Object.prototype || o3[key2] === Number.prototype || o3[key2] === String.prototype) {
              o3[key2] = {};
            }
            if (o3[key2] === Array.prototype) {
              o3[key2] = [];
            }
            o3 = o3[key2];
          }
          var lastKey = keys[keys.length - 1];
          if (isConstructorOrProto(o3, lastKey)) {
            return;
          }
          if (o3 === Object.prototype || o3 === Number.prototype || o3 === String.prototype) {
            o3 = {};
          }
          if (o3 === Array.prototype) {
            o3 = [];
          }
          if (o3[lastKey] === void 0 || flags.bools[lastKey] || typeof o3[lastKey] === "boolean") {
            o3[lastKey] = value2;
          } else if (Array.isArray(o3[lastKey])) {
            o3[lastKey].push(value2);
          } else {
            o3[lastKey] = [o3[lastKey], value2];
          }
        }
        function setArg(key2, val2, arg2) {
          if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
            if (flags.unknownFn(arg2) === false) {
              return;
            }
          }
          var value2 = !flags.strings[key2] && isNumber(val2) ? Number(val2) : val2;
          setKey(argv, key2.split("."), value2);
          (aliases[key2] || []).forEach(function(x4) {
            setKey(argv, x4.split("."), value2);
          });
        }
        Object.keys(flags.bools).forEach(function(key2) {
          setArg(key2, defaults2[key2] === void 0 ? false : defaults2[key2]);
        });
        var notFlags = [];
        if (args.indexOf("--") !== -1) {
          notFlags = args.slice(args.indexOf("--") + 1);
          args = args.slice(0, args.indexOf("--"));
        }
        for (var i4 = 0; i4 < args.length; i4++) {
          var arg = args[i4];
          var key;
          var next;
          if (/^--.+=/.test(arg)) {
            var m4 = arg.match(/^--([^=]+)=([\s\S]*)$/);
            key = m4[1];
            var value = m4[2];
            if (flags.bools[key]) {
              value = value !== "false";
            }
            setArg(key, value, arg);
          } else if (/^--no-.+/.test(arg)) {
            key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false, arg);
          } else if (/^--.+/.test(arg)) {
            key = arg.match(/^--(.+)/)[1];
            next = args[i4 + 1];
            if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, next, arg);
              i4 += 1;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next === "true", arg);
              i4 += 1;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          } else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1, -1).split("");
            var broken = false;
            for (var j3 = 0; j3 < letters.length; j3++) {
              next = arg.slice(j3 + 2);
              if (next === "-") {
                setArg(letters[j3], next, arg);
                continue;
              }
              if (/[A-Za-z]/.test(letters[j3]) && next[0] === "=") {
                setArg(letters[j3], next.slice(1), arg);
                broken = true;
                break;
              }
              if (/[A-Za-z]/.test(letters[j3]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                setArg(letters[j3], next, arg);
                broken = true;
                break;
              }
              if (letters[j3 + 1] && letters[j3 + 1].match(/\W/)) {
                setArg(letters[j3], arg.slice(j3 + 2), arg);
                broken = true;
                break;
              } else {
                setArg(letters[j3], flags.strings[letters[j3]] ? "" : true, arg);
              }
            }
            key = arg.slice(-1)[0];
            if (!broken && key !== "-") {
              if (args[i4 + 1] && !/^(-|--)[^-]/.test(args[i4 + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                setArg(key, args[i4 + 1], arg);
                i4 += 1;
              } else if (args[i4 + 1] && /^(true|false)$/.test(args[i4 + 1])) {
                setArg(key, args[i4 + 1] === "true", arg);
                i4 += 1;
              } else {
                setArg(key, flags.strings[key] ? "" : true, arg);
              }
            }
          } else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
              argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
            }
            if (opts.stopEarly) {
              argv._.push.apply(argv._, args.slice(i4 + 1));
              break;
            }
          }
        }
        Object.keys(defaults2).forEach(function(k3) {
          if (!hasKey(argv, k3.split("."))) {
            setKey(argv, k3.split("."), defaults2[k3]);
            (aliases[k3] || []).forEach(function(x4) {
              setKey(argv, x4.split("."), defaults2[k3]);
            });
          }
        });
        if (opts["--"]) {
          argv["--"] = notFlags.slice();
        } else {
          notFlags.forEach(function(k3) {
            argv._.push(k3);
          });
        }
        return argv;
      };
    });
    var require_register = __commonJS3((exports3) => {
      "use strict";
      var __spreadArray2 = exports3 && exports3.__spreadArray || function(to, from, pack) {
        if (pack || arguments.length === 2)
          for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) {
            if (ar || !(i4 in from)) {
              if (!ar)
                ar = Array.prototype.slice.call(from, 0, i4);
              ar[i4] = from[i4];
            }
          }
        return to.concat(ar || Array.prototype.slice.call(from));
      };
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.register = void 0;
      var match_path_sync_1 = require_match_path_sync();
      var config_loader_1 = require_config_loader();
      var noOp2 = function() {
        return void 0;
      };
      function getCoreModules(builtinModules2) {
        builtinModules2 = builtinModules2 || [
          "assert",
          "buffer",
          "child_process",
          "cluster",
          "crypto",
          "dgram",
          "dns",
          "domain",
          "events",
          "fs",
          "http",
          "https",
          "net",
          "os",
          "path",
          "punycode",
          "querystring",
          "readline",
          "stream",
          "string_decoder",
          "tls",
          "tty",
          "url",
          "util",
          "v8",
          "vm",
          "zlib"
        ];
        var coreModules = {};
        for (var _i = 0, builtinModules_1 = builtinModules2; _i < builtinModules_1.length; _i++) {
          var module_1 = builtinModules_1[_i];
          coreModules[module_1] = true;
        }
        return coreModules;
      }
      function register2(params) {
        var cwd;
        var explicitParams;
        if (params) {
          cwd = params.cwd;
          if (params.baseUrl || params.paths) {
            explicitParams = params;
          }
        } else {
          var minimist = require_minimist();
          var argv = minimist(process.argv.slice(2), {
            string: ["project"],
            alias: {
              project: ["P"]
            }
          });
          cwd = argv.project;
        }
        var configLoaderResult = (0, config_loader_1.configLoader)({
          cwd: cwd !== null && cwd !== void 0 ? cwd : process.cwd(),
          explicitParams
        });
        if (configLoaderResult.resultType === "failed") {
          console.warn("".concat(configLoaderResult.message, ". tsconfig-paths will be skipped"));
          return noOp2;
        }
        var matchPath = (0, match_path_sync_1.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
        var Module = require("module");
        var originalResolveFilename = Module._resolveFilename;
        var coreModules = getCoreModules(Module.builtinModules);
        Module._resolveFilename = function(request, _parent) {
          var isCoreModule = coreModules.hasOwnProperty(request);
          if (!isCoreModule) {
            var found = matchPath(request);
            if (found) {
              var modifiedArguments = __spreadArray2([found], [].slice.call(arguments, 1), true);
              return originalResolveFilename.apply(this, modifiedArguments);
            }
          }
          return originalResolveFilename.apply(this, arguments);
        };
        return function() {
          Module._resolveFilename = originalResolveFilename;
        };
      }
      exports3.register = register2;
    });
    var require_lib4 = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.loadConfig = exports3.register = exports3.matchFromAbsolutePathsAsync = exports3.createMatchPathAsync = exports3.matchFromAbsolutePaths = exports3.createMatchPath = void 0;
      var match_path_sync_1 = require_match_path_sync();
      Object.defineProperty(exports3, "createMatchPath", { enumerable: true, get: function() {
        return match_path_sync_1.createMatchPath;
      } });
      Object.defineProperty(exports3, "matchFromAbsolutePaths", { enumerable: true, get: function() {
        return match_path_sync_1.matchFromAbsolutePaths;
      } });
      var match_path_async_1 = require_match_path_async();
      Object.defineProperty(exports3, "createMatchPathAsync", { enumerable: true, get: function() {
        return match_path_async_1.createMatchPathAsync;
      } });
      Object.defineProperty(exports3, "matchFromAbsolutePathsAsync", { enumerable: true, get: function() {
        return match_path_async_1.matchFromAbsolutePathsAsync;
      } });
      var register_1 = require_register();
      Object.defineProperty(exports3, "register", { enumerable: true, get: function() {
        return register_1.register;
      } });
      var config_loader_1 = require_config_loader();
      Object.defineProperty(exports3, "loadConfig", { enumerable: true, get: function() {
        return config_loader_1.loadConfig;
      } });
    });
    var import_source_map_support = __toModule(require_source_map_support());
    var import_pirates = __toModule(require_lib3());
    var _path2 = require("path");
    var _esbuild = require("esbuild");
    var _fs2 = require("fs");
    var _fs3 = _interopRequireDefault2(_fs2);
    var _module2 = require("module");
    var _module3 = _interopRequireDefault2(_module2);
    var _process = require("process");
    var _process2 = _interopRequireDefault2(_process);
    var import_joycon = __toModule(require_lib22());
    var singleComment = Symbol("singleComment");
    var multiComment = Symbol("multiComment");
    var stripWithoutWhitespace = () => "";
    var stripWithWhitespace = (string2, start, end) => string2.slice(start, end).replace(/\S/g, " ");
    var isEscaped = (jsonString, quotePosition) => {
      let index6 = quotePosition - 1;
      let backslashCount = 0;
      while (jsonString[index6] === "\\") {
        index6 -= 1;
        backslashCount += 1;
      }
      return Boolean(backslashCount % 2);
    };
    function stripJsonComments(jsonString, { whitespace = true } = {}) {
      if (typeof jsonString !== "string") {
        throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
      }
      const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace;
      let isInsideString = false;
      let isInsideComment = false;
      let offset = 0;
      let result = "";
      for (let index6 = 0; index6 < jsonString.length; index6++) {
        const currentCharacter = jsonString[index6];
        const nextCharacter = jsonString[index6 + 1];
        if (!isInsideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, index6);
          if (!escaped) {
            isInsideString = !isInsideString;
          }
        }
        if (isInsideString) {
          continue;
        }
        if (!isInsideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, index6);
          offset = index6;
          isInsideComment = singleComment;
          index6++;
        } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          index6++;
          isInsideComment = false;
          result += strip(jsonString, offset, index6);
          offset = index6;
          continue;
        } else if (isInsideComment === singleComment && currentCharacter === "\n") {
          isInsideComment = false;
          result += strip(jsonString, offset, index6);
          offset = index6;
        } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, index6);
          offset = index6;
          isInsideComment = multiComment;
          index6++;
          continue;
        } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          index6++;
          isInsideComment = false;
          result += strip(jsonString, offset, index6 + 1);
          offset = index6 + 1;
          continue;
        }
      }
      return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
    }
    var nodeVersion = (process.versions.node.match(/^(\d+)\.(\d+)/) || []).slice(1).map(Number);
    function removeNodePrefix(code) {
      if (nodeVersion[0] <= 14 && nodeVersion[1] < 18) {
        return code.replace(/([\b\(])require\("node:([^"]+)"\)([\b\)])/g, '$1require("$2")$3');
      }
      return code;
    }
    function jsoncParse(data) {
      try {
        return new Function("return " + stripJsonComments(data).trim())();
      } catch (_3) {
        return {};
      }
    }
    var joycon = new import_joycon.default();
    joycon.addLoader({
      test: /\.json$/,
      loadSync: (file) => {
        const content = _fs3.default.readFileSync(file, "utf8");
        return jsoncParse(content);
      }
    });
    var getOptions = (cwd) => {
      const { data, path: path4 } = joycon.loadSync(["tsconfig.json", "jsconfig.json"], cwd);
      if (path4 && data) {
        return data;
      }
      return {};
    };
    var inferPackageFormat = (cwd, filename) => {
      if (filename.endsWith(".mjs")) {
        return "esm";
      }
      if (filename.endsWith(".cjs")) {
        return "cjs";
      }
      const { data } = joycon.loadSync(["package.json"], cwd);
      return data && data.type === "module" && /\.m?js$/.test(filename) ? "esm" : "cjs";
    };
    var import_tsconfig_paths = __toModule(require_lib4());
    var noOp = () => {
    };
    function registerTsconfigPaths() {
      const configLoaderResult = (0, import_tsconfig_paths.loadConfig)(process.cwd());
      if (configLoaderResult.resultType === "failed") {
        return noOp;
      }
      const matchPath = (0, import_tsconfig_paths.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
      const Module = require("module");
      const originalResolveFilename = Module._resolveFilename;
      Module._resolveFilename = function(request, _parent) {
        const isCoreModule = _module2.builtinModules.includes(request);
        if (!isCoreModule) {
          const found = matchPath(request);
          if (found) {
            const modifiedArguments = [found, ...[].slice.call(arguments, 1)];
            return originalResolveFilename.apply(this, modifiedArguments);
          }
        }
        return originalResolveFilename.apply(this, arguments);
      };
      return () => {
        Module._resolveFilename = originalResolveFilename;
      };
    }
    var _debug = require_src2();
    var _debug2 = _interopRequireDefault2(_debug);
    var debug = _debug2.default.call(void 0, "esbuild-register");
    var IMPORT_META_URL_VARIABLE_NAME = "__esbuild_register_import_meta_url__";
    var map2 = {};
    function installSourceMapSupport() {
      if (_process2.default.setSourceMapsEnabled) {
        ;
        _process2.default.setSourceMapsEnabled(true);
      } else {
        import_source_map_support.default.install({
          handleUncaughtExceptions: false,
          environment: "node",
          retrieveSourceMap(file) {
            if (map2[file]) {
              return {
                url: file,
                map: map2[file]
              };
            }
            return null;
          }
        });
      }
    }
    function patchCommonJsLoader(compile) {
      const extensions = _module3.default.Module._extensions;
      const jsHandler = extensions[".js"];
      extensions[".js"] = function(module22, filename) {
        try {
          return jsHandler.call(this, module22, filename);
        } catch (error2) {
          if (error2.code !== "ERR_REQUIRE_ESM") {
            throw error2;
          }
          let content = _fs3.default.readFileSync(filename, "utf8");
          content = compile(content, filename, "cjs");
          module22._compile(content, filename);
        }
      };
      return () => {
        extensions[".js"] = jsHandler;
      };
    }
    var FILE_LOADERS = {
      ".js": "js",
      ".jsx": "jsx",
      ".ts": "ts",
      ".tsx": "tsx",
      ".mjs": "js",
      ".mts": "ts",
      ".cts": "ts"
    };
    var DEFAULT_EXTENSIONS = Object.keys(FILE_LOADERS);
    var getLoader = (filename) => FILE_LOADERS[_path2.extname.call(void 0, filename)];
    function register(esbuildOptions = {}) {
      const {
        extensions = DEFAULT_EXTENSIONS,
        hookIgnoreNodeModules = true,
        hookMatcher,
        ...overrides
      } = esbuildOptions;
      const compile = function compile2(code, filename, format) {
        const define2 = {
          "import.meta.url": IMPORT_META_URL_VARIABLE_NAME,
          ...overrides.define
        };
        const banner = `const ${IMPORT_META_URL_VARIABLE_NAME} = require('url').pathToFileURL(__filename).href;${overrides.banner || ""}`;
        if (code.includes(banner)) {
          return code;
        }
        const dir = _path2.dirname.call(void 0, filename);
        const tsconfigRaw = getOptions(dir);
        format = format != null ? format : inferPackageFormat(dir, filename);
        const result = _esbuild.transformSync.call(void 0, code, {
          sourcefile: filename,
          loader: getLoader(filename),
          sourcemap: "both",
          tsconfigRaw,
          format,
          define: define2,
          banner,
          ...overrides
        });
        const js = result.code;
        debug("compiled %s", filename);
        debug("%s", js);
        const warnings = result.warnings;
        if (warnings && warnings.length > 0) {
          for (const warning3 of warnings) {
            console.log(warning3.location);
            console.log(warning3.text);
          }
        }
        if (format === "esm")
          return js;
        return removeNodePrefix(js);
      };
      const revert = (0, import_pirates.addHook)(compile, {
        exts: extensions,
        ignoreNodeModules: hookIgnoreNodeModules,
        matcher: hookMatcher
      });
      installSourceMapSupport();
      const unpatchCommonJsLoader = patchCommonJsLoader(compile);
      const unregisterTsconfigPaths = registerTsconfigPaths();
      return {
        unregister() {
          revert();
          unpatchCommonJsLoader();
          unregisterTsconfigPaths();
        }
      };
    }
    exports2.register = register;
  }
});

// src/cli/commands/utils.ts
var import_fs3, import_hanji2, import_path3, assertES5, safeRegister, prepareCheckParams, prepareDropParams, prepareGenerateConfig, prepareExportConfig, flattenDatabaseCredentials, flattenPull, preparePushConfig, preparePullConfig, prepareStudioConfig, migrateConfig, prepareMigrateConfig, drizzleConfigFromFile;
var init_utils3 = __esm({
  "src/cli/commands/utils.ts"() {
    "use strict";
    init_source();
    import_fs3 = require("fs");
    import_hanji2 = __toESM(require_hanji());
    import_path3 = require("path");
    init_esm();
    init_getTablesFilterByExtensions();
    init_global();
    init_schemaValidator();
    init_serializer();
    init_cli();
    init_common();
    init_gel();
    init_gel();
    init_libsql();
    init_mysql();
    init_outputs();
    init_postgres();
    init_singlestore();
    init_sqlite();
    init_studio();
    init_views();
    assertES5 = async (unregister) => {
      try {
        init_es5();
      } catch (e4) {
        if ("errors" in e4 && Array.isArray(e4.errors) && e4.errors.length > 0) {
          const es5Error = e4.errors.filter((it) => {
            var _a2;
            return (_a2 = it.text) == null ? void 0 : _a2.includes(`("es5") is not supported yet`);
          }).length > 0;
          if (es5Error) {
            console.log(
              error(
                `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
              )
            );
            process.exit(1);
          }
        }
        console.error(e4);
        process.exit(1);
      }
    };
    safeRegister = async () => {
      const { register } = await Promise.resolve().then(() => __toESM(require_node2()));
      let res;
      try {
        res = register({
          format: "cjs",
          loader: "ts"
        });
      } catch {
        res = {
          unregister: () => {
          }
        };
      }
      await assertES5(res.unregister);
      return res;
    };
    prepareCheckParams = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      if (!config.out || !config.dialect) {
        let text = `Please provide required params for AWS Data API driver:
`;
        console.log(error(text));
        console.log(wrapParam("database", config.out));
        console.log(wrapParam("secretArn", config.dialect));
        process.exit(1);
      }
      return { out: config.out, dialect: config.dialect };
    };
    prepareDropParams = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      if (config.dialect === "gel") {
        console.log(
          error(
            `You can't use 'drop' command with Gel dialect`
          )
        );
        process.exit(1);
      }
      return { out: config.out || "drizzle", bundle: config.driver === "expo" };
    };
    prepareGenerateConfig = async (options, from) => {
      var _a2;
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      const { schema: schema6, out, breakpoints, dialect: dialect6, driver: driver2, casing: casing2 } = config;
      if (!schema6 || !dialect6) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("schema", schema6));
        console.log(wrapParam("dialect", dialect6));
        console.log(wrapParam("out", out, true));
        process.exit(1);
      }
      const fileNames = prepareFilenames(schema6);
      if (fileNames.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
        process.exit(0);
      }
      const prefix2 = ("migrations" in config ? (_a2 = config.migrations) == null ? void 0 : _a2.prefix : options.prefix) || "index";
      return {
        dialect: dialect6,
        name: options.name,
        custom: options.custom || false,
        prefix: prefix2,
        breakpoints: breakpoints ?? true,
        schema: schema6,
        out: out || "drizzle",
        bundle: driver2 === "expo" || driver2 === "durable-sqlite",
        casing: casing2,
        driver: driver2
      };
    };
    prepareExportConfig = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config, true) : options;
      const { schema: schema6, dialect: dialect6, sql } = config;
      if (!schema6 || !dialect6) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("schema", schema6));
        console.log(wrapParam("dialect", dialect6));
        process.exit(1);
      }
      const fileNames = prepareFilenames(schema6);
      if (fileNames.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
        process.exit(0);
      }
      return {
        dialect: dialect6,
        schema: schema6,
        sql
      };
    };
    flattenDatabaseCredentials = (config) => {
      if ("dbCredentials" in config) {
        const { dbCredentials, ...rest } = config;
        return {
          ...rest,
          ...dbCredentials
        };
      }
      return config;
    };
    flattenPull = (config) => {
      if ("dbCredentials" in config) {
        const { dbCredentials, introspect, ...rest } = config;
        return {
          ...rest,
          ...dbCredentials,
          casing: introspect == null ? void 0 : introspect.casing
        };
      }
      return config;
    };
    preparePushConfig = async (options, from) => {
      const raw2 = flattenDatabaseCredentials(
        from === "config" ? await drizzleConfigFromFile(options.config) : options
      );
      raw2.verbose ||= options.verbose;
      raw2.strict ||= options.strict;
      const parsed = pushParams.safeParse(raw2);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", raw2.dialect));
        console.log(wrapParam("schema", raw2.schema));
        process.exit(1);
      }
      const config = parsed.data;
      const schemaFiles = prepareFilenames(config.schema);
      if (schemaFiles.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${config.schema} was found`);
        process.exit(0);
      }
      const tablesFilterConfig = config.tablesFilter;
      const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
      const schemasFilterConfig = config.schemaFilter;
      const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
      tablesFilter.push(...getTablesFilterByExtensions(config));
      if (config.dialect === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues4(config);
          process.exit(1);
        }
        return {
          dialect: "postgresql",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter,
          entities: config.entities
        };
      }
      if (config.dialect === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues3(config);
          process.exit(1);
        }
        return {
          dialect: "mysql",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues5(config);
          process.exit(1);
        }
        return {
          dialect: "singlestore",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues6(config, "push");
          process.exit(1);
        }
        return {
          dialect: "sqlite",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "turso") {
        const parsed2 = libSQLCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues6(config, "push");
          process.exit(1);
        }
        return {
          dialect: "turso",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "gel") {
        console.log(
          error(
            `You can't use 'push' command with Gel dialect`
          )
        );
        process.exit(1);
      }
      assertUnreachable(config.dialect);
    };
    preparePullConfig = async (options, from) => {
      var _a2, _b, _c, _d, _e, _f;
      const raw2 = flattenPull(
        from === "config" ? await drizzleConfigFromFile(options.config) : options
      );
      const parsed = pullParams.safeParse(raw2);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", raw2.dialect));
        process.exit(1);
      }
      const config = parsed.data;
      const dialect6 = config.dialect;
      const tablesFilterConfig = config.tablesFilter;
      const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
      if (config.extensionsFilters) {
        if (config.extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
          tablesFilter.push(
            ...["!geography_columns", "!geometry_columns", "!spatial_ref_sys"]
          );
        }
      }
      const schemasFilterConfig = config.schemaFilter;
      const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
      if (dialect6 === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues4(config);
          process.exit(1);
        }
        return {
          dialect: "postgresql",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_a2 = config.migrations) == null ? void 0 : _a2.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues3(config);
          process.exit(1);
        }
        return {
          dialect: "mysql",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues5(config);
          process.exit(1);
        }
        return {
          dialect: "singlestore",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues6(config, "pull");
          process.exit(1);
        }
        return {
          dialect: "sqlite",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_d = config.migrations) == null ? void 0 : _d.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "turso") {
        const parsed2 = libSQLCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues2(config, "pull");
          process.exit(1);
        }
        return {
          dialect: dialect6,
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_e = config.migrations) == null ? void 0 : _e.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "gel") {
        const parsed2 = gelCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues(config);
          process.exit(1);
        }
        return {
          dialect: dialect6,
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_f = config.migrations) == null ? void 0 : _f.prefix) || "index",
          entities: config.entities
        };
      }
      assertUnreachable(dialect6);
    };
    prepareStudioConfig = async (options) => {
      const params = studioCliParams.parse(options);
      const config = await drizzleConfigFromFile(params.config);
      const result = studioConfig.safeParse(config);
      if (!result.success) {
        if (!("dialect" in config)) {
          console.log(outputs.studio.noDialect());
        }
        process.exit(1);
      }
      if (!("dbCredentials" in config)) {
        console.log(outputs.studio.noCredentials());
        process.exit(1);
      }
      const { host, port } = params;
      const { dialect: dialect6, schema: schema6 } = result.data;
      const flattened = flattenDatabaseCredentials(config);
      if (dialect6 === "postgresql") {
        const parsed = postgresCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues4(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "mysql") {
        const parsed = mysqlCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues3(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "singlestore") {
        const parsed = singlestoreCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues5(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "sqlite") {
        const parsed = sqliteCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues6(flattened, "studio");
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "turso") {
        const parsed = libSQLCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues2(flattened, "studio");
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "gel") {
        console.log(
          error(
            `You can't use 'studio' command with Gel dialect`
          )
        );
        process.exit(1);
      }
      assertUnreachable(dialect6);
    };
    migrateConfig = objectType({
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      migrations: configMigrations
    });
    prepareMigrateConfig = async (configPath) => {
      const config = await drizzleConfigFromFile(configPath);
      const parsed = migrateConfig.safeParse(config);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", config.dialect));
        process.exit(1);
      }
      const { dialect: dialect6, out } = parsed.data;
      const { schema: schema6, table: table6 } = parsed.data.migrations || {};
      const flattened = flattenDatabaseCredentials(config);
      if (dialect6 === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues4(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table6
        };
      }
      if (dialect6 === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues3(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table6
        };
      }
      if (dialect6 === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues5(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table6
        };
      }
      if (dialect6 === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues6(flattened, "migrate");
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table6
        };
      }
      if (dialect6 === "turso") {
        const parsed2 = libSQLCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues2(flattened, "migrate");
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table6
        };
      }
      if (dialect6 === "gel") {
        console.log(
          error(
            `You can't use 'migrate' command with Gel dialect`
          )
        );
        process.exit(1);
      }
      assertUnreachable(dialect6);
    };
    drizzleConfigFromFile = async (configPath, isExport) => {
      const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
      const defaultTsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.ts")));
      const defaultJsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.js")));
      const defaultJsonConfigExists = (0, import_fs3.existsSync)(
        (0, import_path3.join)((0, import_path3.resolve)("drizzle.config.json"))
      );
      const defaultConfigPath = defaultTsConfigExists ? "drizzle.config.ts" : defaultJsConfigExists ? "drizzle.config.js" : "drizzle.config.json";
      if (!configPath && !isExport) {
        console.log(
          source_default.gray(
            `No config path provided, using default '${defaultConfigPath}'`
          )
        );
      }
      const path4 = (0, import_path3.resolve)((0, import_path3.join)(prefix2, configPath ?? defaultConfigPath));
      if (!(0, import_fs3.existsSync)(path4)) {
        console.log(`${path4} file does not exist`);
        process.exit(1);
      }
      if (!isExport) console.log(source_default.grey(`Reading config file '${path4}'`));
      const { unregister } = await safeRegister();
      const required = require(`${path4}`);
      const content = required.default ?? required;
      unregister();
      const res = configCommonSchema.safeParse(content);
      if (!res.success) {
        console.log(res.error);
        if (!("dialect" in content)) {
          console.log(error("Please specify 'dialect' param in config file"));
        }
        process.exit(1);
      }
      return res.data;
    };
  }
});

// src/serializer/mysqlImports.ts
var mysqlImports_exports = {};
__export(mysqlImports_exports, {
  prepareFromExports: () => prepareFromExports,
  prepareFromMySqlImports: () => prepareFromMySqlImports
});
var import_drizzle_orm, import_mysql_core, prepareFromExports, prepareFromMySqlImports;
var init_mysqlImports = __esm({
  "src/serializer/mysqlImports.ts"() {
    "use strict";
    import_drizzle_orm = require("drizzle-orm");
    import_mysql_core = require("drizzle-orm/mysql-core");
    init_utils3();
    prepareFromExports = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t4) => {
        if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlTable)) {
          tables.push(t4);
        }
        if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlView)) {
          views.push(t4);
        }
      });
      return { tables, views };
    };
    prepareFromMySqlImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/utils.ts
function getColumnCasing(column11, casing2) {
  if (!column11.name) return "";
  return !column11.keyAsName || casing2 === void 0 ? column11.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column11.name) : (0, import_casing.toSnakeCase)(column11.name);
}
var import_casing, sqlToStr;
var init_utils4 = __esm({
  "src/serializer/utils.ts"() {
    "use strict";
    import_casing = require("drizzle-orm/casing");
    sqlToStr = (sql, casing2) => {
      return sql.toQuery({
        escapeName: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeParam: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeString: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        casing: new import_casing.CasingCache(casing2)
      }).sql;
    };
  }
});

// src/serializer/mysqlSerializer.ts
var mysqlSerializer_exports = {};
__export(mysqlSerializer_exports, {
  fromDatabase: () => fromDatabase,
  generateMySqlSnapshot: () => generateMySqlSnapshot,
  indexName: () => indexName
});
function clearDefaults(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
    } else {
      return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var import_drizzle_orm2, import_mysql_core2, indexName, handleEnumType, generateMySqlSnapshot, fromDatabase;
var init_mysqlSerializer = __esm({
  "src/serializer/mysqlSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm2 = require("drizzle-orm");
    import_mysql_core2 = require("drizzle-orm/mysql-core");
    init_outputs();
    init_utils2();
    init_utils4();
    indexName = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    handleEnumType = (type) => {
      let str = type.split("(")[1];
      str = str.substring(0, str.length - 1);
      const values = str.split(",").map((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.length - 1))}'`);
      return `enum(${values.join(",")})`;
    };
    generateMySqlSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_mysql_core2.MySqlDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          schema: schema6,
          checks,
          primaryKeys,
          uniqueConstraints
        } = (0, import_mysql_core2.getTableConfig)(table6);
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        let checksInTable = {};
        columns.forEach((column11) => {
          const name = getColumnCasing(column11, casing2);
          const notNull = column11.notNull;
          const sqlType = column11.getSQLType();
          const sqlTypeLowered = sqlType.toLowerCase();
          const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
          const generated = column11.generated;
          const columnToSet = {
            name,
            type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType,
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column11.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column11.primary) {
            primaryKeysObject[`${tableName}_${name}`] = {
              name: `${tableName}_${name}`,
              columns: [name]
            };
          }
          if (column11.isUnique) {
            const existingUnique = uniqueConstraintObject[column11.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column11.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column11.uniqueName] = {
              name: column11.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column11.default !== void 0) {
            if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) {
              columnToSet.default = sqlToStr(column11.default, casing2);
            } else {
              if (typeof column11.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`;
              } else {
                if (sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column11.default)}'`;
                } else if (column11.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column11.default;
                }
              }
              if (["blob", "text", "json"].includes(column11.getSQLType())) {
                columnToSet.default = `(${columnToSet.default})`;
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c3) => c3.name);
          const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
              name = name.replace(originalColumnNames[i4], columnNames[i4]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
          for (const column11 of pk.columns) {
            columnsObject[getColumnCasing(column11, casing2)].notNull = true;
          }
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
          const name = unq.name ?? (0, import_mysql_core2.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = (0, import_drizzle_orm2.getTableName)(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
              name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
            }
            for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
              name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            var _a2;
            if ((0, import_drizzle_orm2.is)(it, import_drizzle_orm2.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return `${getColumnCasing(it, casing2)}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          } else {
            if (typeof foreignKeysObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint.

We have encountered a collision between the index name on columns ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} and the foreign key on columns ${source_default.underline.blue(
                    foreignKeysObject[name].columnsFrom.join(",")
                  )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html

            `
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorythm,
            lock: value.config.lock
          };
        });
        checks.forEach((check2) => {
          check2;
          const checkName = check2.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check2.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check2.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.value).sql
          };
        });
        if (!schema6) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            foreignKeys: foreignKeysObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject,
            checkConstraint: checkConstraintObject
          };
        }
      }
      for (const view5 of views) {
        const {
          isExisting,
          name,
          query,
          schema: schema6,
          selectedFields,
          algorithm,
          sqlSecurity,
          withCheckOption
        } = (0, import_mysql_core2.getViewConfig)(view5);
        const columnsObject = {};
        const existingView = resultViews[name];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema6 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm2.is)(selectedFields[key], import_mysql_core2.MySqlColumn)) {
            const column11 = selectedFields[key];
            const notNull = column11.notNull;
            const sqlTypeLowered = column11.getSQLType().toLowerCase();
            const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
            const generated = column11.generated;
            const columnToSet = {
              name: column11.name,
              type: column11.getSQLType(),
              primaryKey: false,
              // If field is autoincrement it's notNull by default
              // notNull: autoIncrement ? true : notNull,
              notNull,
              autoincrement: autoIncrement,
              onUpdate: column11.hasOnUpdateNow,
              generated: generated ? {
                as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: generated.mode ?? "stored"
              } : void 0
            };
            if (column11.default !== void 0) {
              if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) {
                columnToSet.default = sqlToStr(column11.default, casing2);
              } else {
                if (typeof column11.default === "string") {
                  columnToSet.default = `'${column11.default}'`;
                } else {
                  if (sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column11.default)}'`;
                  } else if (column11.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                      columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    }
                  } else {
                    columnToSet.default = column11.default;
                  }
                }
                if (["blob", "text", "json"].includes(column11.getSQLType())) {
                  columnToSet.default = `(${columnToSet.default})`;
                }
              }
            }
            columnsObject[column11.name] = columnToSet;
          }
        }
        resultViews[name] = {
          columns: columnsObject,
          name,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          withCheckOption,
          algorithm: algorithm ?? "undefined",
          // set default values
          sqlSecurity: sqlSecurity ?? "definer"
          // set default values
        };
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column11 of response) {
        if (!tablesFilter(column11["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column11["TABLE_SCHEMA"];
        const tableName = column11["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column11["COLUMN_NAME"];
        const isNullable = column11["IS_NULLABLE"] === "YES";
        const dataType = column11["DATA_TYPE"];
        const columnType = column11["COLUMN_TYPE"];
        const isPrimary = column11["COLUMN_KEY"] === "PRI";
        const columnDefault = column11["COLUMN_DEFAULT"];
        const collation = column11["CHARACTER_SET_NAME"];
        const geenratedExpression = column11["GENERATION_EXPRESSION"];
        let columnExtra = column11["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column11["EXTRA"] !== "undefined") {
          columnExtra = column11["EXTRA"];
          isAutoincrement = column11["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraint: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='PRIMARY KEY'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["TABLE_NAME"];
        const columnName = tableToPkRow["COLUMN_NAME"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(
          `SELECT 
      kcu.TABLE_SCHEMA,
      kcu.TABLE_NAME,
      kcu.CONSTRAINT_NAME,
      kcu.COLUMN_NAME,
      kcu.REFERENCED_TABLE_SCHEMA,
      kcu.REFERENCED_TABLE_NAME,
      kcu.REFERENCED_COLUMN_NAME,
      rc.UPDATE_RULE,
      rc.DELETE_RULE
  FROM 
      INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
  LEFT JOIN 
      information_schema.referential_constraints rc 
      ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
  WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY' 
      AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;`
        );
        const fkRows = fks;
        for (const fkRow of fkRows) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableSchema = fkRow["TABLE_SCHEMA"];
          const tableName = fkRow["TABLE_NAME"];
          const constraintName = fkRow["CONSTRAINT_NAME"];
          const columnName = fkRow["COLUMN_NAME"];
          const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"];
          const refTableName = fkRow["REFERENCED_TABLE_NAME"];
          const refColumnName = fkRow["REFERENCED_COLUMN_NAME"];
          const updateRule = fkRow["UPDATE_RULE"];
          const deleteRule = fkRow["DELETE_RULE"];
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") {
            tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName);
            tableInResult.foreignKeys[constraintName].columnsTo.push(
              refColumnName
            );
          } else {
            tableInResult.foreignKeys[constraintName] = {
              name: constraintName,
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
              onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
            };
          }
          tableInResult.foreignKeys[constraintName].columnsFrom = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
          ];
          tableInResult.foreignKeys[constraintName].columnsTo = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
          ];
        }
      } catch (e4) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        } else {
          if (typeof tableInResult.foreignKeys[constraintName] === "undefined") {
            if (typeof tableInResult.indexes[constraintName] !== "undefined") {
              tableInResult.indexes[constraintName].columns.push(columnName);
            } else {
              tableInResult.indexes[constraintName] = {
                name: constraintName,
                columns: [columnName],
                isUnique
              };
            }
          }
        }
      }
      const views = await db.query(
        `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
      );
      const resultViews = {};
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for await (const view5 of views) {
        const viewName = view5["TABLE_NAME"];
        const definition = view5["VIEW_DEFINITION"];
        const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase();
        const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase();
        const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
        const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
        const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          algorithm,
          definition,
          sqlSecurity,
          withCheckOption
        };
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
        progressCallback("views", viewsCount, "done");
      }
      const checkConstraints = await db.query(
        `SELECT 
    tc.table_name, 
    tc.constraint_name, 
    cc.check_clause
FROM 
    information_schema.table_constraints tc
JOIN 
    information_schema.check_constraints cc 
    ON tc.constraint_name = cc.constraint_name
WHERE 
    tc.constraint_schema = '${inputSchema}'
AND 
    tc.constraint_type = 'CHECK';`
      );
      checksCount += checkConstraints.length;
      if (progressCallback) {
        progressCallback("checks", checksCount, "fetching");
      }
      for (const checkConstraintRow of checkConstraints) {
        const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
        const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
        const tableName = checkConstraintRow["TABLE_NAME"];
        const tableInResult = result[tableName];
        tableInResult.checkConstraint[constraintName] = {
          name: constraintName,
          value: constraintValue
        };
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// src/serializer/pgImports.ts
var pgImports_exports = {};
__export(pgImports_exports, {
  prepareFromExports: () => prepareFromExports2,
  prepareFromPgImports: () => prepareFromPgImports
});
var import_drizzle_orm3, import_pg_core, prepareFromExports2, prepareFromPgImports;
var init_pgImports = __esm({
  "src/serializer/pgImports.ts"() {
    "use strict";
    import_drizzle_orm3 = require("drizzle-orm");
    import_pg_core = require("drizzle-orm/pg-core");
    init_utils3();
    prepareFromExports2 = (exports2) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const roles = [];
      const policies = [];
      const views = [];
      const matViews = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t4) => {
        if ((0, import_pg_core.isPgEnum)(t4)) {
          enums.push(t4);
          return;
        }
        if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgTable)) {
          tables.push(t4);
        }
        if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgSchema)) {
          schemas.push(t4);
        }
        if ((0, import_pg_core.isPgView)(t4)) {
          views.push(t4);
        }
        if ((0, import_pg_core.isPgMaterializedView)(t4)) {
          matViews.push(t4);
        }
        if ((0, import_pg_core.isPgSequence)(t4)) {
          sequences.push(t4);
        }
        if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgRole)) {
          roles.push(t4);
        }
        if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgPolicy)) {
          policies.push(t4);
        }
      });
      return { tables, enums, schemas, sequences, views, matViews, roles, policies };
    };
    prepareFromPgImports = async (imports) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const views = [];
      const roles = [];
      const policies = [];
      const matViews = [];
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports2(i0);
        tables.push(...prepared.tables);
        enums.push(...prepared.enums);
        schemas.push(...prepared.schemas);
        sequences.push(...prepared.sequences);
        views.push(...prepared.views);
        matViews.push(...prepared.matViews);
        roles.push(...prepared.roles);
        policies.push(...prepared.policies);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews, roles, policies };
    };
  }
});

// src/extensions/vector.ts
var vectorOps;
var init_vector = __esm({
  "src/extensions/vector.ts"() {
    "use strict";
    vectorOps = [
      "vector_l2_ops",
      "vector_ip_ops",
      "vector_cosine_ops",
      "vector_l1_ops",
      "bit_hamming_ops",
      "bit_jaccard_ops",
      "halfvec_l2_ops",
      "sparsevec_l2_ops"
    ];
  }
});

// src/serializer/pgSerializer.ts
var pgSerializer_exports = {};
__export(pgSerializer_exports, {
  buildArrayString: () => buildArrayString,
  fromDatabase: () => fromDatabase2,
  generatePgSnapshot: () => generatePgSnapshot,
  indexName: () => indexName2
});
function stringFromIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
}
function maxRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
}
function minRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
}
function stringFromDatabaseIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
}
function buildArrayString(array2, sqlType) {
  sqlType = sqlType.split("[")[0];
  const values = array2.map((value) => {
    if (typeof value === "number" || typeof value === "bigint") {
      return value.toString();
    } else if (typeof value === "boolean") {
      return value ? "true" : "false";
    } else if (Array.isArray(value)) {
      return buildArrayString(value, sqlType);
    } else if (value instanceof Date) {
      if (sqlType === "date") {
        return `"${value.toISOString().split("T")[0]}"`;
      } else if (sqlType === "timestamp") {
        return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
      } else {
        return `"${value.toISOString()}"`;
      }
    } else if (typeof value === "object") {
      return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
    }
    return `"${value}"`;
  }).join(",");
  return `{${values}}`;
}
function prepareRoles(entities) {
  let useRoles = false;
  const includeRoles = [];
  const excludeRoles = [];
  if (entities && entities.roles) {
    if (typeof entities.roles === "object") {
      if (entities.roles.provider) {
        if (entities.roles.provider === "supabase") {
          excludeRoles.push(...[
            "anon",
            "authenticator",
            "authenticated",
            "service_role",
            "supabase_auth_admin",
            "supabase_storage_admin",
            "dashboard_user",
            "supabase_admin"
          ]);
        } else if (entities.roles.provider === "neon") {
          excludeRoles.push(...["authenticated", "anonymous"]);
        }
      }
      if (entities.roles.include) {
        includeRoles.push(...entities.roles.include);
      }
      if (entities.roles.exclude) {
        excludeRoles.push(...entities.roles.exclude);
      }
    } else {
      useRoles = entities.roles;
    }
  }
  return { useRoles, includeRoles, excludeRoles };
}
var import_drizzle_orm4, import_pg_core2, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn, getColumnsInfoQuery;
var init_pgSerializer = __esm({
  "src/serializer/pgSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm4 = require("drizzle-orm");
    import_pg_core2 = require("drizzle-orm/pg-core");
    init_vector();
    init_outputs();
    init_utils2();
    init_utils4();
    indexName2 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o;
      const dialect6 = new import_pg_core2.PgDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const sequencesToReturn = {};
      const rolesToReturn = {};
      const policiesToReturn = {};
      const indexesInSchema = {};
      for (const table6 of tables) {
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          checks,
          schema: schema6,
          primaryKeys,
          uniqueConstraints,
          policies: policies2,
          enableRLS
        } = (0, import_pg_core2.getTableConfig)(table6);
        if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) {
          continue;
        }
        const columnsObject = {};
        const indexesObject = {};
        const checksObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const policiesObject = {};
        columns.forEach((column11) => {
          var _a3, _b2, _c2, _d2, _e2, _f2;
          const name = getColumnCasing(column11, casing2);
          const notNull = column11.notNull;
          const primaryKey = column11.primary;
          const sqlTypeLowered = column11.getSQLType().toLowerCase();
          const getEnumSchema = (column12) => {
            while ((0, import_drizzle_orm4.is)(column12, import_pg_core2.PgArray)) {
              column12 = column12.baseColumn;
            }
            return (0, import_drizzle_orm4.is)(column12, import_pg_core2.PgEnumColumn) ? column12.enum.schema || "public" : void 0;
          };
          const typeSchema = getEnumSchema(column11);
          const generated = column11.generated;
          const identity = column11.generatedIdentity;
          const increment = stringFromIdentityProperty((_a3 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _a3.increment) ?? "1";
          const minValue = stringFromIdentityProperty((_b2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _b2.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column11.columnType) : "1");
          const maxValue = stringFromIdentityProperty((_c2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _c2.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType()));
          const startWith = stringFromIdentityProperty((_d2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _d2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache3 = stringFromIdentityProperty((_e2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _e2.cache) ?? "1";
          const columnToSet = {
            name,
            type: column11.getSQLType(),
            typeSchema,
            primaryKey,
            notNull,
            generated: generated ? {
              as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: "stored"
            } : void 0,
            identity: identity ? {
              type: identity.type,
              name: identity.sequenceName ?? `${tableName}_${name}_seq`,
              schema: schema6 ?? "public",
              increment,
              startWith,
              minValue,
              maxValue,
              cache: cache3,
              cycle: ((_f2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _f2.cycle) ?? false
            } : void 0
          };
          if (column11.isUnique) {
            const existingUnique = uniqueConstraintObject[column11.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column11.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column11.uniqueName] = {
              name: column11.uniqueName,
              nullsNotDistinct: column11.uniqueType === "not distinct",
              columns: [columnToSet.name]
            };
          }
          if (column11.default !== void 0) {
            if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) {
              columnToSet.default = sqlToStr(column11.default, casing2);
            } else {
              if (typeof column11.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`;
              } else {
                if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`;
                } else if (column11.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered === "timestamp") {
                    columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  } else {
                    columnToSet.default = `'${column11.default.toISOString()}'`;
                  }
                } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) {
                  columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`;
                } else {
                  columnToSet.default = column11.default;
                }
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c3) => c3.name);
          const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
              name = name.replace(originalColumnNames[i4], columnNames[i4]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
          const name = unq.name ?? (0, import_pg_core2.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table. 
        The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            nullsNotDistinct: unq.nullsNotDistinct,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete;
          const onUpdate = fk5.onUpdate;
          const reference = fk5.reference();
          const tableTo = (0, import_drizzle_orm4.getTableName)(reference.foreignTable);
          const schemaTo = (0, import_pg_core2.getTableConfig)(reference.foreignTable).schema;
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
              name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
            }
            for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
              name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            schemaTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          let indexColumnNames = [];
          columns2.forEach((it) => {
            if ((0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL)) {
              if (typeof value.config.name === "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `Please specify an index name in ${(0, import_drizzle_orm4.getTableName)(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
                  )}`
                );
                process.exit(1);
              }
            }
            it = it;
            const name2 = getColumnCasing(it, casing2);
            if (!(0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `You are specifying an index on the ${source_default.blueBright(
                    name2
                  )} column inside the ${source_default.blueBright(
                    tableName
                  )} table with the ${source_default.blueBright(
                    "vector"
                  )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].

You can specify it using current syntax: ${source_default.underline(
                    `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))`
                  )}

You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing
`
                )}`
              );
              process.exit(1);
            }
            indexColumnNames.push(name2);
          });
          const name = value.config.name ? value.config.name : indexName2(tableName, indexColumnNames);
          let indexColumns = columns2.map(
            (it) => {
              var _a3, _b2, _c2, _d2, _e2;
              if ((0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL)) {
                return {
                  expression: dialect6.sqlToQuery(it, "indexes").sql,
                  asc: true,
                  isExpression: true,
                  nulls: "last"
                };
              } else {
                it = it;
                return {
                  expression: getColumnCasing(it, casing2),
                  isExpression: false,
                  asc: ((_a3 = it.indexConfig) == null ? void 0 : _a3.order) === "asc",
                  nulls: ((_b2 = it.indexConfig) == null ? void 0 : _b2.nulls) ? (_c2 = it.indexConfig) == null ? void 0 : _c2.nulls : ((_d2 = it.indexConfig) == null ? void 0 : _d2.order) === "desc" ? "first" : "last",
                  opclass: (_e2 = it.indexConfig) == null ? void 0 : _e2.opClass
                };
              }
            }
          );
          if (typeof indexesInSchema[schema6 ?? "public"] !== "undefined") {
            if (indexesInSchema[schema6 ?? "public"].includes(name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated index name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated index name`
                )}`
              );
              process.exit(1);
            }
            indexesInSchema[schema6 ?? "public"].push(name);
          } else {
            indexesInSchema[schema6 ?? "public"] = [name];
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0,
            concurrently: value.config.concurrently ?? false,
            method: value.config.method ?? "btree",
            with: value.config.with ?? {}
          };
        });
        policies2.forEach((policy5) => {
          var _a3, _b2;
          const mappedTo = [];
          if (!policy5.to) {
            mappedTo.push("public");
          } else {
            if (policy5.to && typeof policy5.to === "string") {
              mappedTo.push(policy5.to);
            } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) {
              mappedTo.push(policy5.to.name);
            } else if (policy5.to && Array.isArray(policy5.to)) {
              policy5.to.forEach((it) => {
                if (typeof it === "string") {
                  mappedTo.push(it);
                } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
                  mappedTo.push(it.name);
                }
              });
            }
          }
          if (policiesObject[policy5.name] !== void 0) {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                  policy5.name
                )} name`
              )}`
            );
            process.exit(1);
          }
          policiesObject[policy5.name] = {
            name: policy5.name,
            as: ((_a3 = policy5.as) == null ? void 0 : _a3.toUpperCase()) ?? "PERMISSIVE",
            for: ((_b2 = policy5.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL",
            to: mappedTo.sort(),
            using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
            withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
          };
        });
        checks.forEach((check2) => {
          const checkName = check2.name;
          if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") {
            if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check2.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name across ${source_default.underline.blue(
                    schema6 ?? "public"
                  )} schema in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated check contraint name`
                )}`
              );
              process.exit(1);
            }
            checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].push(checkName);
          } else {
            checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] = [check2.name];
          }
          checksObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.value).sql
          };
        });
        const tableKey2 = `${schema6 ?? "public"}.${tableName}`;
        result[tableKey2] = {
          name: tableName,
          schema: schema6 ?? "",
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          policies: policiesObject,
          checkConstraints: checksObject,
          isRLSEnabled: enableRLS
        };
      }
      for (const policy5 of policies) {
        if (!policy5._linkedTable) {
          console.log(
            `
${withStyle.errorWarning(
              `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:`
            )}`
          );
          continue;
        }
        const tableConfig = (0, import_pg_core2.getTableConfig)(policy5._linkedTable);
        const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
        const mappedTo = [];
        if (!policy5.to) {
          mappedTo.push("public");
        } else {
          if (policy5.to && typeof policy5.to === "string") {
            mappedTo.push(policy5.to);
          } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) {
            mappedTo.push(policy5.to.name);
          } else if (policy5.to && Array.isArray(policy5.to)) {
            policy5.to.forEach((it) => {
              if (typeof it === "string") {
                mappedTo.push(it);
              } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
                mappedTo.push(it.name);
              }
            });
          }
        }
        if (((_a2 = result[tableKey2]) == null ? void 0 : _a2.policies[policy5.name]) !== void 0 || policiesToReturn[policy5.name] !== void 0) {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                policy5.name
              )} name`
            )}`
          );
          process.exit(1);
        }
        const mappedPolicy = {
          name: policy5.name,
          as: ((_b = policy5.as) == null ? void 0 : _b.toUpperCase()) ?? "PERMISSIVE",
          for: ((_c = policy5.for) == null ? void 0 : _c.toUpperCase()) ?? "ALL",
          to: mappedTo.sort(),
          using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
          withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
        };
        if (result[tableKey2]) {
          result[tableKey2].policies[policy5.name] = mappedPolicy;
        } else {
          policiesToReturn[policy5.name] = {
            ...mappedPolicy,
            schema: tableConfig.schema ?? "public",
            on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"`
          };
        }
      }
      for (const sequence of sequences) {
        const name = sequence.seqName;
        if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") {
          const increment = stringFromIdentityProperty((_d = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _d.increment) ?? "1";
          const minValue = stringFromIdentityProperty((_e = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _e.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
          const maxValue = stringFromIdentityProperty((_f = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _f.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
          const startWith = stringFromIdentityProperty((_g = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _g.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache3 = stringFromIdentityProperty((_h = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _h.cache) ?? "1";
          sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = {
            name,
            schema: sequence.schema ?? "public",
            increment,
            startWith,
            minValue,
            maxValue,
            cache: cache3,
            cycle: ((_i = sequence.seqOptions) == null ? void 0 : _i.cycle) ?? false
          };
        } else {
        }
      }
      for (const role of roles) {
        if (!role._existing) {
          rolesToReturn[role.name] = {
            name: role.name,
            createDb: role.createDb === void 0 ? false : role.createDb,
            createRole: role.createRole === void 0 ? false : role.createRole,
            inherit: role.inherit === void 0 ? true : role.inherit
          };
        }
      }
      const combinedViews = [...views, ...matViews];
      for (const view5 of combinedViews) {
        let viewName;
        let schema6;
        let query;
        let selectedFields;
        let isExisting;
        let withOption;
        let tablespace;
        let using;
        let withNoData;
        let materialized = false;
        if ((0, import_drizzle_orm4.is)(view5, import_pg_core2.PgView)) {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view5));
        } else {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(view5));
          materialized = true;
        }
        const viewSchema = schema6 ?? "public";
        const viewKey = `${viewSchema}.${viewName}`;
        const columnsObject = {};
        const uniqueConstraintObject = {};
        const existingView = resultViews[viewKey];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm4.is)(selectedFields[key], import_pg_core2.PgColumn)) {
            const column11 = selectedFields[key];
            const notNull = column11.notNull;
            const primaryKey = column11.primary;
            const sqlTypeLowered = column11.getSQLType().toLowerCase();
            const typeSchema = (0, import_drizzle_orm4.is)(column11, import_pg_core2.PgEnumColumn) ? column11.enum.schema || "public" : void 0;
            const generated = column11.generated;
            const identity = column11.generatedIdentity;
            const increment = stringFromIdentityProperty((_j = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _j.increment) ?? "1";
            const minValue = stringFromIdentityProperty((_k = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _k.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column11.columnType) : "1");
            const maxValue = stringFromIdentityProperty((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType()));
            const startWith = stringFromIdentityProperty((_m2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _m2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
            const cache3 = stringFromIdentityProperty((_n = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _n.cache) ?? "1";
            const columnToSet = {
              name: column11.name,
              type: column11.getSQLType(),
              typeSchema,
              primaryKey,
              notNull,
              generated: generated ? {
                as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: "stored"
              } : void 0,
              identity: identity ? {
                type: identity.type,
                name: identity.sequenceName ?? `${viewName}_${column11.name}_seq`,
                schema: schema6 ?? "public",
                increment,
                startWith,
                minValue,
                maxValue,
                cache: cache3,
                cycle: ((_o = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _o.cycle) ?? false
              } : void 0
            };
            if (column11.isUnique) {
              const existingUnique = uniqueConstraintObject[column11.uniqueName];
              if (typeof existingUnique !== "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table. 
          The unique constraint ${source_default.underline.blue(column11.uniqueName)} on the ${source_default.underline.blue(
                      column11.name
                    )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
                  )}`
                );
                process.exit(1);
              }
              uniqueConstraintObject[column11.uniqueName] = {
                name: column11.uniqueName,
                nullsNotDistinct: column11.uniqueType === "not distinct",
                columns: [columnToSet.name]
              };
            }
            if (column11.default !== void 0) {
              if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) {
                columnToSet.default = sqlToStr(column11.default, casing2);
              } else {
                if (typeof column11.default === "string") {
                  columnToSet.default = `'${column11.default}'`;
                } else {
                  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`;
                  } else if (column11.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered === "timestamp") {
                      columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    } else {
                      columnToSet.default = `'${column11.default.toISOString()}'`;
                    }
                  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) {
                    columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`;
                  } else {
                    columnToSet.default = column11.default;
                  }
                }
              }
            }
            columnsObject[column11.name] = columnToSet;
          }
        }
        resultViews[viewKey] = {
          columns: columnsObject,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          name: viewName,
          schema: viewSchema,
          isExisting,
          with: withOption,
          withNoData,
          materialized,
          tablespace,
          using
        };
      }
      const enumsToReturn = enums.reduce((map2, obj) => {
        const enumSchema4 = obj.schema || "public";
        const key = `${enumSchema4}.${obj.enumName}`;
        map2[key] = {
          name: obj.enumName,
          schema: enumSchema4,
          values: obj.enumValues
        };
        return map2;
      }, {});
      const schemasObject = Object.fromEntries(
        schemas.filter((it) => {
          if (schemaFilter) {
            return schemaFilter.includes(it.schemaName) && it.schemaName !== "public";
          } else {
            return it.schemaName !== "public";
          }
        }).map((it) => [it.schemaName, it.schemaName])
      );
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies: policiesToReturn,
        views: resultViews,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        }
      };
    };
    trimChar = (str, char) => {
      let start = 0;
      let end = str.length;
      while (start < end && str[start] === char) ++start;
      while (end > start && str[end - 1] === char) --end;
      return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
    };
    fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
      const result = {};
      const views = {};
      const policies = {};
      const internals = { tables: {} };
      const where = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
      const allTables = await db.query(
        `SELECT 
    n.nspname AS table_schema, 
    c.relname AS table_name, 
    CASE 
        WHEN c.relkind = 'r' THEN 'table'
        WHEN c.relkind = 'v' THEN 'view'
        WHEN c.relkind = 'm' THEN 'materialized_view'
    END AS type,
	c.relrowsecurity AS rls_enabled
FROM 
    pg_catalog.pg_class c
JOIN 
    pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE 
	c.relkind IN ('r', 'v', 'm') 
    ${where === "" ? "" : ` AND ${where}`};`
      );
      const schemas = new Set(allTables.map((it) => it.table_schema));
      schemas.delete("public");
      const allSchemas = await db.query(`select s.nspname as table_schema
  from pg_catalog.pg_namespace s
  join pg_catalog.pg_user u on u.usesysid = s.nspowner
  where nspname not in ('information_schema', 'pg_catalog', 'public')
        and nspname not like 'pg_toast%'
        and nspname not like 'pg_temp_%'
  order by table_schema;`);
      allSchemas.forEach((item) => {
        if (schemaFilters.includes(item.table_schema)) {
          schemas.add(item.table_schema);
        }
      });
      let columnsCount = 0;
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let tableCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const sequencesToReturn = {};
      const seqWhere = schemaFilters.map((t4) => `schemaname = '${t4}'`).join(" or ");
      const allSequences = await db.query(
        `select schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size from pg_sequences as seq${seqWhere === "" ? "" : ` WHERE ${seqWhere}`};`
      );
      for (const dbSeq of allSequences) {
        const schemaName = dbSeq.schemaname;
        const sequenceName = dbSeq.sequencename;
        const startValue = stringFromDatabaseIdentityProperty(dbSeq.start_value);
        const minValue = stringFromDatabaseIdentityProperty(dbSeq.min_value);
        const maxValue = stringFromDatabaseIdentityProperty(dbSeq.max_value);
        const incrementBy = stringFromDatabaseIdentityProperty(dbSeq.increment_by);
        const cycle = dbSeq.cycle;
        const cacheSize = stringFromDatabaseIdentityProperty(dbSeq.cache_size);
        const key = `${schemaName}.${sequenceName}`;
        sequencesToReturn[key] = {
          name: sequenceName,
          schema: schemaName,
          startWith: startValue,
          minValue,
          maxValue,
          increment: incrementBy,
          cycle,
          cache: cacheSize
        };
      }
      const whereEnums = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
      const allEnums = await db.query(
        `select n.nspname as enum_schema,
  t.typname as enum_name,
  e.enumlabel as enum_value,
  e.enumsortorder as sort_order
  from pg_type t
  join pg_enum e on t.oid = e.enumtypid
  join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`}
  order by enum_schema, enum_name, sort_order;`
      );
      const enumsToReturn = {};
      for (const dbEnum of allEnums) {
        const enumName = dbEnum.enum_name;
        const enumValue = dbEnum.enum_value;
        const enumSchema4 = dbEnum.enum_schema || "public";
        const key = `${enumSchema4}.${enumName}`;
        if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
          enumsToReturn[key].values.push(enumValue);
        } else {
          enumsToReturn[key] = {
            name: enumName,
            values: [enumValue],
            schema: enumSchema4
          };
        }
      }
      if (progressCallback) {
        progressCallback("enums", Object.keys(enumsToReturn).length, "done");
      }
      const allRoles = await db.query(
        `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
      );
      const rolesToReturn = {};
      const preparedRoles = prepareRoles(entities);
      if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
        for (const dbRole of allRoles) {
          if (preparedRoles.useRoles) {
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreatedb,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          } else {
            if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue;
            if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue;
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreaterole,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          }
        }
      }
      const schemasForLinkedPoliciesInSchema = Object.values((tsSchema == null ? void 0 : tsSchema.policies) ?? {}).map((it) => it.schema);
      const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t4) => `schemaname = '${t4}'`).join(" or ");
      const policiesByTable = {};
      const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
      for (const dbPolicy of allPolicies) {
        const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
        const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
        const parsedTo = typeof to === "string" ? to.slice(1, -1).split(",") : to;
        const parsedWithCheck = withCheck === null ? void 0 : withCheck;
        const parsedUsing = using === null ? void 0 : using;
        if (tableForPolicy) {
          tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
        } else {
          policiesByTable[`${schemaname}.${tablename}`] = {
            [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
          };
        }
        if (tsSchema == null ? void 0 : tsSchema.policies[dbPolicy.name]) {
          policies[dbPolicy.name] = {
            ...rest,
            to: parsedTo,
            withCheck: parsedWithCheck,
            using: parsedUsing,
            on: tsSchema == null ? void 0 : tsSchema.policies[dbPolicy.name].on
          };
        }
      }
      if (progressCallback) {
        progressCallback(
          "policies",
          Object.values(policiesByTable).reduce((total, innerRecord) => {
            return total + Object.keys(innerRecord).length;
          }, 0),
          "done"
        );
      }
      const sequencesInColumns = [];
      const all = allTables.filter((it) => it.type === "table").map((row) => {
        return new Promise(async (res, rej) => {
          var _a2, _b, _c, _d, _e, _f;
          const tableName = row.table_name;
          if (!tablesFilter(tableName)) return res("");
          tableCount += 1;
          const tableSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const indexToReturn = {};
            const foreignKeysToReturn = {};
            const primaryKeys = {};
            const uniqueConstrains = {};
            const checkConstraints = {};
            const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
            const tableConstraints = await db.query(
              `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
      FROM information_schema.table_constraints tc
      JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
      JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
        AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
      WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
            );
            const tableChecks = await db.query(`SELECT 
						tc.constraint_name,
						tc.constraint_type,
						pg_get_constraintdef(con.oid) AS constraint_definition
					FROM 
						information_schema.table_constraints AS tc
						JOIN pg_constraint AS con 
							ON tc.constraint_name = con.conname
							AND con.conrelid = (
								SELECT oid 
								FROM pg_class 
								WHERE relname = tc.table_name 
								AND relnamespace = (
									SELECT oid 
									FROM pg_namespace 
									WHERE nspname = tc.constraint_schema
								)
							)
					WHERE 
						tc.table_name = '${tableName}'
						AND tc.constraint_schema = '${tableSchema}'
						AND tc.constraint_type = 'CHECK';`);
            columnsCount += tableResponse.length;
            if (progressCallback) {
              progressCallback("columns", columnsCount, "fetching");
            }
            const tableForeignKeys = await db.query(
              `SELECT
            con.contype AS constraint_type,
            nsp.nspname AS constraint_schema,
            con.conname AS constraint_name,
            rel.relname AS table_name,
            att.attname AS column_name,
            fnsp.nspname AS foreign_table_schema,
            frel.relname AS foreign_table_name,
            fatt.attname AS foreign_column_name,
            CASE con.confupdtype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS update_rule,
            CASE con.confdeltype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS delete_rule
          FROM
            pg_catalog.pg_constraint con
            JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
            JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
            LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
              AND att.attrelid = con.conrelid
            LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
            LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
            LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
              AND fatt.attrelid = con.confrelid
          WHERE
            nsp.nspname = '${tableSchema}'
            AND rel.relname = '${tableName}'
            AND con.contype IN ('f');`
            );
            foreignKeysCount += tableForeignKeys.length;
            if (progressCallback) {
              progressCallback("fks", foreignKeysCount, "fetching");
            }
            for (const fk5 of tableForeignKeys) {
              const columnFrom = fk5.column_name;
              const tableTo = fk5.foreign_table_name;
              const columnTo = fk5.foreign_column_name;
              const schemaTo = fk5.foreign_table_schema;
              const foreignKeyName = fk5.constraint_name;
              const onUpdate = (_a2 = fk5.update_rule) == null ? void 0 : _a2.toLowerCase();
              const onDelete = (_b = fk5.delete_rule) == null ? void 0 : _b.toLowerCase();
              if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
                foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
                foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
              } else {
                foreignKeysToReturn[foreignKeyName] = {
                  name: foreignKeyName,
                  tableFrom: tableName,
                  tableTo,
                  schemaTo,
                  columnsFrom: [columnFrom],
                  columnsTo: [columnTo],
                  onDelete,
                  onUpdate
                };
              }
              foreignKeysToReturn[foreignKeyName].columnsFrom = [
                ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
              ];
              foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
            }
            const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
            for (const unqs of uniqueConstrainsRows) {
              const columnName = unqs.column_name;
              const constraintName = unqs.constraint_name;
              if (typeof uniqueConstrains[constraintName] !== "undefined") {
                uniqueConstrains[constraintName].columns.push(columnName);
              } else {
                uniqueConstrains[constraintName] = {
                  columns: [columnName],
                  nullsNotDistinct: false,
                  name: constraintName
                };
              }
            }
            checksCount += tableChecks.length;
            if (progressCallback) {
              progressCallback("checks", checksCount, "fetching");
            }
            for (const checks of tableChecks) {
              let checkValue = checks.constraint_definition;
              const constraintName = checks.constraint_name;
              checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
              checkConstraints[constraintName] = {
                name: constraintName,
                value: checkValue
              };
            }
            for (const columnResponse of tableResponse) {
              const columnName = columnResponse.column_name;
              const columnAdditionalDT = columnResponse.additional_dt;
              const columnDimensions = columnResponse.array_dimensions;
              const enumType2 = columnResponse.enum_name;
              let columnType = columnResponse.data_type;
              const typeSchema = columnResponse.type_schema;
              const defaultValueRes = columnResponse.column_default;
              const isGenerated = columnResponse.is_generated === "ALWAYS";
              const generationExpression = columnResponse.generation_expression;
              const isIdentity = columnResponse.is_identity === "YES";
              const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = columnResponse.identity_start;
              const identityIncrement = columnResponse.identity_increment;
              const identityMaximum = columnResponse.identity_maximum;
              const identityMinimum = columnResponse.identity_minimum;
              const identityCycle = columnResponse.identity_cycle === "YES";
              const identityName = columnResponse.seq_name;
              const primaryKey = tableConstraints.filter(
                (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
              );
              const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
              if (cprimaryKey.length > 1) {
                const tableCompositePkName = await db.query(
                  `SELECT conname AS primary_key
            FROM   pg_constraint join pg_class on (pg_class.oid = conrelid)
            WHERE  contype = 'p' 
            AND    connamespace = $1::regnamespace  
            AND    pg_class.relname = $2;`,
                  [tableSchema, tableName]
                );
                primaryKeys[tableCompositePkName[0].primary_key] = {
                  name: tableCompositePkName[0].primary_key,
                  columns: cprimaryKey.map((c3) => c3.column_name)
                };
              }
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(columnResponse, internals, tableName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
                // default: isSerial ? undefined : defaultValue,
                notNull: columnResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
                  cycle: identityCycle,
                  schema: tableSchema
                } : void 0
              };
              if (identityName && typeof identityName === "string") {
                delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const dbIndexes = await db.query(
              `SELECT  DISTINCT ON (t.relname, ic.relname, k.i) t.relname as table_name, ic.relname AS indexname,
        k.i AS index_order,
        i.indisunique as is_unique,
        am.amname as method,
        ic.reloptions as with,
        coalesce(a.attname, pg_get_indexdef(i.indexrelid, k.i, false)) AS column_name,
          CASE
        WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
        ELSE 0
    END AS is_expression,
        i.indoption[k.i-1] & 1 = 1 AS descending,
        i.indoption[k.i-1] & 2 = 2 AS nulls_first,
        pg_get_expr(
                              i.indpred,
                              i.indrelid
                          ) as where,
         opc.opcname
      FROM pg_class t
          LEFT JOIN pg_index i ON t.oid = i.indrelid
          LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
		  CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
          LEFT JOIN pg_attribute AS a
            ON i.indrelid = a.attrelid AND k.attnum = a.attnum
          JOIN pg_namespace c on c.oid = t.relnamespace
        LEFT JOIN pg_am AS am ON ic.relam = am.oid
        JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
      WHERE
      c.nspname = '${tableSchema}' AND
      t.relname = '${tableName}';`
            );
            const dbIndexFromConstraint = await db.query(
              `SELECT
          idx.indexrelname AS index_name,
          idx.relname AS table_name,
          schemaname,
          CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
        FROM
          pg_stat_user_indexes idx
        LEFT JOIN
          pg_constraint con ON con.conindid = idx.indexrelid
        WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
        group by index_name, table_name,schemaname, generated_by_constraint;`
            );
            const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
              (it) => it.index_name
            );
            for (const dbIndex of dbIndexes) {
              const indexName6 = dbIndex.indexname;
              const indexColumnName = dbIndex.column_name;
              const indexIsUnique = dbIndex.is_unique;
              const indexMethod = dbIndex.method;
              const indexWith = dbIndex.with;
              const indexWhere = dbIndex.where;
              const opclass = dbIndex.opcname;
              const isExpression = dbIndex.is_expression === 1;
              const desc = dbIndex.descending;
              const nullsFirst = dbIndex.nulls_first;
              const mappedWith = {};
              if (indexWith !== null) {
                indexWith.forEach((it) => {
                  const splitted = it.split("=");
                  mappedWith[splitted[0]] = splitted[1];
                });
              }
              if (idxsInConsteraint.includes(indexName6)) continue;
              if (typeof indexToReturn[indexName6] !== "undefined") {
                indexToReturn[indexName6].columns.push({
                  expression: indexColumnName,
                  asc: !desc,
                  nulls: nullsFirst ? "first" : "last",
                  opclass,
                  isExpression
                });
              } else {
                indexToReturn[indexName6] = {
                  name: indexName6,
                  columns: [
                    {
                      expression: indexColumnName,
                      asc: !desc,
                      nulls: nullsFirst ? "first" : "last",
                      opclass,
                      isExpression
                    }
                  ],
                  isUnique: indexIsUnique,
                  // should not be a part of diff detects
                  concurrently: false,
                  method: indexMethod,
                  where: indexWhere === null ? void 0 : indexWhere,
                  with: mappedWith
                };
              }
            }
            indexesCount += Object.keys(indexToReturn).length;
            if (progressCallback) {
              progressCallback("indexes", indexesCount, "fetching");
            }
            result[`${tableSchema}.${tableName}`] = {
              name: tableName,
              schema: tableSchema !== "public" ? tableSchema : "",
              columns: columnToReturn,
              indexes: indexToReturn,
              foreignKeys: foreignKeysToReturn,
              compositePrimaryKeys: primaryKeys,
              uniqueConstraints: uniqueConstrains,
              checkConstraints,
              policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
              isRLSEnabled: row.rls_enabled
            };
          } catch (e4) {
            rej(e4);
            return;
          }
          res("");
        });
      });
      if (progressCallback) {
        progressCallback("tables", tableCount, "done");
      }
      for await (const _3 of all) {
      }
      const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
        return new Promise(async (res, rej) => {
          var _a2, _b, _c, _d;
          const viewName = row.table_name;
          if (!tablesFilter(viewName)) return res("");
          tableCount += 1;
          const viewSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
            for (const viewResponse of viewResponses) {
              const columnName = viewResponse.column_name;
              const columnAdditionalDT = viewResponse.additional_dt;
              const columnDimensions = viewResponse.array_dimensions;
              const enumType2 = viewResponse.enum_name;
              let columnType = viewResponse.data_type;
              const typeSchema = viewResponse.type_schema;
              const isGenerated = viewResponse.is_generated === "ALWAYS";
              const generationExpression = viewResponse.generation_expression;
              const isIdentity = viewResponse.is_identity === "YES";
              const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = viewResponse.identity_start;
              const identityIncrement = viewResponse.identity_increment;
              const identityMaximum = viewResponse.identity_maximum;
              const identityMinimum = viewResponse.identity_minimum;
              const identityCycle = viewResponse.identity_cycle === "YES";
              const identityName = viewResponse.seq_name;
              const defaultValueRes = viewResponse.column_default;
              const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(viewResponse, internals, viewName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey,
                notNull: viewResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: ((_a2 = sequencesToReturn[identityName]) == null ? void 0 : _a2.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
                  cycle: identityCycle,
                  schema: viewSchema
                } : void 0
              };
              if (identityName) {
                delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const [viewInfo] = await db.query(`
					SELECT
    c.relname AS view_name,
    n.nspname AS schema_name,
    pg_get_viewdef(c.oid, true) AS definition,
    ts.spcname AS tablespace_name,
    c.reloptions AS options,
    pg_tablespace_location(ts.oid) AS location
FROM
    pg_class c
JOIN
    pg_namespace n ON c.relnamespace = n.oid
LEFT JOIN
    pg_tablespace ts ON c.reltablespace = ts.oid 
WHERE
    (c.relkind = 'm' OR c.relkind = 'v')
    AND n.nspname = '${viewSchema}'
    AND c.relname = '${viewName}';`);
            const resultWith = {};
            if (viewInfo.options) {
              viewInfo.options.forEach((pair) => {
                const splitted = pair.split("=");
                const key = splitted[0];
                const value = splitted[1];
                if (value === "true") {
                  resultWith[key] = true;
                } else if (value === "false") {
                  resultWith[key] = false;
                } else if (!isNaN(Number(value))) {
                  resultWith[key] = Number(value);
                } else {
                  resultWith[key] = value;
                }
              });
            }
            const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
            const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
            const materialized = row.type === "materialized_view";
            views[`${viewSchema}.${viewName}`] = {
              name: viewName,
              schema: viewSchema,
              columns: columnToReturn,
              isExisting: false,
              definition,
              materialized,
              with: withOption,
              tablespace: viewInfo.tablespace_name ?? void 0
            };
          } catch (e4) {
            rej(e4);
            return;
          }
          res("");
        });
      });
      viewsCount = allViews.length;
      for await (const _3 of allViews) {
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("indexes", indexesCount, "done");
        progressCallback("fks", foreignKeysCount, "done");
        progressCallback("checks", checksCount, "done");
        progressCallback("views", viewsCount, "done");
      }
      const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies,
        views,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
    defaultForColumn = (column11, internals, tableName) => {
      var _a2, _b;
      const columnName = column11.column_name;
      const isArray = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
      if (column11.column_default === null || column11.column_default === void 0 || column11.data_type === "serial" || column11.data_type === "smallserial" || column11.data_type === "bigserial") {
        return void 0;
      }
      if (column11.column_default.endsWith("[]")) {
        column11.column_default = column11.column_default.slice(0, -2);
      }
      column11.column_default = column11.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
      const columnDefaultAsString = column11.column_default.toString();
      if (isArray) {
        return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
          if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type.slice(0, -2))) {
            return value;
          } else if (column11.data_type.startsWith("timestamp")) {
            return `${value}`;
          } else if (column11.data_type.slice(0, -2) === "interval") {
            return value.replaceAll('"', `"`);
          } else if (column11.data_type.slice(0, -2) === "boolean") {
            return value === "t" ? "true" : "false";
          } else if (["json", "jsonb"].includes(column11.data_type.slice(0, -2))) {
            return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
          } else {
            return `"${value}"`;
          }
        }).join(",")}}'`;
      }
      if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type)) {
        if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
          return Number(columnDefaultAsString);
        } else {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
          return columnDefaultAsString;
        }
      } else if (column11.data_type.includes("numeric")) {
        return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
      } else if (column11.data_type === "json" || column11.data_type === "jsonb") {
        const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
        return `'${jsonWithoutSpaces}'::${column11.data_type}`;
      } else if (column11.data_type === "boolean") {
        return column11.column_default === "true";
      } else if (columnDefaultAsString === "NULL") {
        return `NULL`;
      } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
        return columnDefaultAsString;
      } else {
        return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
      }
    };
    getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => {
      return db.query(
        `SELECT 
    a.attrelid::regclass::text AS table_name,  -- Table, view, or materialized view name
    a.attname AS column_name,   -- Column name
    CASE 
        WHEN NOT a.attisdropped THEN 
            CASE 
                WHEN a.attnotnull THEN 'NO'
                ELSE 'YES'
            END 
        ELSE NULL 
    END AS is_nullable,  -- NULL or NOT NULL constraint
    a.attndims AS array_dimensions,  -- Array dimensions
    CASE 
        WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) 
        AND EXISTS (
            SELECT FROM pg_attrdef ad
            WHERE ad.adrelid = a.attrelid 
            AND ad.adnum = a.attnum 
            AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' 
                || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
        )
        THEN CASE a.atttypid
            WHEN 'int'::regtype THEN 'serial'
            WHEN 'int8'::regtype THEN 'bigserial'
            WHEN 'int2'::regtype THEN 'smallserial'
        END
        ELSE format_type(a.atttypid, a.atttypmod)
    END AS data_type,  -- Column data type
--    ns.nspname AS type_schema,  -- Schema name
    pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name,  -- Serial sequence (if any)
    c.column_default,  -- Column default value
    c.data_type AS additional_dt,  -- Data type from information_schema
    c.udt_name AS enum_name,  -- Enum type (if applicable)
    c.is_generated,  -- Is it a generated column?
    c.generation_expression,  -- Generation expression (if generated)
    c.is_identity,  -- Is it an identity column?
    c.identity_generation,  -- Identity generation strategy (ALWAYS or BY DEFAULT)
    c.identity_start,  -- Start value of identity column
    c.identity_increment,  -- Increment for identity column
    c.identity_maximum,  -- Maximum value for identity column
    c.identity_minimum,  -- Minimum value for identity column
    c.identity_cycle,  -- Does the identity column cycle?
    enum_ns.nspname AS type_schema  -- Schema of the enum type
FROM 
    pg_attribute a
JOIN 
    pg_class cls ON cls.oid = a.attrelid  -- Join pg_class to get table/view/materialized view info
JOIN 
    pg_namespace ns ON ns.oid = cls.relnamespace  -- Join namespace to get schema info
LEFT JOIN 
    information_schema.columns c ON c.column_name = a.attname 
        AND c.table_schema = ns.nspname 
        AND c.table_name = cls.relname  -- Match schema and table/view name
LEFT JOIN 
    pg_type enum_t ON enum_t.oid = a.atttypid  -- Join to get the type info
LEFT JOIN 
    pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace  -- Join to get the enum schema
WHERE 
    a.attnum > 0  -- Valid column numbers only
    AND NOT a.attisdropped  -- Skip dropped columns
    AND cls.relkind IN ('r', 'v', 'm')  -- Include regular tables ('r'), views ('v'), and materialized views ('m')
    AND ns.nspname = '${schema6}'  -- Filter by schema
    AND cls.relname = '${table6}'  -- Filter by table name
ORDER BY 
    a.attnum;  -- Order by column number`
      );
    };
  }
});

// src/serializer/sqliteImports.ts
var sqliteImports_exports = {};
__export(sqliteImports_exports, {
  prepareFromExports: () => prepareFromExports3,
  prepareFromSqliteImports: () => prepareFromSqliteImports
});
var import_drizzle_orm5, import_sqlite_core, prepareFromExports3, prepareFromSqliteImports;
var init_sqliteImports = __esm({
  "src/serializer/sqliteImports.ts"() {
    "use strict";
    import_drizzle_orm5 = require("drizzle-orm");
    import_sqlite_core = require("drizzle-orm/sqlite-core");
    init_utils3();
    prepareFromExports3 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t4) => {
        if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteTable)) {
          tables.push(t4);
        }
        if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteView)) {
          views.push(t4);
        }
      });
      return { tables, views };
    };
    prepareFromSqliteImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports3(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/sqliteSerializer.ts
var sqliteSerializer_exports = {};
__export(sqliteSerializer_exports, {
  fromDatabase: () => fromDatabase3,
  generateSqliteSnapshot: () => generateSqliteSnapshot
});
function mapSqlToSqliteType(sqlType) {
  const lowered = sqlType.toLowerCase();
  if ([
    "int",
    "integer",
    "integer auto_increment",
    "tinyint",
    "smallint",
    "mediumint",
    "bigint",
    "unsigned big int",
    "int2",
    "int8"
  ].some((it) => lowered.startsWith(it))) {
    return "integer";
  } else if ([
    "character",
    "varchar",
    "varying character",
    "national varying character",
    "nchar",
    "native character",
    "nvarchar",
    "text",
    "clob"
  ].some((it) => lowered.startsWith(it))) {
    const match2 = lowered.match(/\d+/);
    if (match2) {
      return `text(${match2[0]})`;
    }
    return "text";
  } else if (lowered.startsWith("blob")) {
    return "blob";
  } else if (["real", "double", "double precision", "float"].some((it) => lowered.startsWith(it))) {
    return "real";
  } else {
    return "numeric";
  }
}
function extractGeneratedColumns(input) {
  const columns = {};
  const lines = input.split(/,\s*(?![^()]*\))/);
  for (const line of lines) {
    if (line.includes("GENERATED ALWAYS AS")) {
      const parts = line.trim().split(/\s+/);
      const columnName = parts[0].replace(/[`'"]/g, "");
      const expression = line.substring(line.indexOf("("), line.indexOf(")") + 1).trim();
      const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i));
      let type = "virtual";
      if (typeIndex !== -1) {
        type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase();
      }
      columns[columnName] = {
        columnName,
        expression,
        type
      };
    }
  }
  return columns;
}
function filterIgnoredTablesByField(fieldName) {
  return `${fieldName} != '__drizzle_migrations'
			AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
}
var import_drizzle_orm6, import_sqlite_core2, generateSqliteSnapshot, fromDatabase3;
var init_sqliteSerializer = __esm({
  "src/serializer/sqliteSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm6 = require("drizzle-orm");
    import_sqlite_core2 = require("drizzle-orm/sqlite-core");
    init_outputs();
    init_utils2();
    init_utils4();
    generateSqliteSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_sqlite_core2.SQLiteSyncDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { indexes: {} };
      for (const table6 of tables) {
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          checks,
          foreignKeys: tableForeignKeys,
          primaryKeys,
          uniqueConstraints
        } = (0, import_sqlite_core2.getTableConfig)(table6);
        columns.forEach((column11) => {
          const name = getColumnCasing(column11, casing2);
          const notNull = column11.notNull;
          const primaryKey = column11.primary;
          const generated = column11.generated;
          const columnToSet = {
            name,
            type: column11.getSQLType(),
            primaryKey,
            notNull,
            autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.autoIncrement : false,
            generated: generated ? {
              as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
              type: generated.mode ?? "virtual"
            } : void 0
          };
          if (column11.default !== void 0) {
            if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) {
              columnToSet.default = sqlToStr(column11.default, casing2);
            } else {
              columnToSet.default = typeof column11.default === "string" ? `'${escapeSingleQuotes(column11.default)}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default;
            }
          }
          columnsObject[name] = columnToSet;
          if (column11.isUnique) {
            const existingUnique = indexesObject[column11.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column11.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            indexesObject[column11.uniqueName] = {
              name: column11.uniqueName,
              columns: [columnToSet.name],
              isUnique: true
            };
          }
        });
        const foreignKeys = tableForeignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = (0, import_drizzle_orm6.getTableName)(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
              name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
            }
            for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
              name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        foreignKeys.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            var _a2;
            if ((0, import_drizzle_orm6.is)(it, import_drizzle_orm6.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return getColumnCasing(it, casing2);
            }
          });
          let where = void 0;
          if (value.config.where !== void 0) {
            if ((0, import_drizzle_orm6.is)(value.config.where, import_drizzle_orm6.SQL)) {
              where = dialect6.sqlToQuery(value.config.where).sql;
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where
          };
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
          const name = unq.name ?? (0, import_sqlite_core2.uniqueKeyName)(table6, columnNames);
          const existingUnique = indexesObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          indexesObject[name] = {
            name: unq.name,
            columns: columnNames,
            isUnique: true
          };
        });
        primaryKeys.forEach((it) => {
          if (it.columns.length > 1) {
            const originalColumnNames = it.columns.map((c3) => c3.name);
            const columnNames = it.columns.map((c3) => getColumnCasing(c3, casing2));
            let name = it.getName();
            if (casing2 !== void 0) {
              for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
                name = name.replace(originalColumnNames[i4], columnNames[i4]);
              }
            }
            primaryKeysObject[name] = {
              columns: columnNames,
              name
            };
          } else {
            columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
          }
        });
        checks.forEach((check2) => {
          const checkName = check2.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check2.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check2.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.value).sql
          };
        });
        result[tableName] = {
          name: tableName,
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          checkConstraints: checkConstraintObject
        };
      }
      for (const view5 of views) {
        const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core2.getViewConfig)(view5);
        const columnsObject = {};
        const existingView = resultViews[name];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema6 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm6.is)(selectedFields[key], import_sqlite_core2.SQLiteColumn)) {
            const column11 = selectedFields[key];
            const notNull = column11.notNull;
            const primaryKey = column11.primary;
            const generated = column11.generated;
            const columnToSet = {
              name: column11.name,
              type: column11.getSQLType(),
              primaryKey,
              notNull,
              autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.autoIncrement : false,
              generated: generated ? {
                as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
                type: generated.mode ?? "virtual"
              } : void 0
            };
            if (column11.default !== void 0) {
              if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) {
                columnToSet.default = sqlToStr(column11.default, casing2);
              } else {
                columnToSet.default = typeof column11.default === "string" ? `'${column11.default}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default;
              }
            }
            columnsObject[column11.name] = columnToSet;
          }
        }
        resultViews[name] = {
          columns: columnsObject,
          name,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql
        };
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase3 = async (db, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const resultViews = {};
      const columns = await db.query(`SELECT 
		  m.name as "tableName",
		  p.name as "columnName",
		  p.type as "columnType",
		  p."notnull" as "notNull",
		  p.dflt_value as "defaultValue",
		  p.pk as pk,
		  p.hidden as hidden,
		  m.sql,
		  m.type as type
		FROM sqlite_master AS m
		JOIN pragma_table_xinfo(m.name) AS p
		WHERE (m.type = 'table' OR m.type = 'view') 
		  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      const tablesWithSeq = [];
      const seq = await db.query(`SELECT
		  *
		FROM sqlite_master
		WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*'
    	  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const s4 of seq) {
        tablesWithSeq.push(s4.name);
      }
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const tableToPk = {};
      let tableToGeneratedColumnsInfo = {};
      for (const column11 of columns) {
        if (!tablesFilter(column11.tableName)) continue;
        if (column11.type !== "view") {
          columnsCount += 1;
        }
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const tableName = column11.tableName;
        tablesCount.add(tableName);
        if (progressCallback) {
          progressCallback("tables", tablesCount.size, "fetching");
        }
        const columnName = column11.columnName;
        const isNotNull = column11.notNull === 1;
        const columnType = column11.columnType;
        const isPrimary = column11.pk !== 0;
        const columnDefault = column11.defaultValue;
        const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
        if (isPrimary) {
          if (typeof tableToPk[tableName] === "undefined") {
            tableToPk[tableName] = [columnName];
          } else {
            tableToPk[tableName].push(columnName);
          }
        }
        const table6 = result[tableName];
        if (column11.hidden === 2 || column11.hidden === 3) {
          if (typeof tableToGeneratedColumnsInfo[column11.tableName] === "undefined") {
            tableToGeneratedColumnsInfo[column11.tableName] = extractGeneratedColumns(
              column11.sql
            );
          }
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
            columnDefault
          ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: mapSqlToSqliteType(columnType),
          primaryKey: false,
          notNull: isNotNull,
          generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? {
            type: tableToGeneratedColumnsInfo[tableName][columnName].type,
            as: tableToGeneratedColumnsInfo[tableName][columnName].expression
          } : void 0
        };
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        if (value.length > 1) {
          result[key].compositePrimaryKeys = {
            [`${key}_${value.join("_")}_pk`]: {
              columns: value,
              name: `${key}_${value.join("_")}_pk`
            }
          };
        } else if (value.length === 1) {
          result[key].columns[value[0]].primaryKey = true;
        } else {
        }
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(`SELECT
			  m.name as "tableFrom",
			  f.id as "id",
			  f."table" as "tableTo",
			  f."from",
			  f."to",
			  f."on_update" as "onUpdate",
			  f."on_delete" as "onDelete",
			  f.seq as "seq"
      		FROM
			  sqlite_master m,
			  pragma_foreign_key_list(m.name) as f
      		WHERE ${filterIgnoredTablesByField("m.tbl_name")};`);
        const fkByTableName = {};
        for (const fkRow of fks) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableName = fkRow.tableFrom;
          const columnName = fkRow.from;
          const refTableName = fkRow.tableTo;
          const refColumnName = fkRow.to;
          const updateRule = fkRow.onUpdate;
          const deleteRule = fkRow.onDelete;
          const sequence = fkRow.seq;
          const id = fkRow.id;
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
            fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
            fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
          } else {
            fkByTableName[`${tableName}_${id}`] = {
              name: "",
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
              onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
            };
          }
          const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
          const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
          fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
            "_"
          )}_${refTableName}_${columnsTo.join("_")}_fk`;
        }
        for (const idx of Object.keys(fkByTableName)) {
          const value = fkByTableName[idx];
          result[value.tableFrom].foreignKeys[value.name] = value;
        }
      } catch (e4) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      const idxs = await db.query(`SELECT 
    	  m.tbl_name as tableName,
    	  il.name as indexName,
    	  ii.name as columnName,
    	  il.[unique] as isUnique,
    	  il.seq as seq
		FROM 
		  sqlite_master AS m,
    	  pragma_index_list(m.name) AS il,
    	  pragma_index_info(il.name) AS ii
		WHERE 
		  m.type = 'table' 
    	  AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\'
    	  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      for (const idxRow of idxs) {
        const tableName = idxRow.tableName;
        const constraintName = idxRow.indexName;
        const columnName = idxRow.columnName;
        const isUnique = idxRow.isUnique === 1;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) {
          tableInResult.indexes[constraintName].columns.push(columnName);
        } else {
          tableInResult.indexes[constraintName] = {
            name: constraintName,
            columns: columnName ? [columnName] : [],
            isUnique
          };
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      const views = await db.query(
        `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
      );
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for (const view5 of views) {
        const viewName = view5["view_name"];
        const sql = view5["sql"];
        const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
        const match2 = sql.match(regex);
        if (!match2) {
          console.log("Could not process view");
          process.exit(1);
        }
        const viewDefinition = match2[1];
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          definition: viewDefinition
        };
      }
      if (progressCallback) {
        progressCallback("views", viewsCount, "done");
      }
      const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
      const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
      let checkCounter = 0;
      const checkConstraints = {};
      const checks = await db.query(`SELECT
		  name as "tableName",
		  sql as "sql"
		FROM sqlite_master 
		WHERE type = 'table'
		  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const check2 of checks) {
        if (!tablesFilter(check2.tableName)) continue;
        const { tableName, sql } = check2;
        let namedChecks = [...sql.matchAll(namedCheckPattern)];
        if (namedChecks.length > 0) {
          namedChecks.forEach(([_3, checkName, checkValue]) => {
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        } else {
          let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)];
          unnamedChecks.forEach(([_3, checkValue]) => {
            let checkName = `${tableName}_check_${++checkCounter}`;
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        }
        checksCount += Object.values(checkConstraints).length;
        if (progressCallback) {
          progressCallback("checks", checksCount, "fetching");
        }
        const table6 = result[tableName];
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {},
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints
          };
        } else {
          result[tableName].checkConstraints = checkConstraints;
        }
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        }
      };
    };
  }
});

// src/serializer/singlestoreImports.ts
var singlestoreImports_exports = {};
__export(singlestoreImports_exports, {
  prepareFromExports: () => prepareFromExports4,
  prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
});
var import_drizzle_orm7, import_singlestore_core, prepareFromExports4, prepareFromSingleStoreImports;
var init_singlestoreImports = __esm({
  "src/serializer/singlestoreImports.ts"() {
    "use strict";
    import_drizzle_orm7 = require("drizzle-orm");
    import_singlestore_core = require("drizzle-orm/singlestore-core");
    init_utils3();
    prepareFromExports4 = (exports2) => {
      const tables = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t4) => {
        if ((0, import_drizzle_orm7.is)(t4, import_singlestore_core.SingleStoreTable)) {
          tables.push(t4);
        }
      });
      return {
        tables
        /* views  */
      };
    };
    prepareFromSingleStoreImports = async (imports) => {
      const tables = [];
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports4(i0);
        tables.push(...prepared.tables);
      }
      unregister();
      return {
        tables: Array.from(new Set(tables))
        /* , views */
      };
    };
  }
});

// src/serializer/singlestoreSerializer.ts
var singlestoreSerializer_exports = {};
__export(singlestoreSerializer_exports, {
  fromDatabase: () => fromDatabase4,
  generateSingleStoreSnapshot: () => generateSingleStoreSnapshot,
  indexName: () => indexName3
});
function clearDefaults2(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
    } else {
      return `'${resultDefault}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var import_drizzle_orm8, import_singlestore_core2, dialect5, indexName3, generateSingleStoreSnapshot, fromDatabase4;
var init_singlestoreSerializer = __esm({
  "src/serializer/singlestoreSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm8 = require("drizzle-orm");
    import_singlestore_core2 = require("drizzle-orm/singlestore-core");
    init_outputs();
    init_utils4();
    dialect5 = new import_singlestore_core2.SingleStoreDialect();
    indexName3 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generateSingleStoreSnapshot = (tables, casing2) => {
      const dialect6 = new import_singlestore_core2.SingleStoreDialect({ casing: casing2 });
      const result = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          schema: schema6,
          primaryKeys,
          uniqueConstraints
        } = (0, import_singlestore_core2.getTableConfig)(table6);
        const columnsObject = {};
        const indexesObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        columns.forEach((column11) => {
          const notNull = column11.notNull;
          const sqlTypeLowered = column11.getSQLType().toLowerCase();
          const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
          const generated = column11.generated;
          const columnToSet = {
            name: column11.name,
            type: column11.getSQLType(),
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column11.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm8.is)(generated.as, import_drizzle_orm8.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column11.primary) {
            primaryKeysObject[`${tableName}_${column11.name}`] = {
              name: `${tableName}_${column11.name}`,
              columns: [column11.name]
            };
          }
          if (column11.isUnique) {
            const existingUnique = uniqueConstraintObject[column11.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column11.uniqueName
                )} on the ${source_default.underline.blue(
                  column11.name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column11.uniqueName] = {
              name: column11.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column11.default !== void 0) {
            if ((0, import_drizzle_orm8.is)(column11.default, import_drizzle_orm8.SQL)) {
              columnToSet.default = sqlToStr(column11.default, casing2);
            } else {
              if (typeof column11.default === "string") {
                columnToSet.default = `'${column11.default}'`;
              } else {
                if (sqlTypeLowered === "json" || Array.isArray(column11.default)) {
                  columnToSet.default = `'${JSON.stringify(column11.default)}'`;
                } else if (column11.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column11.default;
                }
              }
            }
          }
          columnsObject[column11.name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const columnNames = pk.columns.map((c3) => c3.name);
          primaryKeysObject[pk.getName()] = {
            name: pk.getName(),
            columns: columnNames
          };
          for (const column11 of pk.columns) {
            columnsObject[column11.name].notNull = true;
          }
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c3) => c3.name);
          const name = unq.name ?? (0, import_singlestore_core2.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            columns: columnNames
          };
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            var _a2;
            if ((0, import_drizzle_orm8.is)(it, import_drizzle_orm8.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return `${it.name}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorythm,
            lock: value.config.lock
          };
        });
        if (!schema6) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject
          };
        }
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column11 of response) {
        if (!tablesFilter(column11["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column11["TABLE_SCHEMA"];
        const tableName = column11["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column11["COLUMN_NAME"];
        const isNullable = column11["IS_NULLABLE"] === "YES";
        const dataType = column11["DATA_TYPE"];
        const columnType = column11["COLUMN_TYPE"];
        const isPrimary = column11["COLUMN_KEY"] === "PRI";
        let columnDefault = column11["COLUMN_DEFAULT"];
        const collation = column11["CHARACTER_SET_NAME"];
        const geenratedExpression = column11["GENERATION_EXPRESSION"];
        let columnExtra = column11["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column11["EXTRA"] !== "undefined") {
          columnExtra = column11["EXTRA"];
          isAutoincrement = column11["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) {
          changedType = columnType.replace(/\(\s*[^)]*\)$/, "");
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        if (columnDefault == null ? void 0 : columnDefault.endsWith(".")) {
          columnDefault = columnDefault.slice(0, -1);
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            uniqueConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='UNIQUE'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["table_name"];
        const columnName = tableToPkRow["column_name"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// src/serializer/index.ts
var import_fs4, glob, import_path4, serializeMySql, serializePg, serializeSQLite, serializeSingleStore, prepareFilenames;
var init_serializer = __esm({
  "src/serializer/index.ts"() {
    "use strict";
    init_source();
    import_fs4 = __toESM(require("fs"));
    glob = __toESM(require_glob());
    import_path4 = __toESM(require("path"));
    init_views();
    serializeMySql = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      console.log(source_default.gray(`Reading schema files:
${filenames.join("\n")}
`));
      const { prepareFromMySqlImports: prepareFromMySqlImports2 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
      const { generateMySqlSnapshot: generateMySqlSnapshot2 } = await Promise.resolve().then(() => (init_mysqlSerializer(), mysqlSerializer_exports));
      const { tables, views } = await prepareFromMySqlImports2(filenames);
      return generateMySqlSnapshot2(tables, views, casing2);
    };
    serializePg = async (path4, casing2, schemaFilter) => {
      const filenames = prepareFilenames(path4);
      const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
      const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
      const { tables, enums, schemas, sequences, views, matViews, roles, policies } = await prepareFromPgImports2(
        filenames
      );
      return generatePgSnapshot2(tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter);
    };
    serializeSQLite = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      const { prepareFromSqliteImports: prepareFromSqliteImports2 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
      const { generateSqliteSnapshot: generateSqliteSnapshot2 } = await Promise.resolve().then(() => (init_sqliteSerializer(), sqliteSerializer_exports));
      const { tables, views } = await prepareFromSqliteImports2(filenames);
      return generateSqliteSnapshot2(tables, views, casing2);
    };
    serializeSingleStore = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      console.log(source_default.gray(`Reading schema files:
${filenames.join("\n")}
`));
      const { prepareFromSingleStoreImports: prepareFromSingleStoreImports2 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
      const { generateSingleStoreSnapshot: generateSingleStoreSnapshot2 } = await Promise.resolve().then(() => (init_singlestoreSerializer(), singlestoreSerializer_exports));
      const {
        tables
        /* views */
      } = await prepareFromSingleStoreImports2(filenames);
      return generateSingleStoreSnapshot2(
        tables,
        /* views, */
        casing2
      );
    };
    prepareFilenames = (path4) => {
      if (typeof path4 === "string") {
        path4 = [path4];
      }
      const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
      const result = path4.reduce((result2, cur) => {
        const globbed = glob.sync(`${prefix2}${cur}`);
        globbed.forEach((it) => {
          const fileName = import_fs4.default.lstatSync(it).isDirectory() ? null : import_path4.default.resolve(it);
          const filenames = fileName ? [fileName] : import_fs4.default.readdirSync(it).map((file) => import_path4.default.join(import_path4.default.resolve(it), file));
          filenames.filter((file) => !import_fs4.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
        });
        return result2;
      }, /* @__PURE__ */ new Set());
      const res = [...result];
      const errors = res.filter((it) => {
        return !(it.endsWith(".ts") || it.endsWith(".js") || it.endsWith(".cjs") || it.endsWith(".mjs") || it.endsWith(".mts") || it.endsWith(".cts"));
      });
      if (res.length === 0) {
        console.log(
          error(
            `No schema files found for path config [${path4.map((it) => `'${it}'`).join(", ")}]`
          )
        );
        console.log(
          error(
            `If path represents a file - please make sure to use .ts or other extension in the path`
          )
        );
        process.exit(1);
      }
      return res;
    };
  }
});

// src/migrationPreparator.ts
var import_crypto, import_fs5, prepareMySqlDbPushSnapshot, prepareSingleStoreDbPushSnapshot, prepareSQLiteDbPushSnapshot, prepareMySqlMigrationSnapshot, prepareSingleStoreMigrationSnapshot, prepareSqliteMigrationSnapshot, fillPgSnapshot, preparePgMigrationSnapshot, preparePrevSnapshot;
var init_migrationPreparator = __esm({
  "src/migrationPreparator.ts"() {
    "use strict";
    import_crypto = require("crypto");
    import_fs5 = __toESM(require("fs"));
    init_serializer();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    prepareMySqlDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeMySql(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      return { prev, cur: result };
    };
    prepareSingleStoreDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeSingleStore(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      return { prev, cur: result };
    };
    prepareSQLiteDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeSQLite(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = {
        version: version3,
        dialect: dialect6,
        id,
        prevId: idPrev,
        ...rest
      };
      return { prev, cur: result };
    };
    prepareMySqlMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
      const prevSnapshot = mysqlSchema.parse(
        preparePrevSnapshot(migrationFolders, dryMySql)
      );
      const serialized = await serializeMySql(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    prepareSingleStoreMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
      const prevSnapshot = singlestoreSchema.parse(
        preparePrevSnapshot(migrationFolders, drySingleStore)
      );
      const serialized = await serializeSingleStore(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    prepareSqliteMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
      const prevSnapshot = sqliteSchema.parse(
        preparePrevSnapshot(snapshots, drySQLite)
      );
      const serialized = await serializeSQLite(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = {
        version: version3,
        dialect: dialect6,
        id,
        prevId: idPrev,
        ...rest
      };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    fillPgSnapshot = ({
      serialized,
      id,
      idPrev
    }) => {
      return { id, prevId: idPrev, ...serialized };
    };
    preparePgMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
      const prevSnapshot = pgSchema.parse(preparePrevSnapshot(snapshots, dryPg));
      const serialized = await serializePg(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const result = { id, prevId: idPrev, ...serialized };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = fillPgSnapshot({ serialized: prevRest, id, idPrev });
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    preparePrevSnapshot = (snapshots, defaultPrev) => {
      let prevSnapshot;
      if (snapshots.length === 0) {
        prevSnapshot = defaultPrev;
      } else {
        const lastSnapshot = snapshots[snapshots.length - 1];
        prevSnapshot = JSON.parse(import_fs5.default.readFileSync(lastSnapshot).toString());
      }
      return prevSnapshot;
    };
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js
var require_heap = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js"(exports2, module2) {
    (function() {
      var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
      floor = Math.floor, min = Math.min;
      defaultCmp = function(x4, y2) {
        if (x4 < y2) {
          return -1;
        }
        if (x4 > y2) {
          return 1;
        }
        return 0;
      };
      insort = function(a3, x4, lo, hi, cmp) {
        var mid;
        if (lo == null) {
          lo = 0;
        }
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (lo < 0) {
          throw new Error("lo must be non-negative");
        }
        if (hi == null) {
          hi = a3.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x4, a3[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a3, [lo, lo - lo].concat(x4)), x4;
      };
      heappush = function(array2, item, cmp) {
        if (cmp == null) {
          cmp = defaultCmp;
        }
        array2.push(item);
        return _siftdown(array2, 0, array2.length - 1, cmp);
      };
      heappop = function(array2, cmp) {
        var lastelt, returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        lastelt = array2.pop();
        if (array2.length) {
          returnitem = array2[0];
          array2[0] = lastelt;
          _siftup(array2, 0, cmp);
        } else {
          returnitem = lastelt;
        }
        return returnitem;
      };
      heapreplace = function(array2, item, cmp) {
        var returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        returnitem = array2[0];
        array2[0] = item;
        _siftup(array2, 0, cmp);
        return returnitem;
      };
      heappushpop = function(array2, item, cmp) {
        var _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (array2.length && cmp(array2[0], item) < 0) {
          _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
          _siftup(array2, 0, cmp);
        }
        return item;
      };
      heapify = function(array2, cmp) {
        var i4, _i, _j, _len, _ref, _ref1, _results, _results1;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        _ref1 = function() {
          _results1 = [];
          for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
            _results1.push(_j2);
          }
          return _results1;
        }.apply(this).reverse();
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          i4 = _ref1[_i];
          _results.push(_siftup(array2, i4, cmp));
        }
        return _results;
      };
      updateItem = function(array2, item, cmp) {
        var pos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        pos = array2.indexOf(item);
        if (pos === -1) {
          return;
        }
        _siftdown(array2, 0, pos, cmp);
        return _siftup(array2, pos, cmp);
      };
      nlargest = function(array2, n3, cmp) {
        var elem, result, _i, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array2.slice(0, n3);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array2.slice(n3);
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          elem = _ref[_i];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array2, n3, cmp) {
        var elem, i4, los, result, _i, _j, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n3 * 10 <= array2.length) {
          result = array2.slice(0, n3).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array2.slice(n3);
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            elem = _ref[_i];
            if (cmp(elem, los) < 0) {
              insort(result, elem, 0, null, cmp);
              result.pop();
              los = result[result.length - 1];
            }
          }
          return result;
        }
        heapify(array2, cmp);
        _results = [];
        for (i4 = _j = 0, _ref1 = min(n3, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i4 = 0 <= _ref1 ? ++_j : --_j) {
          _results.push(heappop(array2, cmp));
        }
        return _results;
      };
      _siftdown = function(array2, startpos, pos, cmp) {
        var newitem, parent, parentpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        newitem = array2[pos];
        while (pos > startpos) {
          parentpos = pos - 1 >> 1;
          parent = array2[parentpos];
          if (cmp(newitem, parent) < 0) {
            array2[pos] = parent;
            pos = parentpos;
            continue;
          }
          break;
        }
        return array2[pos] = newitem;
      };
      _siftup = function(array2, pos, cmp) {
        var childpos, endpos, newitem, rightpos, startpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        endpos = array2.length;
        startpos = pos;
        newitem = array2[pos];
        childpos = 2 * pos + 1;
        while (childpos < endpos) {
          rightpos = childpos + 1;
          if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
            childpos = rightpos;
          }
          array2[pos] = array2[childpos];
          pos = childpos;
          childpos = 2 * pos + 1;
        }
        array2[pos] = newitem;
        return _siftdown(array2, startpos, pos, cmp);
      };
      Heap = function() {
        Heap2.push = heappush;
        Heap2.pop = heappop;
        Heap2.replace = heapreplace;
        Heap2.pushpop = heappushpop;
        Heap2.heapify = heapify;
        Heap2.updateItem = updateItem;
        Heap2.nlargest = nlargest;
        Heap2.nsmallest = nsmallest;
        function Heap2(cmp) {
          this.cmp = cmp != null ? cmp : defaultCmp;
          this.nodes = [];
        }
        Heap2.prototype.push = function(x4) {
          return heappush(this.nodes, x4, this.cmp);
        };
        Heap2.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap2.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap2.prototype.contains = function(x4) {
          return this.nodes.indexOf(x4) !== -1;
        };
        Heap2.prototype.replace = function(x4) {
          return heapreplace(this.nodes, x4, this.cmp);
        };
        Heap2.prototype.pushpop = function(x4) {
          return heappushpop(this.nodes, x4, this.cmp);
        };
        Heap2.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap2.prototype.updateItem = function(x4) {
          return updateItem(this.nodes, x4, this.cmp);
        };
        Heap2.prototype.clear = function() {
          return this.nodes = [];
        };
        Heap2.prototype.empty = function() {
          return this.nodes.length === 0;
        };
        Heap2.prototype.size = function() {
          return this.nodes.length;
        };
        Heap2.prototype.clone = function() {
          var heap;
          heap = new Heap2();
          heap.nodes = this.nodes.slice(0);
          return heap;
        };
        Heap2.prototype.toArray = function() {
          return this.nodes.slice(0);
        };
        Heap2.prototype.insert = Heap2.prototype.push;
        Heap2.prototype.top = Heap2.prototype.peek;
        Heap2.prototype.front = Heap2.prototype.peek;
        Heap2.prototype.has = Heap2.prototype.contains;
        Heap2.prototype.copy = Heap2.prototype.clone;
        return Heap2;
      }();
      (function(root, factory) {
        if (typeof define === "function" && define.amd) {
          return define([], factory);
        } else if (typeof exports2 === "object") {
          return module2.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap;
      });
    }).call(exports2);
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js
var require_heap2 = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js"(exports2, module2) {
    module2.exports = require_heap();
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
var require_difflib = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports2) {
    (function() {
      var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max, min, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
      ({ floor, max, min } = Math);
      Heap = require_heap2();
      assert = require("assert");
      _calculateRatio = function(matches, length) {
        if (length) {
          return 2 * matches / length;
        } else {
          return 1;
        }
      };
      _arrayCmp = function(a3, b3) {
        var i4, l3, la, lb, ref;
        [la, lb] = [a3.length, b3.length];
        for (i4 = l3 = 0, ref = min(la, lb); 0 <= ref ? l3 < ref : l3 > ref; i4 = 0 <= ref ? ++l3 : --l3) {
          if (a3[i4] < b3[i4]) {
            return -1;
          }
          if (a3[i4] > b3[i4]) {
            return 1;
          }
        }
        return la - lb;
      };
      _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
      _any = function(items) {
        var item, l3, len;
        for (l3 = 0, len = items.length; l3 < len; l3++) {
          item = items[l3];
          if (item) {
            return true;
          }
        }
        return false;
      };
      SequenceMatcher = class SequenceMatcher {
        /*
            SequenceMatcher is a flexible class for comparing pairs of sequences of
            any type, so long as the sequence elements are hashable.  The basic
            algorithm predates, and is a little fancier than, an algorithm
            published in the late 1980's by Ratcliff and Obershelp under the
            hyperbolic name "gestalt pattern matching".  The basic idea is to find
            the longest contiguous matching subsequence that contains no "junk"
            elements (R-O doesn't address junk).  The same idea is then applied
            recursively to the pieces of the sequences to the left and to the right
            of the matching subsequence.  This does not yield minimal edit
            sequences, but does tend to yield matches that "look right" to people.
        
            SequenceMatcher tries to compute a "human-friendly diff" between two
            sequences.  Unlike e.g. UNIX(tm) diff, the fundamental notion is the
            longest *contiguous* & junk-free matching subsequence.  That's what
            catches peoples' eyes.  The Windows(tm) windiff has another interesting
            notion, pairing up elements that appear uniquely in each sequence.
            That, and the method here, appear to yield more intuitive difference
            reports than does diff.  This method appears to be the least vulnerable
            to synching up on blocks of "junk lines", though (like blank lines in
            ordinary text files, or maybe "<P>" lines in HTML files).  That may be
            because this is the only method of the 3 that has a *concept* of
            "junk" <wink>.
        
            Example, comparing two strings, and considering blanks to be "junk":
        
            >>> isjunk = (c) -> c is ' '
            >>> s = new SequenceMatcher(isjunk,
                                        'private Thread currentThread;',
                                        'private volatile Thread currentThread;')
        
            .ratio() returns a float in [0, 1], measuring the "similarity" of the
            sequences.  As a rule of thumb, a .ratio() value over 0.6 means the
            sequences are close matches:
        
            >>> s.ratio().toPrecision(3)
            '0.866'
        
            If you're only interested in where the sequences match,
            .getMatchingBlocks() is handy:
        
            >>> for [a, b, size] in s.getMatchingBlocks()
            ...   console.log("a[#{a}] and b[#{b}] match for #{size} elements");
            a[0] and b[0] match for 8 elements
            a[8] and b[17] match for 21 elements
            a[29] and b[38] match for 0 elements
        
            Note that the last tuple returned by .get_matching_blocks() is always a
            dummy, (len(a), len(b), 0), and this is the only case in which the last
            tuple element (number of elements matched) is 0.
        
            If you want to know how to change the first sequence into the second,
            use .get_opcodes():
        
            >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
            ...   console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
            equal a[0:8] b[0:8]
            insert a[8:8] b[8:17]
            equal a[8:29] b[17:38]
        
            See the Differ class for a fancy human-friendly file differencer, which
            uses SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            See also function getCloseMatches() in this module, which shows how
            simple code building on SequenceMatcher can be used to do useful work.
        
            Timing:  Basic R-O is cubic time worst case and quadratic time expected
            case.  SequenceMatcher is quadratic time for the worst case and has
            expected-case behavior dependent in a complicated way on how many
            elements the sequences have in common; best case time is linear.
        
            Methods:
        
            constructor(isjunk=null, a='', b='')
                Construct a SequenceMatcher.
        
            setSeqs(a, b)
                Set the two sequences to be compared.
        
            setSeq1(a)
                Set the first sequence to be compared.
        
            setSeq2(b)
                Set the second sequence to be compared.
        
            findLongestMatch(alo, ahi, blo, bhi)
                Find longest matching block in a[alo:ahi] and b[blo:bhi].
        
            getMatchingBlocks()
                Return list of triples describing matching subsequences.
        
            getOpcodes()
                Return list of 5-tuples describing how to turn a into b.
        
            ratio()
                Return a measure of the sequences' similarity (float in [0,1]).
        
            quickRatio()
                Return an upper bound on .ratio() relatively quickly.
        
            realQuickRatio()
                Return an upper bound on ratio() very quickly.
            */
        constructor(isjunk1, a3 = "", b3 = "", autojunk = true) {
          this.isjunk = isjunk1;
          this.autojunk = autojunk;
          this.a = this.b = null;
          this.setSeqs(a3, b3);
        }
        setSeqs(a3, b3) {
          this.setSeq1(a3);
          return this.setSeq2(b3);
        }
        setSeq1(a3) {
          if (a3 === this.a) {
            return;
          }
          this.a = a3;
          return this.matchingBlocks = this.opcodes = null;
        }
        setSeq2(b3) {
          if (b3 === this.b) {
            return;
          }
          this.b = b3;
          this.matchingBlocks = this.opcodes = null;
          this.fullbcount = null;
          return this._chainB();
        }
        // For each element x in b, set b2j[x] to a list of the indices in
        // b where x appears; the indices are in increasing order; note that
        // the number of times x appears in b is b2j[x].length ...
        // when @isjunk is defined, junk elements don't show up in this
        // map at all, which stops the central findLongestMatch method
        // from starting any matching block at a junk element ...
        // also creates the fast isbjunk function ...
        // b2j also does not contain entries for "popular" elements, meaning
        // elements that account for more than 1 + 1% of the total elements, and
        // when the sequence is reasonably large (>= 200 elements); this can
        // be viewed as an adaptive notion of semi-junk, and yields an enormous
        // speedup when, e.g., comparing program files with hundreds of
        // instances of "return null;" ...
        // note that this is only called when b changes; so for cross-product
        // kinds of matches, it's best to call setSeq2 once, then setSeq1
        // repeatedly
        _chainB() {
          var b3, b2j, elt, i4, indices, isjunk, junk, l3, len, n3, ntest, popular;
          b3 = this.b;
          this.b2j = b2j = /* @__PURE__ */ new Map();
          for (i4 = l3 = 0, len = b3.length; l3 < len; i4 = ++l3) {
            elt = b3[i4];
            if (!b2j.has(elt)) {
              b2j.set(elt, []);
            }
            indices = b2j.get(elt);
            indices.push(i4);
          }
          junk = /* @__PURE__ */ new Map();
          isjunk = this.isjunk;
          if (isjunk) {
            b2j.forEach(function(idxs, elt2) {
              if (isjunk(elt2)) {
                junk.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          popular = /* @__PURE__ */ new Map();
          n3 = b3.length;
          if (this.autojunk && n3 >= 200) {
            ntest = floor(n3 / 100) + 1;
            b2j.forEach(function(idxs, elt2) {
              if (idxs.length > ntest) {
                popular.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          this.isbjunk = function(b4) {
            return junk.has(b4);
          };
          return this.isbpopular = function(b4) {
            return popular.has(b4);
          };
        }
        findLongestMatch(alo, ahi, blo, bhi) {
          var a3, b3, b2j, besti, bestj, bestsize, i4, isbjunk, j3, j2len, jlist, k3, l3, len, m4, newj2len, ref, ref1;
          [a3, b3, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
          [besti, bestj, bestsize] = [alo, blo, 0];
          j2len = {};
          for (i4 = l3 = ref = alo, ref1 = ahi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) {
            newj2len = {};
            jlist = [];
            if (b2j.has(a3[i4])) {
              jlist = b2j.get(a3[i4]);
            }
            for (m4 = 0, len = jlist.length; m4 < len; m4++) {
              j3 = jlist[m4];
              if (j3 < blo) {
                continue;
              }
              if (j3 >= bhi) {
                break;
              }
              k3 = newj2len[j3] = (j2len[j3 - 1] || 0) + 1;
              if (k3 > bestsize) {
                [besti, bestj, bestsize] = [i4 - k3 + 1, j3 - k3 + 1, k3];
              }
            }
            j2len = newj2len;
          }
          while (besti > alo && bestj > blo && !isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) {
            bestsize++;
          }
          while (besti > alo && bestj > blo && isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) {
            bestsize++;
          }
          return [besti, bestj, bestsize];
        }
        getMatchingBlocks() {
          var ahi, alo, bhi, blo, i4, i1, i22, j3, j1, j22, k3, k1, k22, l3, la, lb, len, matchingBlocks, nonAdjacent, queue, x4;
          if (this.matchingBlocks) {
            return this.matchingBlocks;
          }
          [la, lb] = [this.a.length, this.b.length];
          queue = [[0, la, 0, lb]];
          matchingBlocks = [];
          while (queue.length) {
            [alo, ahi, blo, bhi] = queue.pop();
            [i4, j3, k3] = x4 = this.findLongestMatch(alo, ahi, blo, bhi);
            if (k3) {
              matchingBlocks.push(x4);
              if (alo < i4 && blo < j3) {
                queue.push([alo, i4, blo, j3]);
              }
              if (i4 + k3 < ahi && j3 + k3 < bhi) {
                queue.push([i4 + k3, ahi, j3 + k3, bhi]);
              }
            }
          }
          matchingBlocks.sort(_arrayCmp);
          i1 = j1 = k1 = 0;
          nonAdjacent = [];
          for (l3 = 0, len = matchingBlocks.length; l3 < len; l3++) {
            [i22, j22, k22] = matchingBlocks[l3];
            if (i1 + k1 === i22 && j1 + k1 === j22) {
              k1 += k22;
            } else {
              if (k1) {
                nonAdjacent.push([i1, j1, k1]);
              }
              [i1, j1, k1] = [i22, j22, k22];
            }
          }
          if (k1) {
            nonAdjacent.push([i1, j1, k1]);
          }
          nonAdjacent.push([la, lb, 0]);
          return this.matchingBlocks = nonAdjacent;
        }
        getOpcodes() {
          var ai, answer, bj, i4, j3, l3, len, ref, size, tag;
          if (this.opcodes) {
            return this.opcodes;
          }
          i4 = j3 = 0;
          this.opcodes = answer = [];
          ref = this.getMatchingBlocks();
          for (l3 = 0, len = ref.length; l3 < len; l3++) {
            [ai, bj, size] = ref[l3];
            tag = "";
            if (i4 < ai && j3 < bj) {
              tag = "replace";
            } else if (i4 < ai) {
              tag = "delete";
            } else if (j3 < bj) {
              tag = "insert";
            }
            if (tag) {
              answer.push([tag, i4, ai, j3, bj]);
            }
            [i4, j3] = [ai + size, bj + size];
            if (size) {
              answer.push(["equal", ai, i4, bj, j3]);
            }
          }
          return answer;
        }
        getGroupedOpcodes(n3 = 3) {
          var codes, group, groups, i1, i22, j1, j22, l3, len, nn, tag;
          codes = this.getOpcodes();
          if (!codes.length) {
            codes = [["equal", 0, 1, 0, 1]];
          }
          if (codes[0][0] === "equal") {
            [tag, i1, i22, j1, j22] = codes[0];
            codes[0] = [tag, max(i1, i22 - n3), i22, max(j1, j22 - n3), j22];
          }
          if (codes[codes.length - 1][0] === "equal") {
            [tag, i1, i22, j1, j22] = codes[codes.length - 1];
            codes[codes.length - 1] = [tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)];
          }
          nn = n3 + n3;
          groups = [];
          group = [];
          for (l3 = 0, len = codes.length; l3 < len; l3++) {
            [tag, i1, i22, j1, j22] = codes[l3];
            if (tag === "equal" && i22 - i1 > nn) {
              group.push([tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)]);
              groups.push(group);
              group = [];
              [i1, j1] = [max(i1, i22 - n3), max(j1, j22 - n3)];
            }
            group.push([tag, i1, i22, j1, j22]);
          }
          if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
            groups.push(group);
          }
          return groups;
        }
        ratio() {
          var l3, len, match2, matches, ref;
          matches = 0;
          ref = this.getMatchingBlocks();
          for (l3 = 0, len = ref.length; l3 < len; l3++) {
            match2 = ref[l3];
            matches += match2[2];
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        quickRatio() {
          var avail, elt, fullbcount, l3, len, len1, m4, matches, numb, ref, ref1;
          if (!this.fullbcount) {
            this.fullbcount = fullbcount = {};
            ref = this.b;
            for (l3 = 0, len = ref.length; l3 < len; l3++) {
              elt = ref[l3];
              fullbcount[elt] = (fullbcount[elt] || 0) + 1;
            }
          }
          fullbcount = this.fullbcount;
          avail = {};
          matches = 0;
          ref1 = this.a;
          for (m4 = 0, len1 = ref1.length; m4 < len1; m4++) {
            elt = ref1[m4];
            if (_has(avail, elt)) {
              numb = avail[elt];
            } else {
              numb = fullbcount[elt] || 0;
            }
            avail[elt] = numb - 1;
            if (numb > 0) {
              matches++;
            }
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        realQuickRatio() {
          var la, lb;
          [la, lb] = [this.a.length, this.b.length];
          return _calculateRatio(min(la, lb), la + lb);
        }
      };
      getCloseMatches = function(word, possibilities, n3 = 3, cutoff = 0.6) {
        var l3, len, len1, m4, result, results, s4, score, x4;
        if (!(n3 > 0)) {
          throw new Error(`n must be > 0: (${n3})`);
        }
        if (!(0 <= cutoff && cutoff <= 1)) {
          throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
        }
        result = [];
        s4 = new SequenceMatcher();
        s4.setSeq2(word);
        for (l3 = 0, len = possibilities.length; l3 < len; l3++) {
          x4 = possibilities[l3];
          s4.setSeq1(x4);
          if (s4.realQuickRatio() >= cutoff && s4.quickRatio() >= cutoff && s4.ratio() >= cutoff) {
            result.push([s4.ratio(), x4]);
          }
        }
        result = Heap.nlargest(result, n3, _arrayCmp);
        results = [];
        for (m4 = 0, len1 = result.length; m4 < len1; m4++) {
          [score, x4] = result[m4];
          results.push(x4);
        }
        return results;
      };
      _countLeading = function(line, ch) {
        var i4, n3;
        [i4, n3] = [0, line.length];
        while (i4 < n3 && line[i4] === ch) {
          i4++;
        }
        return i4;
      };
      Differ = class Differ {
        /*
            Differ is a class for comparing sequences of lines of text, and
            producing human-readable differences or deltas.  Differ uses
            SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            Each line of a Differ delta begins with a two-letter code:
        
                '- '    line unique to sequence 1
                '+ '    line unique to sequence 2
                '  '    line common to both sequences
                '? '    line not present in either input sequence
        
            Lines beginning with '? ' attempt to guide the eye to intraline
            differences, and were not present in either input sequence.  These lines
            can be confusing if the sequences contain tab characters.
        
            Note that Differ makes no claim to produce a *minimal* diff.  To the
            contrary, minimal diffs are often counter-intuitive, because they synch
            up anywhere possible, sometimes accidental matches 100 pages apart.
            Restricting synch points to contiguous matches preserves some notion of
            locality, at the occasional cost of producing a longer diff.
        
            Example: Comparing two texts.
        
            >>> text1 = ['1. Beautiful is better than ugly.\n',
            ...   '2. Explicit is better than implicit.\n',
            ...   '3. Simple is better than complex.\n',
            ...   '4. Complex is better than complicated.\n']
            >>> text1.length
            4
            >>> text2 = ['1. Beautiful is better than ugly.\n',
            ...   '3.   Simple is better than complex.\n',
            ...   '4. Complicated is better than complex.\n',
            ...   '5. Flat is better than nested.\n']
        
            Next we instantiate a Differ object:
        
            >>> d = new Differ()
        
            Note that when instantiating a Differ object we may pass functions to
            filter out line and character 'junk'.
        
            Finally, we compare the two:
        
            >>> result = d.compare(text1, text2)
            [ '  1. Beautiful is better than ugly.\n',
              '- 2. Explicit is better than implicit.\n',
              '- 3. Simple is better than complex.\n',
              '+ 3.   Simple is better than complex.\n',
              '?   ++\n',
              '- 4. Complex is better than complicated.\n',
              '?          ^                     ---- ^\n',
              '+ 4. Complicated is better than complex.\n',
              '?         ++++ ^                      ^\n',
              '+ 5. Flat is better than nested.\n' ]
        
            Methods:
        
            constructor(linejunk=null, charjunk=null)
                Construct a text differencer, with optional filters.
            compare(a, b)
                Compare two sequences of lines; generate the resulting delta.
            */
        constructor(linejunk1, charjunk1) {
          this.linejunk = linejunk1;
          this.charjunk = charjunk1;
        }
        /*
            Construct a text differencer, with optional filters.
        
            The two optional keyword parameters are for filter functions:
        
            - `linejunk`: A function that should accept a single string argument,
              and return true iff the string is junk. The module-level function
              `IS_LINE_JUNK` may be used to filter out lines without visible
              characters, except for at most one splat ('#').  It is recommended
              to leave linejunk null. 
        
            - `charjunk`: A function that should accept a string of length 1. The
              module-level function `IS_CHARACTER_JUNK` may be used to filter out
              whitespace characters (a blank or tab; **note**: bad idea to include
              newline in this!).  Use of IS_CHARACTER_JUNK is recommended.
            */
        compare(a3, b3) {
          var ahi, alo, bhi, blo, cruncher, g3, l3, len, len1, line, lines, m4, ref, tag;
          cruncher = new SequenceMatcher(this.linejunk, a3, b3);
          lines = [];
          ref = cruncher.getOpcodes();
          for (l3 = 0, len = ref.length; l3 < len; l3++) {
            [tag, alo, ahi, blo, bhi] = ref[l3];
            switch (tag) {
              case "replace":
                g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi);
                break;
              case "delete":
                g3 = this._dump("-", a3, alo, ahi);
                break;
              case "insert":
                g3 = this._dump("+", b3, blo, bhi);
                break;
              case "equal":
                g3 = this._dump(" ", a3, alo, ahi);
                break;
              default:
                throw new Error(`unknow tag (${tag})`);
            }
            for (m4 = 0, len1 = g3.length; m4 < len1; m4++) {
              line = g3[m4];
              lines.push(line);
            }
          }
          return lines;
        }
        _dump(tag, x4, lo, hi) {
          var i4, l3, ref, ref1, results;
          results = [];
          for (i4 = l3 = ref = lo, ref1 = hi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) {
            results.push(`${tag} ${x4[i4]}`);
          }
          return results;
        }
        _plainReplace(a3, alo, ahi, b3, blo, bhi) {
          var first, g3, l3, len, len1, line, lines, m4, ref, second;
          assert(alo < ahi && blo < bhi);
          if (bhi - blo < ahi - alo) {
            first = this._dump("+", b3, blo, bhi);
            second = this._dump("-", a3, alo, ahi);
          } else {
            first = this._dump("-", a3, alo, ahi);
            second = this._dump("+", b3, blo, bhi);
          }
          lines = [];
          ref = [first, second];
          for (l3 = 0, len = ref.length; l3 < len; l3++) {
            g3 = ref[l3];
            for (m4 = 0, len1 = g3.length; m4 < len1; m4++) {
              line = g3[m4];
              lines.push(line);
            }
          }
          return lines;
        }
        _fancyReplace(a3, alo, ahi, b3, blo, bhi) {
          var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i4, j3, l3, la, lb, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, r4, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t4, tag;
          [bestRatio, cutoff] = [0.74, 0.75];
          cruncher = new SequenceMatcher(this.charjunk);
          [eqi, eqj] = [
            null,
            null
            // 1st indices of equal lines (if any)
          ];
          lines = [];
          for (j3 = l3 = ref = blo, ref1 = bhi; ref <= ref1 ? l3 < ref1 : l3 > ref1; j3 = ref <= ref1 ? ++l3 : --l3) {
            bj = b3[j3];
            cruncher.setSeq2(bj);
            for (i4 = m4 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m4 < ref3 : m4 > ref3; i4 = ref2 <= ref3 ? ++m4 : --m4) {
              ai = a3[i4];
              if (ai === bj) {
                if (eqi === null) {
                  [eqi, eqj] = [i4, j3];
                }
                continue;
              }
              cruncher.setSeq1(ai);
              if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
                [bestRatio, besti, bestj] = [cruncher.ratio(), i4, j3];
              }
            }
          }
          if (bestRatio < cutoff) {
            if (eqi === null) {
              ref4 = this._plainReplace(a3, alo, ahi, b3, blo, bhi);
              for (o3 = 0, len = ref4.length; o3 < len; o3++) {
                line = ref4[o3];
                lines.push(line);
              }
              return lines;
            }
            [besti, bestj, bestRatio] = [eqi, eqj, 1];
          } else {
            eqi = null;
          }
          ref5 = this._fancyHelper(a3, alo, besti, b3, blo, bestj);
          for (p3 = 0, len1 = ref5.length; p3 < len1; p3++) {
            line = ref5[p3];
            lines.push(line);
          }
          [aelt, belt] = [a3[besti], b3[bestj]];
          if (eqi === null) {
            atags = btags = "";
            cruncher.setSeqs(aelt, belt);
            ref6 = cruncher.getOpcodes();
            for (q3 = 0, len2 = ref6.length; q3 < len2; q3++) {
              [tag, ai1, ai2, bj1, bj2] = ref6[q3];
              [la, lb] = [ai2 - ai1, bj2 - bj1];
              switch (tag) {
                case "replace":
                  atags += Array(la + 1).join("^");
                  btags += Array(lb + 1).join("^");
                  break;
                case "delete":
                  atags += Array(la + 1).join("-");
                  break;
                case "insert":
                  btags += Array(lb + 1).join("+");
                  break;
                case "equal":
                  atags += Array(la + 1).join(" ");
                  btags += Array(lb + 1).join(" ");
                  break;
                default:
                  throw new Error(`unknow tag (${tag})`);
              }
            }
            ref7 = this._qformat(aelt, belt, atags, btags);
            for (r4 = 0, len3 = ref7.length; r4 < len3; r4++) {
              line = ref7[r4];
              lines.push(line);
            }
          } else {
            lines.push("  " + aelt);
          }
          ref8 = this._fancyHelper(a3, besti + 1, ahi, b3, bestj + 1, bhi);
          for (t4 = 0, len4 = ref8.length; t4 < len4; t4++) {
            line = ref8[t4];
            lines.push(line);
          }
          return lines;
        }
        _fancyHelper(a3, alo, ahi, b3, blo, bhi) {
          var g3;
          g3 = [];
          if (alo < ahi) {
            if (blo < bhi) {
              g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi);
            } else {
              g3 = this._dump("-", a3, alo, ahi);
            }
          } else if (blo < bhi) {
            g3 = this._dump("+", b3, blo, bhi);
          }
          return g3;
        }
        _qformat(aline, bline, atags, btags) {
          var common, lines;
          lines = [];
          common = min(_countLeading(aline, "	"), _countLeading(bline, "	"));
          common = min(common, _countLeading(atags.slice(0, common), " "));
          common = min(common, _countLeading(btags.slice(0, common), " "));
          atags = atags.slice(common).replace(/\s+$/, "");
          btags = btags.slice(common).replace(/\s+$/, "");
          lines.push("- " + aline);
          if (atags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${atags}
`);
          }
          lines.push("+ " + bline);
          if (btags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${btags}
`);
          }
          return lines;
        }
      };
      IS_LINE_JUNK = function(line, pat = /^\s*#?\s*$/) {
        return pat.test(line);
      };
      IS_CHARACTER_JUNK = function(ch, ws = " 	") {
        return indexOf.call(ws, ch) >= 0;
      };
      _formatRangeUnified = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (length === 1) {
          return `${beginning}`;
        }
        if (!length) {
          beginning--;
        }
        return `${beginning},${length}`;
      };
      unifiedDiff = function(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) {
        var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, ref, ref1, ref2, ref3, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n3 == null) {
          n3 = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        lines = [];
        started = false;
        ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes();
        for (l3 = 0, len = ref.length; l3 < len; l3++) {
          group = ref[l3];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`--- ${fromfile}${fromdate}${lineterm}`);
            lines.push(`+++ ${tofile}${todate}${lineterm}`);
          }
          [first, last] = [group[0], group[group.length - 1]];
          file1Range = _formatRangeUnified(first[1], last[2]);
          file2Range = _formatRangeUnified(first[3], last[4]);
          lines.push(`@@ -${file1Range} +${file2Range} @@${lineterm}`);
          for (m4 = 0, len1 = group.length; m4 < len1; m4++) {
            [tag, i1, i22, j1, j22] = group[m4];
            if (tag === "equal") {
              ref1 = a3.slice(i1, i22);
              for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) {
                line = ref1[o3];
                lines.push(" " + line);
              }
              continue;
            }
            if (tag === "replace" || tag === "delete") {
              ref2 = a3.slice(i1, i22);
              for (p3 = 0, len3 = ref2.length; p3 < len3; p3++) {
                line = ref2[p3];
                lines.push("-" + line);
              }
            }
            if (tag === "replace" || tag === "insert") {
              ref3 = b3.slice(j1, j22);
              for (q3 = 0, len4 = ref3.length; q3 < len4; q3++) {
                line = ref3[q3];
                lines.push("+" + line);
              }
            }
          }
        }
        return lines;
      };
      _formatRangeContext = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (!length) {
          beginning--;
        }
        if (length <= 1) {
          return `${beginning}`;
        }
        return `${beginning},${beginning + length - 1}`;
      };
      contextDiff = function(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) {
        var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, prefix2, q3, ref, ref1, ref2, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n3 == null) {
          n3 = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        prefix2 = {
          insert: "+ ",
          delete: "- ",
          replace: "! ",
          equal: "  "
        };
        started = false;
        lines = [];
        ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes();
        for (l3 = 0, len = ref.length; l3 < len; l3++) {
          group = ref[l3];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`*** ${fromfile}${fromdate}${lineterm}`);
            lines.push(`--- ${tofile}${todate}${lineterm}`);
            [first, last] = [group[0], group[group.length - 1]];
            lines.push("***************" + lineterm);
            file1Range = _formatRangeContext(first[1], last[2]);
            lines.push(`*** ${file1Range} ****${lineterm}`);
            if (_any(function() {
              var len12, m5, results;
              results = [];
              for (m5 = 0, len12 = group.length; m5 < len12; m5++) {
                [tag, _3, _3, _3, _3] = group[m5];
                results.push(tag === "replace" || tag === "delete");
              }
              return results;
            }())) {
              for (m4 = 0, len1 = group.length; m4 < len1; m4++) {
                [tag, i1, i22, _3, _3] = group[m4];
                if (tag !== "insert") {
                  ref1 = a3.slice(i1, i22);
                  for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) {
                    line = ref1[o3];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
            file2Range = _formatRangeContext(first[3], last[4]);
            lines.push(`--- ${file2Range} ----${lineterm}`);
            if (_any(function() {
              var len32, p4, results;
              results = [];
              for (p4 = 0, len32 = group.length; p4 < len32; p4++) {
                [tag, _3, _3, _3, _3] = group[p4];
                results.push(tag === "replace" || tag === "insert");
              }
              return results;
            }())) {
              for (p3 = 0, len3 = group.length; p3 < len3; p3++) {
                [tag, _3, _3, j1, j22] = group[p3];
                if (tag !== "delete") {
                  ref2 = b3.slice(j1, j22);
                  for (q3 = 0, len4 = ref2.length; q3 < len4; q3++) {
                    line = ref2[q3];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
          }
        }
        return lines;
      };
      ndiff = function(a3, b3, linejunk, charjunk = IS_CHARACTER_JUNK) {
        return new Differ(linejunk, charjunk).compare(a3, b3);
      };
      restore = function(delta, which) {
        var l3, len, line, lines, prefixes2, ref, tag;
        tag = {
          1: "- ",
          2: "+ "
        }[which];
        if (!tag) {
          throw new Error(`unknow delta choice (must be 1 or 2): ${which}`);
        }
        prefixes2 = ["  ", tag];
        lines = [];
        for (l3 = 0, len = delta.length; l3 < len; l3++) {
          line = delta[l3];
          if (ref = line.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
            lines.push(line.slice(2));
          }
        }
        return lines;
      };
      exports2._arrayCmp = _arrayCmp;
      exports2.SequenceMatcher = SequenceMatcher;
      exports2.getCloseMatches = getCloseMatches;
      exports2._countLeading = _countLeading;
      exports2.Differ = Differ;
      exports2.IS_LINE_JUNK = IS_LINE_JUNK;
      exports2.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
      exports2._formatRangeUnified = _formatRangeUnified;
      exports2.unifiedDiff = unifiedDiff;
      exports2._formatRangeContext = _formatRangeContext;
      exports2.contextDiff = contextDiff;
      exports2.ndiff = ndiff;
      exports2.restore = restore;
    }).call(exports2);
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js
var require_difflib2 = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports2, module2) {
    module2.exports = require_difflib();
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
var require_util = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports2, module2) {
    var extendedTypeOf = function(obj) {
      const result = typeof obj;
      if (obj == null) {
        return "null";
      } else if (result === "object" && obj.constructor === Array) {
        return "array";
      } else if (result === "object" && obj instanceof Date) {
        return "date";
      } else {
        return result;
      }
    };
    var roundObj = function(data, precision) {
      const type = typeof data;
      if (type === "array") {
        return data.map((x4) => roundObj(x4, precision));
      } else if (type === "object") {
        for (const key in data) {
          data[key] = roundObj(data[key], precision);
        }
        return data;
      } else if (type === "number" && Number.isFinite(data) && !Number.isInteger(data)) {
        return +data.toFixed(precision);
      } else {
        return data;
      }
    };
    module2.exports = { extendedTypeOf, roundObj };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js
var require_styles = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js"(exports2, module2) {
    var styles3 = {};
    module2["exports"] = styles3;
    var codes = {
      reset: [0, 0],
      bold: [1, 22],
      dim: [2, 22],
      italic: [3, 23],
      underline: [4, 24],
      inverse: [7, 27],
      hidden: [8, 28],
      strikethrough: [9, 29],
      black: [30, 39],
      red: [31, 39],
      green: [32, 39],
      yellow: [33, 39],
      blue: [34, 39],
      magenta: [35, 39],
      cyan: [36, 39],
      white: [37, 39],
      gray: [90, 39],
      grey: [90, 39],
      brightRed: [91, 39],
      brightGreen: [92, 39],
      brightYellow: [93, 39],
      brightBlue: [94, 39],
      brightMagenta: [95, 39],
      brightCyan: [96, 39],
      brightWhite: [97, 39],
      bgBlack: [40, 49],
      bgRed: [41, 49],
      bgGreen: [42, 49],
      bgYellow: [43, 49],
      bgBlue: [44, 49],
      bgMagenta: [45, 49],
      bgCyan: [46, 49],
      bgWhite: [47, 49],
      bgGray: [100, 49],
      bgGrey: [100, 49],
      bgBrightRed: [101, 49],
      bgBrightGreen: [102, 49],
      bgBrightYellow: [103, 49],
      bgBrightBlue: [104, 49],
      bgBrightMagenta: [105, 49],
      bgBrightCyan: [106, 49],
      bgBrightWhite: [107, 49],
      // legacy styles for colors pre v1.0.0
      blackBG: [40, 49],
      redBG: [41, 49],
      greenBG: [42, 49],
      yellowBG: [43, 49],
      blueBG: [44, 49],
      magentaBG: [45, 49],
      cyanBG: [46, 49],
      whiteBG: [47, 49]
    };
    Object.keys(codes).forEach(function(key) {
      var val2 = codes[key];
      var style = styles3[key] = [];
      style.open = "\x1B[" + val2[0] + "m";
      style.close = "\x1B[" + val2[1] + "m";
    });
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
var require_has_flag2 = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports2, module2) {
    "use strict";
    module2.exports = function(flag, argv) {
      argv = argv || process.argv;
      var terminatorPos = argv.indexOf("--");
      var prefix2 = /^-{1,2}/.test(flag) ? "" : "--";
      var pos = argv.indexOf(prefix2 + flag);
      return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports2, module2) {
    "use strict";
    var os3 = require("os");
    var hasFlag2 = require_has_flag2();
    var env3 = process.env;
    var forceColor = void 0;
    if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) {
      forceColor = false;
    } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
      forceColor = true;
    }
    if ("FORCE_COLOR" in env3) {
      forceColor = env3.FORCE_COLOR.length === 0 || parseInt(env3.FORCE_COLOR, 10) !== 0;
    }
    function translateLevel2(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor2(stream) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
        return 3;
      }
      if (hasFlag2("color=256")) {
        return 2;
      }
      if (stream && !stream.isTTY && forceColor !== true) {
        return 0;
      }
      var min = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        var osRelease = os3.release().split(".");
        if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env3) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env3;
        }) || env3.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env3) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env3) {
        var version3 = parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env3.TERM_PROGRAM) {
          case "iTerm.app":
            return version3 >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env3.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env3) {
        return 1;
      }
      if (env3.TERM === "dumb") {
        return min;
      }
      return min;
    }
    function getSupportLevel(stream) {
      var level = supportsColor2(stream);
      return translateLevel2(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
var require_trap = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports2, module2) {
    module2["exports"] = function runTheTrap(text, options) {
      var result = "";
      text = text || "Run the trap, drop the bass";
      text = text.split("");
      var trap = {
        a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
        b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
        c: ["\xA9", "\u023B", "\u03FE"],
        d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
        e: [
          "\xCB",
          "\u0115",
          "\u018E",
          "\u0258",
          "\u03A3",
          "\u03BE",
          "\u04BC",
          "\u0A6C"
        ],
        f: ["\u04FA"],
        g: ["\u0262"],
        h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
        i: ["\u0F0F"],
        j: ["\u0134"],
        k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
        l: ["\u0139"],
        m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
        n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
        o: [
          "\xD8",
          "\xF5",
          "\xF8",
          "\u01FE",
          "\u0298",
          "\u047A",
          "\u05DD",
          "\u06DD",
          "\u0E4F"
        ],
        p: ["\u01F7", "\u048E"],
        q: ["\u09CD"],
        r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
        s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
        t: ["\u0141", "\u0166", "\u0373"],
        u: ["\u01B1", "\u054D"],
        v: ["\u05D8"],
        w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
        x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
        y: ["\xA5", "\u04B0", "\u04CB"],
        z: ["\u01B5", "\u0240"]
      };
      text.forEach(function(c3) {
        c3 = c3.toLowerCase();
        var chars = trap[c3] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c3] !== "undefined") {
          result += trap[c3][rand];
        } else {
          result += c3;
        }
      });
      return result;
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js
var require_zalgo = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js"(exports2, module2) {
    module2["exports"] = function zalgo(text, options) {
      text = text || "   he is here   ";
      var soul = {
        "up": [
          "\u030D",
          "\u030E",
          "\u0304",
          "\u0305",
          "\u033F",
          "\u0311",
          "\u0306",
          "\u0310",
          "\u0352",
          "\u0357",
          "\u0351",
          "\u0307",
          "\u0308",
          "\u030A",
          "\u0342",
          "\u0313",
          "\u0308",
          "\u034A",
          "\u034B",
          "\u034C",
          "\u0303",
          "\u0302",
          "\u030C",
          "\u0350",
          "\u0300",
          "\u0301",
          "\u030B",
          "\u030F",
          "\u0312",
          "\u0313",
          "\u0314",
          "\u033D",
          "\u0309",
          "\u0363",
          "\u0364",
          "\u0365",
          "\u0366",
          "\u0367",
          "\u0368",
          "\u0369",
          "\u036A",
          "\u036B",
          "\u036C",
          "\u036D",
          "\u036E",
          "\u036F",
          "\u033E",
          "\u035B",
          "\u0346",
          "\u031A"
        ],
        "down": [
          "\u0316",
          "\u0317",
          "\u0318",
          "\u0319",
          "\u031C",
          "\u031D",
          "\u031E",
          "\u031F",
          "\u0320",
          "\u0324",
          "\u0325",
          "\u0326",
          "\u0329",
          "\u032A",
          "\u032B",
          "\u032C",
          "\u032D",
          "\u032E",
          "\u032F",
          "\u0330",
          "\u0331",
          "\u0332",
          "\u0333",
          "\u0339",
          "\u033A",
          "\u033B",
          "\u033C",
          "\u0345",
          "\u0347",
          "\u0348",
          "\u0349",
          "\u034D",
          "\u034E",
          "\u0353",
          "\u0354",
          "\u0355",
          "\u0356",
          "\u0359",
          "\u035A",
          "\u0323"
        ],
        "mid": [
          "\u0315",
          "\u031B",
          "\u0300",
          "\u0301",
          "\u0358",
          "\u0321",
          "\u0322",
          "\u0327",
          "\u0328",
          "\u0334",
          "\u0335",
          "\u0336",
          "\u035C",
          "\u035D",
          "\u035E",
          "\u035F",
          "\u0360",
          "\u0362",
          "\u0338",
          "\u0337",
          "\u0361",
          " \u0489"
        ]
      };
      var all = [].concat(soul.up, soul.down, soul.mid);
      function randomNumber(range) {
        var r4 = Math.floor(Math.random() * range);
        return r4;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i4) {
          bool = i4 === character;
        });
        return bool;
      }
      function heComes(text2, options2) {
        var result = "";
        var counts;
        var l3;
        options2 = options2 || {};
        options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true;
        options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true;
        options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true;
        options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi";
        text2 = text2.split("");
        for (l3 in text2) {
          if (isChar(l3)) {
            continue;
          }
          result = result + text2[l3];
          counts = { "up": 0, "down": 0, "mid": 0 };
          switch (options2.size) {
            case "mini":
              counts.up = randomNumber(8);
              counts.mid = randomNumber(2);
              counts.down = randomNumber(8);
              break;
            case "maxi":
              counts.up = randomNumber(16) + 3;
              counts.mid = randomNumber(4) + 1;
              counts.down = randomNumber(64) + 3;
              break;
            default:
              counts.up = randomNumber(8) + 1;
              counts.mid = randomNumber(6) / 2;
              counts.down = randomNumber(8) + 1;
              break;
          }
          var arr = ["up", "mid", "down"];
          for (var d3 in arr) {
            var index6 = arr[d3];
            for (var i4 = 0; i4 <= counts[index6]; i4++) {
              if (options2[index6]) {
                result = result + soul[index6][randomNumber(soul[index6].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text, options);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
var require_america = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) {
    module2["exports"] = function(colors) {
      return function(letter, i4, exploded) {
        if (letter === " ") return letter;
        switch (i4 % 3) {
          case 0:
            return colors.red(letter);
          case 1:
            return colors.white(letter);
          case 2:
            return colors.blue(letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js
var require_zebra = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js"(exports2, module2) {
    module2["exports"] = function(colors) {
      return function(letter, i4, exploded) {
        return i4 % 2 === 0 ? letter : colors.inverse(letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js
var require_rainbow = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js"(exports2, module2) {
    module2["exports"] = function(colors) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i4, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors[rainbowColors[i4++ % rainbowColors.length]](letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js
var require_random = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js"(exports2, module2) {
    module2["exports"] = function(colors) {
      var available = [
        "underline",
        "inverse",
        "grey",
        "yellow",
        "red",
        "green",
        "blue",
        "white",
        "cyan",
        "magenta",
        "brightYellow",
        "brightRed",
        "brightGreen",
        "brightBlue",
        "brightWhite",
        "brightCyan",
        "brightMagenta"
      ];
      return function(letter, i4, exploded) {
        return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js
var require_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js"(exports2, module2) {
    var colors = {};
    module2["exports"] = colors;
    colors.themes = {};
    var util2 = require("util");
    var ansiStyles2 = colors.styles = require_styles();
    var defineProps = Object.defineProperties;
    var newLineRegex = new RegExp(/[\r\n]+/g);
    colors.supportsColor = require_supports_colors().supportsColor;
    if (typeof colors.enabled === "undefined") {
      colors.enabled = colors.supportsColor() !== false;
    }
    colors.enable = function() {
      colors.enabled = true;
    };
    colors.disable = function() {
      colors.enabled = false;
    };
    colors.stripColors = colors.strip = function(str) {
      return ("" + str).replace(/\x1B\[\d+m/g, "");
    };
    var stylize = colors.stylize = function stylize2(str, style) {
      if (!colors.enabled) {
        return str + "";
      }
      var styleMap = ansiStyles2[style];
      if (!styleMap && style in colors) {
        return colors[style](str);
      }
      return styleMap.open + str + styleMap.close;
    };
    var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
    var escapeStringRegexp = function(str) {
      if (typeof str !== "string") {
        throw new TypeError("Expected a string");
      }
      return str.replace(matchOperatorsRe, "\\$&");
    };
    function build(_styles) {
      var builder = function builder2() {
        return applyStyle2.apply(builder2, arguments);
      };
      builder._styles = _styles;
      builder.__proto__ = proto2;
      return builder;
    }
    var styles3 = function() {
      var ret = {};
      ansiStyles2.grey = ansiStyles2.gray;
      Object.keys(ansiStyles2).forEach(function(key) {
        ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
        ret[key] = {
          get: function() {
            return build(this._styles.concat(key));
          }
        };
      });
      return ret;
    }();
    var proto2 = defineProps(function colors2() {
    }, styles3);
    function applyStyle2() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.map(function(arg) {
        if (arg != null && arg.constructor === String) {
          return arg;
        } else {
          return util2.inspect(arg);
        }
      }).join(" ");
      if (!colors.enabled || !str) {
        return str;
      }
      var newLinesPresent = str.indexOf("\n") != -1;
      var nestedStyles = this._styles;
      var i4 = nestedStyles.length;
      while (i4--) {
        var code = ansiStyles2[nestedStyles[i4]];
        str = code.open + str.replace(code.closeRe, code.open) + code.close;
        if (newLinesPresent) {
          str = str.replace(newLineRegex, function(match2) {
            return code.close + match2 + code.open;
          });
        }
      }
      return str;
    }
    colors.setTheme = function(theme) {
      if (typeof theme === "string") {
        console.log("colors.setTheme now only accepts an object, not a string.  If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file.  The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
        return;
      }
      for (var style in theme) {
        (function(style2) {
          colors[style2] = function(str) {
            if (typeof theme[style2] === "object") {
              var out = str;
              for (var i4 in theme[style2]) {
                out = colors[theme[style2][i4]](out);
              }
              return out;
            }
            return colors[theme[style2]](str);
          };
        })(style);
      }
    };
    function init2() {
      var ret = {};
      Object.keys(styles3).forEach(function(name) {
        ret[name] = {
          get: function() {
            return build([name]);
          }
        };
      });
      return ret;
    }
    var sequencer = function sequencer2(map3, str) {
      var exploded = str.split("");
      exploded = exploded.map(map3);
      return exploded.join("");
    };
    colors.trap = require_trap();
    colors.zalgo = require_zalgo();
    colors.maps = {};
    colors.maps.america = require_america()(colors);
    colors.maps.zebra = require_zebra()(colors);
    colors.maps.rainbow = require_rainbow()(colors);
    colors.maps.random = require_random()(colors);
    for (map2 in colors.maps) {
      (function(map3) {
        colors[map3] = function(str) {
          return sequencer(colors.maps[map3], str);
        };
      })(map2);
    }
    var map2;
    defineProps(colors, init2());
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js
var require_safe = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports2, module2) {
    var colors = require_colors();
    module2["exports"] = colors;
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
var require_colorize = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports2, module2) {
    var color = require_safe();
    var { extendedTypeOf } = require_util();
    var Theme = {
      " "(s4) {
        return s4;
      },
      "+": color.green,
      "-": color.red
    };
    var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
      let subvalue;
      const prefix2 = key ? `${key}: ` : "";
      const subindent = indent + "  ";
      const outputElisions = (n3) => {
        const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
        if (n3 < maxElisions) {
          for (let i4 = 0; i4 < n3; i4++) {
            output(" ", subindent + "...");
          }
        } else {
          output(" ", subindent + `... (${n3} entries)`);
        }
      };
      switch (extendedTypeOf(diff2)) {
        case "object":
          if ("__old" in diff2 && "__new" in diff2 && Object.keys(diff2).length === 2) {
            subcolorizeToCallback(options, key, diff2.__old, output, "-", indent);
            return subcolorizeToCallback(options, key, diff2.__new, output, "+", indent);
          } else {
            output(color2, `${indent}${prefix2}{`);
            for (const subkey of Object.keys(diff2)) {
              let m4;
              subvalue = diff2[subkey];
              if (m4 = subkey.match(/^(.*)__deleted$/)) {
                subcolorizeToCallback(options, m4[1], subvalue, output, "-", subindent);
              } else if (m4 = subkey.match(/^(.*)__added$/)) {
                subcolorizeToCallback(options, m4[1], subvalue, output, "+", subindent);
              } else {
                subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent);
              }
            }
            return output(color2, `${indent}}`);
          }
        case "array": {
          output(color2, `${indent}${prefix2}[`);
          let looksLikeDiff = true;
          for (const item of diff2) {
            if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) {
              looksLikeDiff = false;
            }
          }
          if (looksLikeDiff) {
            let op;
            let elisionCount = 0;
            for ([op, subvalue] of diff2) {
              if (op === " " && subvalue == null) {
                elisionCount++;
              } else {
                if (elisionCount > 0) {
                  outputElisions(elisionCount);
                }
                elisionCount = 0;
                if (![" ", "~", "+", "-"].includes(op)) {
                  throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`);
                }
                if (op === "~") {
                  op = " ";
                }
                subcolorizeToCallback(options, "", subvalue, output, op, subindent);
              }
            }
            if (elisionCount > 0) {
              outputElisions(elisionCount);
            }
          } else {
            for (subvalue of diff2) {
              subcolorizeToCallback(options, "", subvalue, output, color2, subindent);
            }
          }
          return output(color2, `${indent}]`);
        }
        default:
          if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) {
            return output(color2, indent + prefix2 + JSON.stringify(diff2));
          }
      }
    };
    var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", "");
    var colorizeToArray = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, (color2, line) => output.push(`${color2}${line}`));
      return output;
    };
    var colorize = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, function(color2, line) {
        if (options.color != null ? options.color : true) {
          return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line}`) + "\n");
        } else {
          return output.push(`${color2}${line}
`);
        }
      });
      return output.join("");
    };
    module2.exports = { colorize, colorizeToArray, colorizeToCallback };
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
var require_lib = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports2, module2) {
    var { SequenceMatcher } = require_difflib2();
    var { extendedTypeOf, roundObj } = require_util();
    var { colorize, colorizeToCallback } = require_colorize();
    var JsonDiff = class {
      constructor(options) {
        options.outputKeys = options.outputKeys || [];
        options.excludeKeys = options.excludeKeys || [];
        this.options = options;
      }
      isScalar(obj) {
        return typeof obj !== "object" || obj === null;
      }
      objectDiff(obj1, obj2) {
        let result = {};
        let score = 0;
        let equal = true;
        for (const [key, value] of Object.entries(obj1)) {
          if (!this.options.outputNewOnly) {
            const postfix = "__deleted";
            if (!(key in obj2) && !this.options.excludeKeys.includes(key)) {
              result[`${key}${postfix}`] = value;
              score -= 30;
              equal = false;
            }
          }
        }
        for (const [key, value] of Object.entries(obj2)) {
          const postfix = !this.options.outputNewOnly ? "__added" : "";
          if (!(key in obj1) && !this.options.excludeKeys.includes(key)) {
            result[`${key}${postfix}`] = value;
            score -= 30;
            equal = false;
          }
        }
        for (const [key, value1] of Object.entries(obj1)) {
          if (key in obj2) {
            if (this.options.excludeKeys.includes(key)) {
              continue;
            }
            score += 20;
            const value2 = obj2[key];
            const change = this.diff(value1, value2);
            if (!change.equal) {
              result[key] = change.result;
              equal = false;
            } else if (this.options.full || this.options.outputKeys.includes(key)) {
              result[key] = value1;
            }
            score += Math.min(20, Math.max(-10, change.score / 5));
          }
        }
        if (equal) {
          score = 100 * Math.max(Object.keys(obj1).length, 0.5);
          if (!this.options.full) {
            result = void 0;
          }
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      findMatchingObject(item, index6, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index6);
            if (extendedTypeOf(item) === extendedTypeOf(candidate)) {
              const { score } = this.diff(item, candidate);
              if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) {
                bestMatch = { score, key, indexDistance };
              }
            }
          }
        }
        return bestMatch;
      }
      scalarize(array2, originals, fuzzyOriginals) {
        const fuzzyMatches = [];
        if (fuzzyOriginals) {
          const keyScores = {};
          for (let index6 = 0; index6 < array2.length; index6++) {
            const item = array2[index6];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index6 = 0; index6 < array2.length; index6++) {
          const item = array2[index6];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index6 };
            result.push(key);
          }
        }
        return result;
      }
      isScalarized(item, originals) {
        return typeof item === "string" && item in originals;
      }
      descalarize(item, originals) {
        if (this.isScalarized(item, originals)) {
          return originals[item].item;
        } else {
          return item;
        }
      }
      arrayDiff(obj1, obj2) {
        const originals1 = { __next: 1 };
        const seq1 = this.scalarize(obj1, originals1);
        const originals2 = { __next: originals1.__next };
        const seq2 = this.scalarize(obj2, originals2, originals1);
        if (this.options.sort) {
          seq1.sort();
          seq2.sort();
        }
        const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes();
        let result = [];
        let score = 0;
        let equal = true;
        for (const [op, i1, i22, j1, j22] of opcodes) {
          let i4, j3;
          let asc, end;
          let asc1, end1;
          let asc2, end2;
          if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
            equal = false;
          }
          switch (op) {
            case "equal":
              for (i4 = i1, end = i22, asc = i1 <= end; asc ? i4 < end : i4 > end; asc ? i4++ : i4--) {
                const item = seq1[i4];
                if (this.isScalarized(item, originals1)) {
                  if (!this.isScalarized(item, originals2)) {
                    throw new Error(
                      `internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item ${JSON.stringify(
                        item
                      )}`
                    );
                  }
                  const item1 = this.descalarize(item, originals1);
                  const item2 = this.descalarize(item, originals2);
                  const change = this.diff(item1, item2);
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    if (this.options.full || this.options.keepUnchangedValues) {
                      result.push([" ", item1]);
                    } else {
                      result.push([" "]);
                    }
                  }
                } else {
                  if (this.options.full || this.options.keepUnchangedValues) {
                    result.push([" ", item]);
                  } else {
                    result.push([" "]);
                  }
                }
                score += 10;
              }
              break;
            case "delete":
              for (i4 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i4 < end1 : i4 > end1; asc1 ? i4++ : i4--) {
                result.push(["-", this.descalarize(seq1[i4], originals1)]);
                score -= 5;
              }
              break;
            case "insert":
              for (j3 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j3 < end2 : j3 > end2; asc2 ? j3++ : j3--) {
                result.push(["+", this.descalarize(seq2[j3], originals2)]);
                score -= 5;
              }
              break;
            case "replace":
              if (!this.options.keysOnly) {
                let asc3, end3;
                let asc4, end4;
                for (i4 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i4 < end3 : i4 > end3; asc3 ? i4++ : i4--) {
                  result.push(["-", this.descalarize(seq1[i4], originals1)]);
                  score -= 5;
                }
                for (j3 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j3 < end4 : j3 > end4; asc4 ? j3++ : j3--) {
                  result.push(["+", this.descalarize(seq2[j3], originals2)]);
                  score -= 5;
                }
              } else {
                let asc5, end5;
                for (i4 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i4 < end5 : i4 > end5; asc5 ? i4++ : i4--) {
                  const change = this.diff(
                    this.descalarize(seq1[i4], originals1),
                    this.descalarize(seq2[i4 - i1 + j1], originals2)
                  );
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    result.push([" "]);
                  }
                }
              }
              break;
          }
        }
        if (equal || opcodes.length === 0) {
          if (!this.options.full) {
            result = void 0;
          } else {
            result = obj1;
          }
          score = 100;
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      diff(obj1, obj2) {
        const type1 = extendedTypeOf(obj1);
        const type2 = extendedTypeOf(obj2);
        if (type1 === type2) {
          switch (type1) {
            case "object":
              return this.objectDiff(obj1, obj2);
            case "array":
              return this.arrayDiff(obj1, obj2);
          }
        }
        let score = 100;
        let result = obj1;
        let equal;
        if (!this.options.keysOnly) {
          if (type1 === "date" && type2 === "date") {
            equal = obj1.getTime() === obj2.getTime();
          } else {
            equal = obj1 === obj2;
          }
          if (!equal) {
            score = 0;
            if (this.options.outputNewOnly) {
              result = obj2;
            } else {
              result = { __old: obj1, __new: obj2 };
            }
          } else if (!this.options.full) {
            result = void 0;
          }
        } else {
          equal = true;
          result = void 0;
        }
        return { score, result, equal };
      }
    };
    function diff2(obj1, obj2, options = {}) {
      if (options.precision !== void 0) {
        obj1 = roundObj(obj1, options.precision);
        obj2 = roundObj(obj2, options.precision);
      }
      return new JsonDiff(options).diff(obj1, obj2).result;
    }
    function diffString(obj1, obj2, options = {}) {
      return colorize(diff2(obj1, obj2, options), options);
    }
    module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  }
});

// src/jsonDiffer.js
function diffSchemasOrTables(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffIndPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffColumns(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].columns = {
        added: addedColumns,
        deleted: deletedColumns
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function diffPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].policies = {
        added: addedPolicies,
        deleted: deletedPolicies
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function applyJsonDiff(json1, json2) {
  json1 = JSON.parse(JSON.stringify(json1));
  json2 = JSON.parse(JSON.stringify(json2));
  const rawDiff = (0, import_json_diff.diff)(json1, json2);
  const difference = JSON.parse(JSON.stringify(rawDiff || {}));
  difference.schemas = difference.schemas || {};
  difference.tables = difference.tables || {};
  difference.enums = difference.enums || {};
  difference.sequences = difference.sequences || {};
  difference.roles = difference.roles || {};
  difference.policies = difference.policies || {};
  difference.views = difference.views || {};
  const schemaKeys = Object.keys(difference.schemas);
  for (let key of schemaKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.schemas[key];
      continue;
    }
  }
  const tableKeys = Object.keys(difference.tables);
  for (let key of tableKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.tables[key];
      continue;
    }
    const table6 = json1.tables[key];
    difference.tables[key] = {
      name: table6.name,
      schema: table6.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table6 = difference.tables[tableKey2];
    const columns = tableValue.columns || {};
    const columnKeys = Object.keys(columns);
    for (let key of columnKeys) {
      if (key.endsWith("__added") || key.endsWith("__deleted")) {
        delete table6.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table6["columns"];
    }
    if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) {
      delete difference.tables[tableKey2];
    }
  }
  const enumsEntries = Object.entries(difference.enums);
  const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    const enumEntry = json1.enums[it[0]];
    const { name, schema: schema6, values } = enumEntry;
    const sequence = mapArraysDiff(values, it[1].values);
    const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => {
      return {
        before: it2.before,
        value: it2.value
      };
    });
    const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value);
    return { name, schema: schema6, addedValues, deletedValues };
  });
  const sequencesEntries = Object.entries(difference.sequences);
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
    return json2.sequences[it[0]];
  });
  const rolesEntries = Object.entries(difference.roles);
  const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json2.roles[it[0]];
  });
  const policiesEntries = Object.entries(difference.policies);
  const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json2.policies[it[0]];
  });
  const viewsEntries = Object.entries(difference.views);
  const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
    ([nameWithSchema, view5]) => {
      const deletedWithOption = view5.with__deleted;
      const addedWithOption = view5.with__added;
      const deletedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
          return [key.replace("__deleted", ""), value];
        })
      );
      const addedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
          return [key.replace("__added", ""), value];
        })
      );
      const alterWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter(
          (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
        ).map(
          (it) => {
            return [it[0], it[1].__new];
          }
        )
      );
      const alteredSchema = view5.schema;
      const alteredDefinition = view5.definition;
      const alteredExisting = view5.isExisting;
      const addedTablespace = view5.tablespace__added;
      const droppedTablespace = view5.tablespace__deleted;
      const alterTablespaceTo = view5.tablespace;
      let alteredTablespace;
      if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
      if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
      if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
      const addedUsing = view5.using__added;
      const droppedUsing = view5.using__deleted;
      const alterUsingTo = view5.using;
      let alteredUsing;
      if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
      if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
      if (alterUsingTo) alteredUsing = alterUsingTo;
      const alteredMeta = view5.meta;
      return Object.fromEntries(
        Object.entries({
          name: json2.views[nameWithSchema].name,
          schema: json2.views[nameWithSchema].schema,
          // pg
          deletedWithOption,
          addedWithOption,
          deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
          addedWith: Object.keys(addedWith).length ? addedWith : void 0,
          alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
          alteredSchema,
          alteredTablespace,
          alteredUsing,
          // mysql
          alteredMeta,
          // common
          alteredDefinition,
          alteredExisting
        }).filter(([_3, value]) => value !== void 0)
      );
    }
  );
  const alteredTablesWithColumns = Object.values(difference.tables).map(
    (table6) => {
      return findAlternationsInTable(table6);
    }
  );
  return {
    alteredTablesWithColumns,
    alteredEnums,
    alteredSequences,
    alteredRoles,
    alteredViews,
    alteredPolicies
  };
}
var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
var init_jsonDiffer = __esm({
  "src/jsonDiffer.js"() {
    "use strict";
    "use-strict";
    import_json_diff = __toESM(require_lib());
    mapArraysDiff = (source, diff2) => {
      const sequence = [];
      let sourceIndex = 0;
      for (let i4 = 0; i4 < diff2.length; i4++) {
        const it = diff2[i4];
        if (it.length === 1) {
          sequence.push({ type: "same", value: source[sourceIndex] });
          sourceIndex += 1;
        } else {
          if (it[0] === "-") {
            sequence.push({ type: "removed", value: it[1] });
          } else {
            sequence.push({ type: "added", value: it[1], before: "" });
          }
        }
      }
      const result = sequence.reverse().reduce(
        (acc, it) => {
          if (it.type === "same") {
            acc.prev = it.value;
          }
          if (it.type === "added" && acc.prev) {
            it.before = acc.prev;
          }
          acc.result.push(it);
          return acc;
        },
        { result: [] }
      );
      return result.result.reverse();
    };
    findAlternationsInTable = (table6) => {
      const columns = table6.columns ?? {};
      const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => {
        return { name: it, ...columns[it] };
      });
      const deletedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__deleted || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__added || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table6.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table6.policies__deleted || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table6.policies__added || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table6.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__deleted || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__added || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table6.name,
        schema: table6.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column11) => {
      const altered = [column11];
      const result = altered.filter((it) => {
        if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) {
          return false;
        }
        return true;
      }).map((it) => {
        if (typeof it.name !== "string" && "__old" in it.name) {
          return {
            ...it,
            name: { type: "changed", old: it.name.__old, new: it.name.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("type" in it) {
          return {
            ...it,
            type: { type: "changed", old: it.type.__old, new: it.type.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("default" in it) {
          return {
            ...it,
            default: {
              type: "changed",
              old: it.default.__old,
              new: it.default.__new
            }
          };
        }
        if ("default__added" in it) {
          const { default__added, ...others } = it;
          return {
            ...others,
            default: { type: "added", value: it.default__added }
          };
        }
        if ("default__deleted" in it) {
          const { default__deleted, ...others } = it;
          return {
            ...others,
            default: { type: "deleted", value: it.default__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("generated" in it) {
          if ("as" in it.generated && "type" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old, type: it.generated.type.__old },
                new: { as: it.generated.as.__new, type: it.generated.type.__new }
              }
            };
          } else if ("as" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old },
                new: { as: it.generated.as.__new }
              }
            };
          } else {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.type.__old },
                new: { as: it.generated.type.__new }
              }
            };
          }
        }
        if ("generated__added" in it) {
          const { generated__added, ...others } = it;
          return {
            ...others,
            generated: { type: "added", value: it.generated__added }
          };
        }
        if ("generated__deleted" in it) {
          const { generated__deleted, ...others } = it;
          return {
            ...others,
            generated: { type: "deleted", value: it.generated__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("identity" in it) {
          return {
            ...it,
            identity: {
              type: "changed",
              old: it.identity.__old,
              new: it.identity.__new
            }
          };
        }
        if ("identity__added" in it) {
          const { identity__added, ...others } = it;
          return {
            ...others,
            identity: { type: "added", value: it.identity__added }
          };
        }
        if ("identity__deleted" in it) {
          const { identity__deleted, ...others } = it;
          return {
            ...others,
            identity: { type: "deleted", value: it.identity__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("notNull" in it) {
          return {
            ...it,
            notNull: {
              type: "changed",
              old: it.notNull.__old,
              new: it.notNull.__new
            }
          };
        }
        if ("notNull__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            notNull: { type: "added", value: it.notNull__added }
          };
        }
        if ("notNull__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            notNull: { type: "deleted", value: it.notNull__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("primaryKey" in it) {
          return {
            ...it,
            primaryKey: {
              type: "changed",
              old: it.primaryKey.__old,
              new: it.primaryKey.__new
            }
          };
        }
        if ("primaryKey__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "added", value: it.primaryKey__added }
          };
        }
        if ("primaryKey__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "deleted", value: it.primaryKey__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("typeSchema" in it) {
          return {
            ...it,
            typeSchema: {
              type: "changed",
              old: it.typeSchema.__old,
              new: it.typeSchema.__new
            }
          };
        }
        if ("typeSchema__added" in it) {
          const { typeSchema__added, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "added", value: it.typeSchema__added }
          };
        }
        if ("typeSchema__deleted" in it) {
          const { typeSchema__deleted, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "deleted", value: it.typeSchema__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("onUpdate" in it) {
          return {
            ...it,
            onUpdate: {
              type: "changed",
              old: it.onUpdate.__old,
              new: it.onUpdate.__new
            }
          };
        }
        if ("onUpdate__added" in it) {
          const { onUpdate__added, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "added", value: it.onUpdate__added }
          };
        }
        if ("onUpdate__deleted" in it) {
          const { onUpdate__deleted, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "deleted", value: it.onUpdate__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("autoincrement" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).filter(Boolean);
      return result[0];
    };
  }
});

// src/sqlgenerator.ts
function fromJson(statements, dialect6, action, json2) {
  const result = statements.flatMap((statement) => {
    const filtered = convertors.filter((it) => {
      return it.can(statement, dialect6);
    });
    const convertor = filtered.length === 1 ? filtered[0] : void 0;
    if (!convertor) {
      return "";
    }
    return convertor.convert(statement, json2, action);
  }).filter((it) => it !== "");
  return result;
}
var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors;
var init_sqlgenerator = __esm({
  "src/sqlgenerator.ts"() {
    "use strict";
    init_migrate();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_utils2();
    parseType = (schemaPrefix, type) => {
      const pgNativeTypes = [
        "uuid",
        "smallint",
        "integer",
        "bigint",
        "boolean",
        "text",
        "varchar",
        "serial",
        "bigserial",
        "decimal",
        "numeric",
        "real",
        "json",
        "jsonb",
        "time",
        "time with time zone",
        "time without time zone",
        "time",
        "timestamp",
        "timestamp with time zone",
        "timestamp without time zone",
        "date",
        "interval",
        "bigint",
        "bigserial",
        "double precision",
        "interval year",
        "interval month",
        "interval day",
        "interval hour",
        "interval minute",
        "interval second",
        "interval year to month",
        "interval day to hour",
        "interval day to minute",
        "interval day to second",
        "interval hour to minute",
        "interval hour to second",
        "interval minute to second",
        "char",
        "vector",
        "geometry",
        "halfvec",
        "sparsevec",
        "bit"
      ];
      const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
      const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join("");
      const withoutArrayDefinition = type.replace(arrayDefinitionRegex, "");
      return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`;
    };
    Convertor = class {
    };
    PgCreateRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
      }
    };
    PgDropRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `DROP ROLE "${statement.name}";`;
      }
    };
    PgRenameRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
      }
    };
    PgAlterRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
      }
    };
    PgCreatePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        var _a2, _b, _c;
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map(
          (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`;
      }
    };
    PgRenamePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_policy" && dialect6 === "postgresql";
      }
      convert(statement, _dialect, action) {
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgCreateIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        var _a2, _b, _c;
        const policy5 = statement.data;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map(
          (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`;
      }
    };
    PgRenameIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newPolicy = statement.newData;
        const oldPolicy = statement.oldData;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgEnableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "enable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
      }
    };
    PgDisableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "disable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
      }
    };
    PgCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "postgresql";
      }
      convert(st) {
        const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
        let statement = "";
        const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        statement += `CREATE TABLE ${name} (
`;
        for (let i4 = 0; i4 < columns.length; i4++) {
          const column11 = columns[i4];
          const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column11.notNull && !column11.identity ? " NOT NULL" : "";
          const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
          const uniqueConstraint6 = column11.isUnique ? ` CONSTRAINT "${column11.uniqueName}" UNIQUE${column11.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column11.type);
          const generated = column11.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : "";
          const unsquashedIdentity = column11.identity ? PgSquasher.unsquashIdentity(column11.identity) : void 0;
          const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
          const identity = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
          statement += `	"${column11.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`;
          statement += i4 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        const enableRls = new PgEnableRlsConvertor().convert({
          type: "enable_rls",
          tableName,
          schema: schema6
        });
        return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
      }
    };
    MySqlCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "mysql";
      }
      convert(st) {
        var _a2, _b;
        const {
          tableName,
          columns,
          schema: schema6,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i4 = 0; i4 < columns.length; i4++) {
          const column11 = columns[i4];
          const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column11.notNull ? " NOT NULL" : "";
          const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
          const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
          statement += `	\`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i4 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              var _a3, _b2;
              return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.columns[it]) == null ? void 0 : _b2.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SingleStoreCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "singlestore";
      }
      convert(st) {
        var _a2, _b;
        const {
          tableName,
          columns,
          schema: schema6,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i4 = 0; i4 < columns.length; i4++) {
          const column11 = columns[i4];
          const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column11.notNull ? " NOT NULL" : "";
          const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
          const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
          statement += `	\`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
          statement += i4 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              var _a3, _b2;
              return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.columns[it]) == null ? void 0 : _b2.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SQLiteCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const {
          tableName,
          columns,
          referenceData,
          compositePKs,
          uniqueConstraints,
          checkConstraints
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i4 = 0; i4 < columns.length; i4++) {
          const column11 = columns[i4];
          const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column11.notNull ? " NOT NULL" : "";
          const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
          const autoincrementStatement = column11.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS ${column11.generated.as} ${column11.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column11.name}\` ${column11.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
          statement += i4 === columns.length - 1 ? "" : ",\n";
        }
        compositePKs.forEach((it) => {
          statement += ",\n	";
          statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
        });
        for (let i4 = 0; i4 < referenceData.length; i4++) {
          const {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          } = referenceData[i4];
          const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
          const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
          const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
          const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
          statement += ",";
          statement += "\n	";
          statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const check2 of checkConstraints) {
            statement += ",\n";
            const { value, name } = SQLiteSquasher.unsquashCheck(check2);
            statement += `	CONSTRAINT "${name}" CHECK(${value})`;
          }
        }
        statement += `
`;
        statement += `);`;
        statement += `
`;
        return statement;
      }
    };
    PgCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { definition, name: viewName, schema: schema6, with: withOption, materialized, withNoData, tablespace, using } = st;
        const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
        let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
        if (using) statement += ` USING "${using}"`;
        const options = [];
        if (withOption) {
          statement += ` WITH (`;
          Object.entries(withOption).forEach(([key, value]) => {
            if (typeof value === "undefined") return;
            options.push(`${key.snake_case()} = ${value}`);
          });
          statement += options.join(", ");
          statement += `)`;
        }
        if (tablespace) statement += ` TABLESPACE ${tablespace}`;
        statement += ` AS (${definition})`;
        if (withNoData) statement += ` WITH NO DATA`;
        statement += `;`;
        return statement;
      }
    };
    MySqlCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "mysql_create_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st;
        let statement = `CREATE `;
        statement += replace ? `OR REPLACE ` : "";
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name}\` AS (${definition})`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    SqliteCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { definition, name } = st;
        return `CREATE VIEW \`${name}\` AS ${definition};`;
      }
    };
    PgDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: viewName, schema: schema6, materialized } = st;
        const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
        return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
      }
    };
    MySqlDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name } = st;
        return `DROP VIEW \`${name}\`;`;
      }
    };
    SqliteDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { name } = st;
        return `DROP VIEW \`${name}\`;`;
      }
    };
    MySqlAlterViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_mysql_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name, algorithm, definition, sqlSecurity, withCheckOption } = st;
        let statement = `ALTER `;
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name}\` AS ${definition}`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    PgRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to, schema: schema6, materialized } = st;
        const nameFrom = `"${schema6}"."${from}"`;
        return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
      }
    };
    MySqlRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to } = st;
        return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
      }
    };
    PgAlterViewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql";
      }
      convert(st) {
        const { fromSchema, toSchema, name, materialized } = st;
        const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
        return statement;
      }
    };
    PgAlterViewAddWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, with: withOption, name, materialized } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" SET (`;
        const options = [];
        Object.entries(withOption).forEach(([key, value]) => {
          options.push(`${key.snake_case()} = ${value}`);
        });
        statement += options.join(", ");
        statement += `);`;
        return statement;
      }
    };
    PgAlterViewDropWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, materialized, with: withOptions } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" RESET (`;
        const options = [];
        Object.entries(withOptions).forEach(([key, value]) => {
          options.push(`${key.snake_case()}`);
        });
        statement += options.join(", ");
        statement += ");";
        return statement;
      }
    };
    PgAlterViewAlterTablespaceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, toTablespace } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET TABLESPACE ${toTablespace};`;
        return statement;
      }
    };
    PgAlterViewAlterUsingConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_using" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, toUsing } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET ACCESS METHOD "${toUsing}";`;
        return statement;
      }
    };
    PgAlterTableAlterColumnSetGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`;
      }
    };
    PgAlterTableAlterColumnDropGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
      }
    };
    PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, oldIdentity, tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity);
        const statementsToReturn = [];
        if (unsquashedOldIdentity.type !== unsquashedIdentity.type) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};`
          );
        }
        if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};`
          );
        }
        if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};`
          );
        }
        if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};`
          );
        }
        if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};`
          );
        }
        if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};`
          );
        }
        if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};`
          );
        }
        return statementsToReturn;
      }
    };
    PgAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`;
      }
    };
    PgAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
      }
    };
    PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashCheck(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
      }
    };
    PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
      }
    };
    SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
      }
    };
    CreatePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, values, schema: schema6 } = st;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`;
      }
    };
    DropPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, schema: schema6 } = st;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `DROP SEQUENCE ${sequenceWithSchema};`;
      }
    };
    RenamePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom, nameTo, schema: schema6 } = st;
        const sequenceWithSchemaFrom = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
        const sequenceWithSchemaTo = schema6 ? `"${schema6}"."${nameTo}"` : `"${nameTo}"`;
        return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
      }
    };
    MovePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "move_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schemaFrom, schemaTo, name } = st;
        const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
        const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`;
        return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`;
      }
    };
    AlterPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, schema: schema6, values } = st;
        const { increment, minValue, maxValue, startWith, cache: cache3, cycle } = values;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache3 ? ` CACHE ${cache3}` : ""}${cycle ? ` CYCLE` : ""};`;
      }
    };
    CreateTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "create_type_enum";
      }
      convert(st) {
        const { name, values, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        let valuesStatement = "(";
        valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", ");
        valuesStatement += ")";
        let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
        return statement;
      }
    };
    DropTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "drop_type_enum";
      }
      convert(st) {
        const { name, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        let statement = `DROP TYPE ${enumNameWithSchema};`;
        return statement;
      }
    };
    AlterTypeAddValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_add_value";
      }
      convert(st) {
        const { name, schema: schema6, value, before } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
      }
    };
    AlterTypeSetSchemaConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "move_type_enum";
      }
      convert(st) {
        const { name, schemaFrom, schemaTo } = st;
        const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
        return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
      }
    };
    AlterRenameTypeConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "rename_type_enum";
      }
      convert(st) {
        const { nameTo, nameFrom, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
        return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
      }
    };
    AlterTypeDropValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_drop_value";
      }
      convert(st) {
        const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st;
        const statements = [];
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
          );
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;`
            );
          }
        }
        statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name,
          schema: enumSchema4,
          values: newValues,
          type: "create_type_enum"
        }));
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType);
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "postgresql";
      }
      convert(statement, _d, action) {
        const { tableName, schema: schema6, policies } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const dropPolicyConvertor = new PgDropPolicyConvertor();
        const droppedPolicies = (policies == null ? void 0 : policies.map((p3) => {
          return dropPolicyConvertor.convert({
            type: "drop_policy",
            tableName,
            data: action === "push" ? PgSquasher.unsquashPolicyPush(p3) : PgSquasher.unsquashPolicy(p3),
            schema: schema6
          });
        })) ?? [];
        return [
          ...droppedPolicies,
          `DROP TABLE ${tableNameWithSchema} CASCADE;`
        ];
      }
    };
    MySQLDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SingleStoreDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SQLiteDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    PgRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement;
        const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`;
        const to = `"${tableNameTo}"`;
        return `ALTER TABLE ${from} RENAME TO ${to};`;
      }
    };
    SqliteRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    MySqlRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
      }
    };
    SingleStoreRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    PgAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    MySqlAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
      }
    };
    SingleStoreAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`;
      }
    };
    SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    PgAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`;
      }
    };
    MySqlAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SingleStoreAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SQLiteAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    PgAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, column: column11, schema: schema6 } = statement;
        const { name, type, notNull, generated, primaryKey, identity } = column11;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
        const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column11.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : "";
        return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`;
      }
    };
    MySqlAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, column: column11 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column11;
        const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) ${generated == null ? void 0 : generated.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`;
      }
    };
    SingleStoreAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, column: column11 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column11;
        const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) ${generated == null ? void 0 : generated.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`;
      }
    };
    SQLiteAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, column: column11, referenceData } = statement;
        const { name, type, notNull, primaryKey, generated } = column11;
        const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0;
        const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
      }
    };
    PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const statements = [];
        const type = parseType(`"${typeSchema}".`, newDataType.name);
        if (!oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (!oldDataType.isEnum && newDataType.isEnum) {
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};`
          );
        }
        if (oldDataType.isEnum && newDataType.isEnum) {
          const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`;
          if (newDataType.name !== oldDataType.name && columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`,
              alterType,
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          } else {
            statements.push(alterType);
          }
        }
        return statements;
      }
    };
    PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
      }
    };
    PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
      }
    };
    PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
      }
    };
    PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated,
          columnNotNull
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    MySqlAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    MySqlAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    LibSQLModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso";
      }
      convert(statement, json2) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        const sqlStatements = [];
        const indexes = [];
        for (const table6 of Object.values(json2.tables)) {
          for (const index6 of Object.values(table6.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index6);
            sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table6.name });
          }
        }
        switch (statement.type) {
          case "alter_table_alter_column_set_type":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = "";
            break;
          case "alter_table_alter_column_set_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = ` NOT NULL`;
            break;
          case "alter_table_alter_column_set_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        sqlStatements.push(
          `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`
        );
        for (const index6 of indexes) {
          const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index6.where ? ` WHERE ${index6.where}` : "";
          const uniqueString = index6.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index6.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
          );
        }
        return sqlStatements;
      }
    };
    MySqlModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql";
      }
      convert(statement) {
        var _a2, _b, _c, _d, _e, _f, _g;
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.type) === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.type) === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`;
      }
    };
    SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    SingleStoreAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    SingleStoreAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    SingleStoreModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore";
      }
      convert(statement) {
        var _a2, _b, _c, _d, _e, _f, _g;
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.type) === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.type) === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`;
      }
    };
    PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
      }
    };
    PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
          statement.new
        );
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}";
${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`;
      }
    };
    MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
      }
    };
    MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
      }
    };
    MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
          statement.new
        );
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
      }
    };
    PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`;
      }
    };
    PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        return `/* 
    Unfortunately in current drizzle-kit version we can't automatically get name for primary key.
    We are working on making it available!

    Meanwhile you can:
        1. Check pk name in your database, by running
            SELECT constraint_name FROM information_schema.table_constraints
            WHERE table_schema = '${typeof schema6 === "undefined" || schema6 === "" ? "public" : schema6}'
                AND table_name = '${tableName}'
                AND constraint_type = 'PRIMARY KEY';
        2. Uncomment code below and paste pk name manually
        
    Hope to release this update as soon as possible
*/

-- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`;
      }
    };
    PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`;
      }
    };
    PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`;
      }
    };
    PgCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate,
          schemaTo
        } = PgSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = columnsTo.map((it) => `"${it}"`).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`;
        const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        return alterStatement;
      }
    };
    LibSQLCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "turso";
      }
      convert(statement, json2, action) {
        const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
        const { columnDefault, columnNotNull, columnType } = statement;
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
        const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
        const columnTypeValue = columnType ? ` ${columnType}` : "";
        const columnFrom = columnsFrom[0];
        const columnTo = columnsTo[0];
        return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    MySqlCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          name,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate
        } = MySqlSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
        const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
        return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    PgAlterForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newFk = PgSquasher.unsquashFK(statement.data);
        const oldFk = PgSquasher.unsquashFK(statement.oldFkey);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        let sql = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}";
`;
        const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : "";
        const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : "";
        const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(",");
        const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`;
        const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        sql += alterStatement;
        return sql;
      }
    };
    PgDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name } = PgSquasher.unsquashFK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}";
`;
      }
    };
    MySqlDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name } = MySqlSquasher.unsquashFK(statement.data);
        return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name}\`;
`;
      }
    };
    CreatePgIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index_pg" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name,
          columns,
          isUnique,
          concurrently,
          with: withMap,
          method,
          where
        } = statement.data;
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const value = columns.map(
          (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
        ).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        function reverseLogic(mappedWith) {
          let reversedString = "";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}=${mappedWith[key]},`;
            }
          }
          reversedString = reversedString.slice(0, -1);
          return reversedString;
        }
        return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
      }
    };
    CreateMySqlIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns, isUnique } = MySqlSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          var _a2, _b, _c, _d;
          return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSingleStoreIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name, columns, isUnique } = SingleStoreSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          var _a2, _b, _c, _d;
          return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSqliteIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const whereStatement = where ? ` WHERE ${where}` : "";
        const uniqueString = columns.map((it) => {
          var _a2, _b, _c, _d;
          return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
      }
    };
    PgDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { schema: schema6 } = statement;
        const { name } = PgSquasher.unsquashIdx(statement.data);
        const indexNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `DROP INDEX ${indexNameWithSchema};`;
      }
    };
    PgCreateSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name } = statement;
        return `CREATE SCHEMA "${name}";
`;
      }
    };
    PgRenameSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { from, to } = statement;
        return `ALTER SCHEMA "${from}" RENAME TO "${to}";
`;
      }
    };
    PgDropSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name } = statement;
        return `DROP SCHEMA "${name}";
`;
      }
    };
    PgAlterTableSetSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schemaFrom, schemaTo } = statement;
        return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
`;
      }
    };
    PgAlterTableSetNewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, to, from } = statement;
        const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
`;
      }
    };
    PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
`;
      }
    };
    SqliteDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name } = PgSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\`;`;
      }
    };
    MySqlDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name } = MySqlSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
      }
    };
    SingleStoreDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name } = SingleStoreSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
      }
    };
    SQLiteRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "sqlite";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
        );
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    LibSQLRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "turso";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
        );
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    SingleStoreRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, uniqueConstraints } = statement;
        const columnNames = columns.map((it) => `\`${it.name}\``).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(
          new SingleStoreCreateTableConvertor().convert({
            type: "create_table",
            tableName: newTableName,
            columns,
            compositePKs,
            uniqueConstraints,
            schema: ""
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SingleStoreDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SingleStoreRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        return sqlStatements;
      }
    };
    convertors = [];
    convertors.push(new PgCreateTableConvertor());
    convertors.push(new MySqlCreateTableConvertor());
    convertors.push(new SingleStoreCreateTableConvertor());
    convertors.push(new SingleStoreRecreateTableConvertor());
    convertors.push(new SQLiteCreateTableConvertor());
    convertors.push(new SQLiteRecreateTableConvertor());
    convertors.push(new LibSQLRecreateTableConvertor());
    convertors.push(new PgCreateViewConvertor());
    convertors.push(new PgDropViewConvertor());
    convertors.push(new PgRenameViewConvertor());
    convertors.push(new PgAlterViewSchemaConvertor());
    convertors.push(new PgAlterViewAddWithOptionConvertor());
    convertors.push(new PgAlterViewDropWithOptionConvertor());
    convertors.push(new PgAlterViewAlterTablespaceConvertor());
    convertors.push(new PgAlterViewAlterUsingConvertor());
    convertors.push(new MySqlCreateViewConvertor());
    convertors.push(new MySqlDropViewConvertor());
    convertors.push(new MySqlRenameViewConvertor());
    convertors.push(new MySqlAlterViewConvertor());
    convertors.push(new SqliteCreateViewConvertor());
    convertors.push(new SqliteDropViewConvertor());
    convertors.push(new CreateTypeEnumConvertor());
    convertors.push(new DropTypeEnumConvertor());
    convertors.push(new AlterTypeAddValueConvertor());
    convertors.push(new AlterTypeSetSchemaConvertor());
    convertors.push(new AlterRenameTypeConvertor());
    convertors.push(new AlterTypeDropValueConvertor());
    convertors.push(new CreatePgSequenceConvertor());
    convertors.push(new DropPgSequenceConvertor());
    convertors.push(new RenamePgSequenceConvertor());
    convertors.push(new MovePgSequenceConvertor());
    convertors.push(new AlterPgSequenceConvertor());
    convertors.push(new PgDropTableConvertor());
    convertors.push(new MySQLDropTableConvertor());
    convertors.push(new SingleStoreDropTableConvertor());
    convertors.push(new SQLiteDropTableConvertor());
    convertors.push(new PgRenameTableConvertor());
    convertors.push(new MySqlRenameTableConvertor());
    convertors.push(new SingleStoreRenameTableConvertor());
    convertors.push(new SqliteRenameTableConvertor());
    convertors.push(new PgAlterTableRenameColumnConvertor());
    convertors.push(new MySqlAlterTableRenameColumnConvertor());
    convertors.push(new SingleStoreAlterTableRenameColumnConvertor());
    convertors.push(new SQLiteAlterTableRenameColumnConvertor());
    convertors.push(new PgAlterTableDropColumnConvertor());
    convertors.push(new MySqlAlterTableDropColumnConvertor());
    convertors.push(new SingleStoreAlterTableDropColumnConvertor());
    convertors.push(new SQLiteAlterTableDropColumnConvertor());
    convertors.push(new PgAlterTableAddColumnConvertor());
    convertors.push(new MySqlAlterTableAddColumnConvertor());
    convertors.push(new SingleStoreAlterTableAddColumnConvertor());
    convertors.push(new SQLiteAlterTableAddColumnConvertor());
    convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
    convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
    convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
    convertors.push(new PgAlterTableAddCheckConstraintConvertor());
    convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
    convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor());
    convertors.push(new CreatePgIndexConvertor());
    convertors.push(new CreateMySqlIndexConvertor());
    convertors.push(new CreateSingleStoreIndexConvertor());
    convertors.push(new CreateSqliteIndexConvertor());
    convertors.push(new PgDropIndexConvertor());
    convertors.push(new SqliteDropIndexConvertor());
    convertors.push(new MySqlDropIndexConvertor());
    convertors.push(new SingleStoreDropIndexConvertor());
    convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
    convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
    convertors.push(new PgAlterPolicyConvertor());
    convertors.push(new PgCreatePolicyConvertor());
    convertors.push(new PgDropPolicyConvertor());
    convertors.push(new PgRenamePolicyConvertor());
    convertors.push(new PgAlterIndPolicyConvertor());
    convertors.push(new PgCreateIndPolicyConvertor());
    convertors.push(new PgDropIndPolicyConvertor());
    convertors.push(new PgRenameIndPolicyConvertor());
    convertors.push(new PgEnableRlsConvertor());
    convertors.push(new PgDisableRlsConvertor());
    convertors.push(new PgDropRoleConvertor());
    convertors.push(new PgAlterRoleConvertor());
    convertors.push(new PgCreateRoleConvertor());
    convertors.push(new PgRenameRoleConvertor());
    convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new MySqlModifyColumn());
    convertors.push(new LibSQLModifyColumn());
    convertors.push(new SingleStoreModifyColumn());
    convertors.push(new PgCreateForeignKeyConvertor());
    convertors.push(new MySqlCreateForeignKeyConvertor());
    convertors.push(new PgAlterForeignKeyConvertor());
    convertors.push(new PgDeleteForeignKeyConvertor());
    convertors.push(new MySqlDeleteForeignKeyConvertor());
    convertors.push(new PgCreateSchemaConvertor());
    convertors.push(new PgRenameSchemaConvertor());
    convertors.push(new PgDropSchemaConvertor());
    convertors.push(new PgAlterTableSetSchemaConvertor());
    convertors.push(new PgAlterTableSetNewSchemaConvertor());
    convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
    convertors.push(new LibSQLCreateForeignKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGenerated());
    convertors.push(new PgAlterTableAlterColumnSetGenerated());
    convertors.push(new PgAlterTableAlterColumnAlterGenerated());
    convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDropPk());
    convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableAddPk());
    convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new SingleStoreAlterTableDropPk());
    convertors.push(new SingleStoreAlterTableAddPk());
    https: `
create table users (
	id int,
    name character varying(128)
);

create type venum as enum('one', 'two', 'three');
alter table users add column typed venum;

insert into users(id, name, typed) values (1, 'name1', 'one');
insert into users(id, name, typed) values (2, 'name2', 'two');
insert into users(id, name, typed) values (3, 'name3', 'three');

alter type venum rename to __venum;
create type venum as enum ('one', 'two', 'three', 'four', 'five');

ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum;

insert into users(id, name, typed) values (4, 'name4', 'four');
insert into users(id, name, typed) values (5, 'name5', 'five');

drop type __venum;
`;
  }
});

// src/cli/commands/sqlitePushUtils.ts
var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
var init_sqlitePushUtils = __esm({
  "src/cli/commands/sqlitePushUtils.ts"() {
    "use strict";
    init_source();
    init_sqliteSchema();
    init_sqlgenerator();
    init_utils2();
    _moveDataStatements = (tableName, json, dataLoss = false) => {
      const statements = [];
      const newTableName = `__new_${tableName}`;
      const tableColumns = Object.values(json.tables[tableName].columns);
      const referenceData = Object.values(json.tables[tableName].foreignKeys);
      const compositePKs = Object.values(
        json.tables[tableName].compositePrimaryKeys
      ).map((it) => SQLiteSquasher.unsquashPK(it));
      const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
      const mappedCheckConstraints = checkConstraints.map(
        (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
      );
      const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
      statements.push(
        new SQLiteCreateTableConvertor().convert({
          type: "sqlite_create_table",
          tableName: newTableName,
          columns: tableColumns,
          referenceData: fks,
          compositePKs,
          checkConstraints: mappedCheckConstraints
        })
      );
      if (!dataLoss) {
        const columns = Object.keys(json.tables[tableName].columns).map(
          (c3) => `"${c3}"`
        );
        statements.push(
          `INSERT INTO \`${newTableName}\`(${columns.join(
            ", "
          )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
        );
      }
      statements.push(
        new SQLiteDropTableConvertor().convert({
          type: "drop_table",
          tableName,
          schema: ""
        })
      );
      statements.push(
        new SqliteRenameTableConvertor().convert({
          fromSchema: "",
          tableNameFrom: newTableName,
          tableNameTo: tableName,
          toSchema: "",
          type: "rename_table"
        })
      );
      for (const idx of Object.values(json.tables[tableName].indexes)) {
        statements.push(
          new CreateSqliteIndexConvertor().convert({
            type: "create_index",
            tableName,
            schema: "",
            data: idx
          })
        );
      }
      return statements;
    };
    getOldTableName = (tableName, meta) => {
      for (const key of Object.keys(meta.tables)) {
        const value = meta.tables[key];
        if (`"${tableName}"` === value) {
          return key.substring(1, key.length - 1);
        }
      }
      return tableName;
    };
    getNewTableName = (tableName, meta) => {
      if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
        return meta.tables[`"${tableName}"`].substring(
          1,
          meta.tables[`"${tableName}"`].length - 1
        );
      }
      return tableName;
    };
    logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await connection.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_drop_column") {
          const tableName = statement.tableName;
          const columnName = statement.columnName;
          const res = await connection.query(
            `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
          const tableName = statement.tableName;
          const columnName = statement.column.name;
          const res = await connection.query(
            `select count(*) as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to add not-null ${source_default.underline(
                columnName
              )} column without default value, which contains ${count} items`
            );
            tablesToTruncate.push(tableName);
            statementsToExecute.push(`delete from ${tableName};`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "recreate_table") {
          const tableName = statement.tableName;
          const oldTableName = getOldTableName(tableName, meta);
          let dataLoss = false;
          const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
          const currentColumnNames = Object.keys(json2.tables[tableName].columns);
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            prevColumnNames,
            currentColumnNames
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await connection.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count = Number(res[0].count);
              if (count > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await connection.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json2.tables[tableName].columns[addedColumn];
              const count = Number(res.count);
              if (count > 0 && columnConf.notNull && !columnConf.default) {
                dataLoss = true;
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
              }
            }
          }
          const tablesReferencingCurrent = [];
          for (const table6 of Object.values(json2.tables)) {
            const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t4) => SQLiteSquasher.unsquashPushFK(t4).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
            tablesReferencingCurrent.push(...tablesRefs);
          }
          if (!tablesReferencingCurrent.length) {
            statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
            continue;
          }
          const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`);
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=OFF;`);
          }
          statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=ON;`);
          }
        } else {
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/jsonStatements.ts
var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
var init_jsonStatements = __esm({
  "src/jsonStatements.ts"() {
    "use strict";
    init_source();
    init_sqlitePushUtils();
    init_views();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    preparePgCreateTableJson = (table6, json2) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6;
      const tableKey2 = `${schema6 || "public"}.${name}`;
      const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName,
        uniqueConstraints: Object.values(uniqueConstraints),
        policies: Object.values(policies),
        checkConstraints: Object.values(checkConstraints),
        isRLSEnabled: isRLSEnabled ?? false
      };
    };
    prepareMySqlCreateTableJson = (table6, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6;
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals,
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareSingleStoreCreateTableJson = (table6, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6;
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals
      };
    };
    prepareSQLiteCreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, checkConstraints } = table6;
      const references2 = Object.values(table6.foreignKeys);
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      return {
        type: "sqlite_create_table",
        tableName: name,
        columns: Object.values(columns),
        referenceData: fks,
        compositePKs: composites,
        uniqueConstraints: Object.values(uniqueConstraints),
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareDropTableJson = (table6) => {
      return {
        type: "drop_table",
        tableName: table6.name,
        schema: table6.schema,
        policies: table6.policies ? Object.values(table6.policies) : []
      };
    };
    prepareRenameTableJson = (tableFrom, tableTo) => {
      return {
        type: "rename_table",
        fromSchema: tableTo.schema,
        toSchema: tableTo.schema,
        tableNameFrom: tableFrom.name,
        tableNameTo: tableTo.name
      };
    };
    prepareCreateEnumJson = (name, schema6, values) => {
      return {
        type: "create_type_enum",
        name,
        schema: schema6,
        values
      };
    };
    prepareAddValuesToEnumJson = (name, schema6, values) => {
      return values.map((it) => {
        return {
          type: "alter_type_add_value",
          name,
          schema: schema6,
          value: it.value,
          before: it.before
        };
      });
    };
    prepareDropEnumValues = (name, schema6, removedValues, json2) => {
      if (!removedValues.length) return [];
      const affectedColumns = [];
      for (const tableKey2 in json2.tables) {
        const table6 = json2.tables[tableKey2];
        for (const columnKey in table6.columns) {
          const column11 = table6.columns[columnKey];
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedColumnType = column11.type.replace(arrayDefinitionRegex, "");
          if (parsedColumnType === name && column11.typeSchema === schema6) {
            affectedColumns.push({
              tableSchema: table6.schema,
              table: table6.name,
              column: column11.name,
              columnType: column11.type,
              default: column11.default
            });
          }
        }
      }
      return [{
        type: "alter_type_drop_value",
        name,
        enumSchema: schema6,
        deletedValues: removedValues,
        newValues: json2.enums[`${schema6}.${name}`].values,
        columnsWithEnum: affectedColumns
      }];
    };
    prepareDropEnumJson = (name, schema6) => {
      return {
        type: "drop_type_enum",
        name,
        schema: schema6
      };
    };
    prepareMoveEnumJson = (name, schemaFrom, schemaTo) => {
      return {
        type: "move_type_enum",
        name,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameEnumJson = (nameFrom, nameTo, schema6) => {
      return {
        type: "rename_type_enum",
        nameFrom,
        nameTo,
        schema: schema6
      };
    };
    prepareCreateSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return {
        type: "create_sequence",
        name: seq.name,
        schema: seq.schema,
        values
      };
    };
    prepareAlterSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return [
        {
          type: "alter_sequence",
          schema: seq.schema,
          name: seq.name,
          values
        }
      ];
    };
    prepareDropSequenceJson = (name, schema6) => {
      return {
        type: "drop_sequence",
        name,
        schema: schema6
      };
    };
    prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => {
      return {
        type: "move_sequence",
        name,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => {
      return {
        type: "rename_sequence",
        nameFrom,
        nameTo,
        schema: schema6
      };
    };
    prepareCreateRoleJson = (role) => {
      return {
        type: "create_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareAlterRoleJson = (role) => {
      return {
        type: "alter_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareDropRoleJson = (name) => {
      return {
        type: "drop_role",
        name
      };
    };
    prepareRenameRoleJson = (nameFrom, nameTo) => {
      return {
        type: "rename_role",
        nameFrom,
        nameTo
      };
    };
    prepareCreateSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "create_schema",
          name: it
        };
      });
    };
    prepareRenameSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "rename_schema",
          from: it.from,
          to: it.to
        };
      });
    };
    prepareDeleteSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "drop_schema",
          name: it
        };
      });
    };
    prepareRenameColumns = (tableName, schema6, pairs) => {
      return pairs.map((it) => {
        return {
          type: "alter_table_rename_column",
          tableName,
          oldColumnName: it.from.name,
          newColumnName: it.to.name,
          schema: schema6
        };
      });
    };
    _prepareDropColumns = (taleName, schema6, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_drop_column",
          tableName: taleName,
          columnName: it.name,
          schema: schema6
        };
      });
    };
    _prepareAddColumns = (tableName, schema6, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_add_column",
          tableName,
          column: it,
          schema: schema6
        };
      });
    };
    _prepareSqliteAddColumns = (tableName, columns, referenceData) => {
      const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue));
      return columns.map((it) => {
        var _a2;
        const columnsWithReference = unsquashed.find((t4) => t4.columnsFrom.includes(it.name));
        if (((_a2 = it.generated) == null ? void 0 : _a2.type) === "stored") {
          warning(
            `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
          );
          return void 0;
        }
        return {
          type: "sqlite_alter_table_add_column",
          tableName,
          column: it,
          referenceData: columnsWithReference ? SQLiteSquasher.squashFK(columnsWithReference) : void 0
        };
      }).filter(Boolean);
    };
    prepareAlterColumnsMysql = (tableName, schema6, columns, json1, json2, action) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column11 of columns) {
        const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
        const table6 = json2.tables[tableName];
        const snapshotColumn = table6.columns[columnName];
        const columnType = snapshotColumn.type;
        const columnDefault = snapshotColumn.default;
        const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
        const columnNotNull = table6.columns[columnName].notNull;
        const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
        const columnPk = table6.columns[columnName].primaryKey;
        if (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") {
          const type = column11.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_c = column11.autoincrement) == null ? void 0 : _c.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      for (const column11 of columns) {
        const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
        const columnType = json2.tables[tableName].columns[columnName].type;
        const columnDefault = json2.tables[tableName].columns[columnName].default;
        const columnGenerated = json2.tables[tableName].columns[columnName].generated;
        const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
        const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column11.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column11.name.old,
            newColumnName: column11.name.new,
            schema: schema6
          });
        }
        if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column11.type.new,
            oldDataType: column11.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_g = column11.default) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.new,
            oldDefaultValue: column11.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_i = column11.default) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_j = column11.notNull) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_k = column11.notNull) == null ? void 0 : _k.type) === "changed") {
          const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_l = column11.notNull) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
          if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
            warning(
              `You are trying to add virtual generated constraint to ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Nongenerated columns can be altered to stored but not virtual generated columns". We will drop an existing column and add it with a virtual generated statement. This means that the data previously stored in this column will be wiped, and new data will be generated on each read for this column
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
          if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
            warning(
              `You are trying to remove virtual generated constraint from ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Stored but not virtual generated columns can be altered to nongenerated columns. The stored generated values become the values of the nongenerated column". We will drop an existing column and add it without a virtual generated statement. This means that this column will have no data after migration
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated,
            oldColumn: json1.tables[tableName].columns[columnName]
          });
        }
        if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    preparePgAlterColumns = (_tableName, schema6, columns, json2, json1, action) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
      const tableKey2 = `${schema6 || "public"}.${_tableName}`;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column11 of columns) {
        const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
        const tableName = json2.tables[tableKey2].name;
        const columnType = json2.tables[tableKey2].columns[columnName].type;
        const columnDefault = json2.tables[tableKey2].columns[columnName].default;
        const columnGenerated = json2.tables[tableKey2].columns[columnName].generated;
        const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey;
        const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema;
        const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema;
        const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column11.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column11.name.old,
            newColumnName: column11.name.new,
            schema: schema6
          });
        }
        if (((_a2 = column11.type) == null ? void 0 : _a2.type) === "changed") {
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedNewColumnType = column11.type.new.replace(arrayDefinitionRegex, "");
          const parsedOldColumnType = column11.type.old.replace(arrayDefinitionRegex, "");
          const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`];
          const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`];
          statements.push({
            type: "pg_alter_table_alter_column_set_type",
            tableName,
            columnName,
            typeSchema,
            newDataType: {
              name: column11.type.new,
              isEnum: isNewTypeIsEnum ? true : false
            },
            oldDataType: {
              name: column11.type.old,
              isEnum: isOldTypeIsEnum ? true : false
            },
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column11.primaryKey) == null ? void 0 : _b.type) === "deleted" || ((_c = column11.primaryKey) == null ? void 0 : _c.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_d = column11.default) == null ? void 0 : _d.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_e = column11.default) == null ? void 0 : _e.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.new,
            oldDefaultValue: column11.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_f = column11.default) == null ? void 0 : _f.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_g = column11.notNull) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_h = column11.notNull) == null ? void 0 : _h.type) === "changed") {
          const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_i = column11.notNull) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_j = column11.identity) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column11.identity.value
          });
        }
        if (((_k = column11.identity) == null ? void 0 : _k.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_change_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column11.identity.new,
            oldIdentity: column11.identity.old
          });
        }
        if (((_l = column11.identity) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_identity",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareSqliteAlterColumns = (tableName, schema6, columns, json2) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column11 of columns) {
        const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
        const columnType = json2.tables[tableName].columns[columnName].type;
        const columnDefault = json2.tables[tableName].columns[columnName].default;
        const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
        const columnGenerated = json2.tables[tableName].columns[columnName].generated;
        const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") {
          const type = column11.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_c = column11.autoincrement) == null ? void 0 : _c.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (typeof column11.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column11.name.old,
            newColumnName: column11.name.new,
            schema: schema6
          });
        }
        if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column11.type.new,
            oldDataType: column11.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_g = column11.default) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column11.default.new,
            oldDefaultValue: column11.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_i = column11.default) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_j = column11.notNull) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_k = column11.notNull) == null ? void 0 : _k.type) === "changed") {
          const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_l = column11.notNull) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
          if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
            statements.push({
              type: "alter_table_alter_column_set_generated",
              tableName,
              columnName,
              schema: schema6,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed") {
          if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
            statements.push({
              type: "alter_table_alter_column_alter_generated",
              tableName,
              columnName,
              schema: schema6,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareRenamePolicyJsons = (tableName, schema6, renames) => {
      return renames.map((it) => {
        return {
          type: "rename_policy",
          tableName,
          oldName: it.from.name,
          newName: it.to.name,
          schema: schema6
        };
      });
    };
    prepareRenameIndPolicyJsons = (renames) => {
      return renames.map((it) => {
        return {
          type: "rename_ind_policy",
          tableKey: it.from.on,
          oldName: it.from.name,
          newName: it.to.name
        };
      });
    };
    prepareCreatePolicyJsons = (tableName, schema6, policies) => {
      return policies.map((it) => {
        return {
          type: "create_policy",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareCreateIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "create_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareDropPolicyJsons = (tableName, schema6, policies) => {
      return policies.map((it) => {
        return {
          type: "drop_policy",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDropIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "drop_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareAlterPolicyJson = (tableName, schema6, oldPolicy, newPolicy) => {
      return {
        type: "alter_policy",
        tableName,
        oldData: oldPolicy,
        newData: newPolicy,
        schema: schema6
      };
    };
    prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => {
      return {
        type: "alter_ind_policy",
        oldData: oldPolicy,
        newData: newPolicy
      };
    };
    preparePgCreateIndexesJson = (tableName, schema6, indexes, fullSchema, action) => {
      if (action === "push") {
        return Object.values(indexes).map((indexData) => {
          const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData);
          const data = fullSchema.tables[`${schema6 === "" ? "public" : schema6}.${tableName}`].indexes[unsquashedIndex.name];
          return {
            type: "create_index_pg",
            tableName,
            data,
            schema: schema6
          };
        });
      }
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index_pg",
          tableName,
          data: PgSquasher.unsquashIdx(indexData),
          schema: schema6
        };
      });
    };
    prepareCreateIndexesJson = (tableName, schema6, indexes, internal) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index",
          tableName,
          data: indexData,
          schema: schema6,
          internal
        };
      });
    };
    prepareCreateReferencesJson = (tableName, schema6, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema6
        };
      });
    };
    prepareLibSQLCreateReferencesJson = (tableName, schema6, foreignKeys, json2, action) => {
      return Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "create_reference",
            tableName,
            data: fkData,
            schema: schema6,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json2.tables[tableFrom].columns[columnFrom];
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
    };
    prepareDropReferencesJson = (tableName, schema6, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "delete_reference",
          tableName,
          data: fkData,
          schema: schema6
        };
      });
    };
    prepareLibSQLDropReferencesJson = (tableName, schema6, foreignKeys, json2, meta, action) => {
      const statements = Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        const keys = Object.keys(json2.tables[tableName].columns);
        const filtered = columnsFrom.filter((it) => keys.includes(it));
        const fullDrop = filtered.length === 0;
        if (fullDrop) return;
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "delete_reference",
            tableName,
            data: fkData,
            schema: schema6,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const newTableName = getNewTableName(tableFrom, meta);
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json2.tables[newTableName].columns[columnFrom];
        const fkToSquash = {
          columnsFrom,
          columnsTo,
          name,
          tableFrom: newTableName,
          tableTo,
          onDelete,
          onUpdate
        };
        const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
        return {
          type: "delete_reference",
          tableName,
          data: foreignKey,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
      return statements.filter((it) => it);
    };
    prepareAlterReferencesJson = (tableName, schema6, foreignKeys) => {
      const stmts = [];
      Object.values(foreignKeys).map((val2) => {
        stmts.push({
          type: "delete_reference",
          tableName,
          schema: schema6,
          data: val2.__old
        });
        stmts.push({
          type: "create_reference",
          tableName,
          schema: schema6,
          data: val2.__new
        });
      });
      return stmts;
    };
    prepareDropIndexesJson = (tableName, schema6, indexes) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "drop_index",
          tableName,
          data: indexData,
          schema: schema6
        };
      });
    };
    prepareAddCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "create_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new
        };
      });
    };
    prepareAddCompositePrimaryKeyPg = (tableName, schema6, pks, json2) => {
      return Object.values(pks).map((it) => {
        const unsquashed = PgSquasher.unsquashPK(it);
        return {
          type: "create_composite_pk",
          tableName,
          data: it,
          schema: schema6,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareDeleteCompositePrimaryKeyPg = (tableName, schema6, pks, json1) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it,
          schema: schema6,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareAlterCompositePrimaryKeyPg = (tableName, schema6, pks, json1, json2) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          schema: schema6,
          oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
          newConstraintName: PgSquasher.unsquashPK(it.__new).name
        };
      });
    };
    prepareAddUniqueConstraintPg = (tableName, schema6, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "create_unique_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDeleteUniqueConstraintPg = (tableName, schema6, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "delete_unique_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareAddCheckConstraint = (tableName, schema6, check2) => {
      return Object.values(check2).map((it) => {
        return {
          type: "create_check_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDeleteCheckConstraint = (tableName, schema6, check2) => {
      return Object.values(check2).map((it) => {
        return {
          type: "delete_check_constraint",
          tableName,
          constraintName: PgSquasher.unsquashCheck(it).name,
          schema: schema6
        };
      });
    };
    prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
      var _a2, _b;
      const res = [];
      for (const it of Object.values(pks)) {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        if (unsquashed.columns.length === 1 && ((_b = (_a2 = json1.tables[tableName]) == null ? void 0 : _a2.columns[unsquashed.columns[0]]) == null ? void 0 : _b.primaryKey)) {
          continue;
        }
        res.push({
          type: "create_composite_pk",
          tableName,
          data: it,
          constraintName: unsquashed.name
        });
      }
      return res;
    };
    prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
      return Object.values(pks).map((it) => {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name,
          newConstraintName: json2.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name
        };
      });
    };
    preparePgCreateViewJson = (name, schema6, definition, materialized, withNoData = false, withOption, using, tablespace) => {
      return {
        type: "create_view",
        name,
        schema: schema6,
        definition,
        with: withOption,
        materialized,
        withNoData,
        using,
        tablespace
      };
    };
    prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => {
      const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
      return {
        type: "mysql_create_view",
        name,
        definition,
        algorithm,
        sqlSecurity,
        withCheckOption,
        replace
      };
    };
    prepareSqliteCreateViewJson = (name, definition) => {
      return {
        type: "sqlite_create_view",
        name,
        definition
      };
    };
    prepareDropViewJson = (name, schema6, materialized) => {
      const resObject = { name, type: "drop_view" };
      if (schema6) resObject["schema"] = schema6;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    prepareRenameViewJson = (to, from, schema6, materialized) => {
      const resObject = {
        type: "rename_view",
        nameTo: to,
        nameFrom: from
      };
      if (schema6) resObject["schema"] = schema6;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
      const returnObject = {
        type: "alter_view_alter_schema",
        fromSchema: from,
        toSchema: to,
        name
      };
      if (materialized) returnObject["materialized"] = materialized;
      return returnObject;
    };
    preparePgAlterViewAddWithOptionJson = (name, schema6, materialized, withOption) => {
      return {
        type: "alter_view_add_with_option",
        name,
        schema: schema6,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewDropWithOptionJson = (name, schema6, materialized, withOption) => {
      return {
        type: "alter_view_drop_with_option",
        name,
        schema: schema6,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewAlterTablespaceJson = (name, schema6, materialized, to) => {
      return {
        type: "alter_view_alter_tablespace",
        name,
        schema: schema6,
        materialized,
        toTablespace: to
      };
    };
    preparePgAlterViewAlterUsingJson = (name, schema6, materialized, to) => {
      return {
        type: "alter_view_alter_using",
        name,
        schema: schema6,
        materialized,
        toUsing: to
      };
    };
    prepareMySqlAlterView = (view5) => {
      return { type: "alter_mysql_view", ...view5 };
    };
  }
});

// src/statementCombiner.ts
var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
var init_statementCombiner = __esm({
  "src/statementCombiner.ts"() {
    "use strict";
    init_jsonStatements();
    init_sqliteSchema();
    prepareLibSQLRecreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    prepareSQLiteRecreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    libSQLCombineStatements = (statements, json2, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
          const { tableName: tableName2, columnName, columnPk } = statement;
          const columnIsPartOfForeignKey = Object.values(
            json2.tables[tableName2].foreignKeys
          ).some((it) => {
            const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
            return unsquashFk.columnsFrom.includes(columnName);
          });
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
            }
            continue;
          }
          if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              newStatements[tableName2].push(statement);
            }
            continue;
          }
          newStatements[tableName2] = [statement];
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement];
            continue;
          }
          if (!statement.isMulticolumn && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (statement.isMulticolumn) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
              continue;
            }
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            newStatements[tableName2].push(statement);
          }
          continue;
        }
        if (statement.type === "delete_reference") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    sqliteCombineStatements = (statements, json2, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (data.columnsFrom.length === 1 && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    prepareSingleStoreRecreateTable = (table6) => {
      const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6;
      const composites = Object.values(compositePrimaryKeys);
      const statements = [
        {
          type: "singlestore_recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          uniqueConstraints: Object.values(uniqueConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    singleStoreCombineStatements = (statements, json2) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(
              ({ type }) => type === "rename_table" || type === "alter_table_rename_column"
            );
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
  }
});

// src/snapshotsDiffer.ts
var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
var init_snapshotsDiffer = __esm({
  "src/snapshotsDiffer.ts"() {
    "use strict";
    init_esm();
    init_jsonDiffer();
    init_sqlgenerator();
    init_jsonStatements();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_statementCombiner();
    init_utils2();
    makeChanged = (schema6) => {
      return objectType({
        type: enumType(["changed"]),
        old: schema6,
        new: schema6
      });
    };
    makeSelfOrChanged = (schema6) => {
      return unionType([
        schema6,
        objectType({
          type: enumType(["changed"]),
          old: schema6,
          new: schema6
        })
      ]);
    };
    makePatched = (schema6) => {
      return unionType([
        objectType({
          type: literalType("added"),
          value: schema6
        }),
        objectType({
          type: literalType("deleted"),
          value: schema6
        }),
        objectType({
          type: literalType("changed"),
          old: schema6,
          new: schema6
        })
      ]);
    };
    columnSchema = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType().optional(),
      default: anyType().optional(),
      notNull: booleanType().optional(),
      // should it be optional? should if be here?
      autoincrement: booleanType().optional(),
      onUpdate: booleanType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        as: stringType(),
        type: enumType(["stored", "virtual"]).default("stored")
      }).optional(),
      identity: stringType().optional()
    }).strict();
    alteredColumnSchema = objectType({
      name: makeSelfOrChanged(stringType()),
      type: makeChanged(stringType()).optional(),
      default: makePatched(anyType()).optional(),
      primaryKey: makePatched(booleanType()).optional(),
      notNull: makePatched(booleanType()).optional(),
      typeSchema: makePatched(stringType()).optional(),
      onUpdate: makePatched(booleanType()).optional(),
      autoincrement: makePatched(booleanType()).optional(),
      generated: makePatched(
        objectType({
          as: stringType(),
          type: enumType(["stored", "virtual"]).default("stored")
        })
      ).optional(),
      identity: makePatched(stringType()).optional()
    }).strict();
    enumSchema3 = objectType({
      name: stringType(),
      schema: stringType(),
      values: arrayType(stringType())
    }).strict();
    changedEnumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      addedValues: objectType({
        before: stringType(),
        value: stringType()
      }).array(),
      deletedValues: arrayType(stringType())
    }).strict();
    tableScheme = objectType({
      name: stringType(),
      schema: stringType().default(""),
      columns: recordType(stringType(), columnSchema),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      policies: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    alteredTableScheme = objectType({
      name: stringType(),
      schema: stringType(),
      altered: alteredColumnSchema.array(),
      addedIndexes: recordType(stringType(), stringType()),
      deletedIndexes: recordType(stringType(), stringType()),
      alteredIndexes: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedForeignKeys: recordType(stringType(), stringType()),
      deletedForeignKeys: recordType(stringType(), stringType()),
      alteredForeignKeys: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedCompositePKs: recordType(stringType(), stringType()),
      deletedCompositePKs: recordType(stringType(), stringType()),
      alteredCompositePKs: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedUniqueConstraints: recordType(stringType(), stringType()),
      deletedUniqueConstraints: recordType(stringType(), stringType()),
      alteredUniqueConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedPolicies: recordType(stringType(), stringType()),
      deletedPolicies: recordType(stringType(), stringType()),
      alteredPolicies: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      deletedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      alteredCheckConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      )
    }).strict();
    alteredViewCommon = objectType({
      name: stringType(),
      alteredDefinition: objectType({
        __old: stringType(),
        __new: stringType()
      }).strict().optional(),
      alteredExisting: objectType({
        __old: booleanType(),
        __new: booleanType()
      }).strict().optional()
    });
    alteredPgViewSchema = alteredViewCommon.merge(
      objectType({
        schema: stringType(),
        deletedWithOption: mergedViewWithOption.optional(),
        addedWithOption: mergedViewWithOption.optional(),
        addedWith: mergedViewWithOption.optional(),
        deletedWith: mergedViewWithOption.optional(),
        alteredWith: mergedViewWithOption.optional(),
        alteredSchema: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredTablespace: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredUsing: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    alteredMySqlViewSchema = alteredViewCommon.merge(
      objectType({
        alteredMeta: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    diffResultScheme = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: changedEnumSchema.array(),
      alteredSequences: sequenceSquashed.array(),
      alteredRoles: roleSchema.array(),
      alteredPolicies: policySquashed.array(),
      alteredViews: alteredPgViewSchema.array()
    }).strict();
    diffResultSchemeMysql = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredMySqlViewSchema.array()
    });
    diffResultSchemeSingleStore = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array()
    });
    diffResultSchemeSQLite = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredViewCommon.array()
    });
    schemaChangeFor = (table6, renamedSchemas) => {
      for (let ren of renamedSchemas) {
        if (table6.schema === ren.from.name) {
          return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        schema: table6.schema
      };
    };
    nameChangeFor = (table6, renamed) => {
      for (let ren of renamed) {
        if (table6.name === ren.from.name) {
          return { name: ren.to.name };
        }
      }
      return {
        name: table6.name
      };
    };
    nameSchemaChangeFor = (table6, renamedTables) => {
      for (let ren of renamedTables) {
        if (table6.name === ren.from.name && table6.schema === ren.from.schema) {
          return {
            key: `${ren.to.schema || "public"}.${ren.to.name}`,
            name: ren.to.name,
            schema: ren.to.schema
          };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        name: table6.name,
        schema: table6.schema
      };
    };
    columnChangeFor = (column11, renamedColumns) => {
      for (let ren of renamedColumns) {
        if (column11 === ren.from.name) {
          return ren.to.name;
        }
      }
      return column11;
    };
    applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
      const {
        created: createdSchemas,
        deleted: deletedSchemas,
        renamed: renamedSchemas
      } = await schemasResolver2({
        created: schemasDiff.added.map((it) => ({ name: it })),
        deleted: schemasDiff.deleted.map((it) => ({ name: it }))
      });
      const schemasPatchedSnap1 = copy(json1);
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (_3, it) => {
          const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema6;
          return [key, it];
        }
      );
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
        const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
        it.schema = schema6;
        return [key, it];
      });
      const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums);
      const {
        created: createdEnums,
        deleted: deletedEnums,
        renamed: renamedEnums,
        moved: movedEnums
      } = await enumsResolver2({
        created: enumsDiff.added,
        deleted: enumsDiff.deleted
      });
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
        const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums);
        it.name = name;
        it.schema = schema6;
        return [key, it];
      });
      const columnTypesChangeMap = renamedEnums.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const columnTypesMovesMap = movedEnums.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column11) => {
            const key = `${column11.typeSchema || "public"}.${column11.type}`;
            const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
            if (change) {
              column11.type = change.nameTo;
              column11.typeSchema = change.schemaTo;
            }
            return column11;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_3, it) => {
          const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema6;
          return [key, it];
        }
      );
      const sequencesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.sequences,
        json2.sequences
      );
      const {
        created: createdSequences,
        deleted: deletedSequences,
        renamed: renamedSequences,
        moved: movedSequences
      } = await sequencesResolver2({
        created: sequencesDiff.added,
        deleted: sequencesDiff.deleted
      });
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_3, it) => {
          const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences);
          it.name = name;
          it.schema = schema6;
          return [key, it];
        }
      );
      const sequencesChangeMap = renamedSequences.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const sequencesMovesMap = movedSequences.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column11) => {
            const key = `${column11.typeSchema || "public"}.${column11.type}`;
            const change = sequencesChangeMap[key] || sequencesMovesMap[key];
            if (change) {
              column11.type = change.nameTo;
              column11.typeSchema = change.schemaTo;
            }
            return column11;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const rolesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.roles,
        json2.roles
      );
      const {
        created: createdRoles,
        deleted: deletedRoles,
        renamed: renamedRoles
      } = await roleResolver2({
        created: rolesDiff.added,
        deleted: rolesDiff.deleted
      });
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (_3, it) => {
          const { name } = nameChangeFor(it, renamedRoles);
          it.name = name;
          return [name, it];
        }
      );
      const rolesChangeMap = renamedRoles.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (roleKey, roleValue) => {
          const key = roleKey;
          const change = rolesChangeMap[key];
          if (change) {
            roleValue.name = change.nameTo;
          }
          return [roleKey, roleValue];
        }
      );
      const tablesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.tables,
        json2.tables
      );
      const {
        created: createdTables,
        deleted: deletedTables,
        moved: movedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(schemasPatchedSnap1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables);
        it.name = name;
        it.schema = schema6;
        return [key, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created2.length > 0) {
          columnCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          columnDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column11) => {
              const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(columnKey, rens);
              column11.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
      const policyRenames = [];
      const policyCreates = [];
      const policyDeletes = [];
      for (let entry of Object.values(policyRes)) {
        const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.policies.deleted.map(
            action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy
          ),
          created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
        });
        if (created2.length > 0) {
          policyCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          policyDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          policyRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const policyRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const policyPatchedSnap1 = copy(tablesPatchedSnap1);
      policyPatchedSnap1.tables = mapEntries(
        policyPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedPolicies = mapKeys(
            tableValue.policies,
            (policyKey, policy5) => {
              const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(policyKey, rens);
              const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5);
              unsquashedPolicy.name = newName;
              policy5 = PgSquasher.squashPolicy(unsquashedPolicy);
              return newName;
            }
          );
          tableValue.policies = patchedPolicies;
          return [tableKey2, tableValue];
        }
      );
      const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies);
      const indPolicyCreates = [];
      const indPolicyDeletes = [];
      const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({
        deleted: indPolicyRes.deleted.map(
          (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.values)
        ),
        created: indPolicyRes.added.map(
          (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.values)
        )
      });
      if (created.length > 0) {
        indPolicyCreates.push({
          policies: created
        });
      }
      if (deleted.length > 0) {
        indPolicyDeletes.push({
          policies: deleted
        });
      }
      const indPolicyRenamesDict = indPolicyRenames.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      const indPolicyPatchedSnap1 = copy(policyPatchedSnap1);
      indPolicyPatchedSnap1.policies = mapEntries(
        indPolicyPatchedSnap1.policies,
        (policyKey, policyValue) => {
          const key = policyKey;
          const change = indPolicyRenamesDict[key];
          if (change) {
            policyValue.name = change.nameTo;
          }
          return [policyKey, policyValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews,
        moved: movedViews
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
      });
      const movedViewDic = {};
      movedViews.forEach((it) => {
        movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
      });
      const viewsPatchedSnap1 = copy(policyPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
          const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = `${viewValue.schema}.${viewValue.name}`;
          }
          if (moved) viewKey = `${moved.to}.${viewValue.name}`;
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultScheme.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull,
          action
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonRenameColumnsStatements = [];
      const jsonDropColumnsStatemets = [];
      const jsonAddColumnsStatemets = [];
      for (let it of columnRenames) {
        jsonRenameColumnsStatements.push(
          ...prepareRenameColumns(it.table, it.schema, it.renames)
        );
      }
      for (let it of columnDeletes) {
        jsonDropColumnsStatemets.push(
          ..._prepareDropColumns(it.table, it.schema, it.columns)
        );
      }
      for (let it of columnCreates) {
        jsonAddColumnsStatemets.push(
          ..._prepareAddColumns(it.table, it.schema, it.columns)
        );
      }
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonSetTableSchemas = [];
      if (movedTables) {
        for (let it of movedTables) {
          jsonSetTableSchemas.push({
            type: "alter_table_set_schema",
            tableName: it.name,
            schemaFrom: it.schemaFrom || "public",
            schemaTo: it.schemaTo || "public"
          });
        }
      }
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      for (let it of alteredTables) {
        let addedColumns;
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = PgSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns;
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = PgSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {});
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.addedCompositePKs,
            curFull
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.deletedCompositePKs,
            prevFull
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
          it.name,
          it.schema,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createCheckConstraints = [];
        let deleteCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted2 = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted2[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted2)
          );
        }
        createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deleteCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted2 = {};
          for (const k3 of Object.keys(it.alteredCheckConstraints)) {
            added[k3] = it.alteredCheckConstraints[k3].__new;
            deleted2[k3] = it.alteredCheckConstraints[k3].__old;
          }
          createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2));
        }
        jsonCreatedCheckConstraints.push(...createCheckConstraints);
        jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      }
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return preparePgAlterColumns(
          it.name,
          it.schema,
          it.altered,
          json2,
          json1,
          action
        );
      }).flat();
      const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull,
          action
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      const jsonCreatePoliciesStatements = [];
      const jsonDropPoliciesStatements = [];
      const jsonAlterPoliciesStatements = [];
      const jsonRenamePoliciesStatements = [];
      const jsonRenameIndPoliciesStatements = [];
      const jsonCreateIndPoliciesStatements = [];
      const jsonDropIndPoliciesStatements = [];
      const jsonAlterIndPoliciesStatements = [];
      const jsonEnableRLSStatements = [];
      const jsonDisableRLSStatements = [];
      for (let it of indPolicyRenames) {
        jsonRenameIndPoliciesStatements.push(
          ...prepareRenameIndPolicyJsons([it])
        );
      }
      for (const it of indPolicyCreates) {
        jsonCreateIndPoliciesStatements.push(
          ...prepareCreateIndPolicyJsons(
            it.policies
          )
        );
      }
      for (const it of indPolicyDeletes) {
        jsonDropIndPoliciesStatements.push(
          ...prepareDropIndPolicyJsons(
            it.policies
          )
        );
      }
      typedResult.alteredPolicies.forEach(({ values }) => {
        const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values);
        if (newPolicy.as !== oldPolicy.as) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        if (newPolicy.for !== oldPolicy.for) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        jsonAlterIndPoliciesStatements.push(
          prepareAlterIndPolicyJson(
            oldPolicy,
            newPolicy
          )
        );
      });
      for (let it of policyRenames) {
        jsonRenamePoliciesStatements.push(
          ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
        );
      }
      for (const it of policyCreates) {
        jsonCreatePoliciesStatements.push(
          ...prepareCreatePolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      for (const it of policyDeletes) {
        jsonDropPoliciesStatements.push(
          ...prepareDropPolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      alteredTables.forEach((it) => {
        Object.keys(it.alteredPolicies).forEach((policyName) => {
          const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
          const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
          if (newPolicy.as !== oldPolicy.as) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          if (newPolicy.for !== oldPolicy.for) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          jsonAlterPoliciesStatements.push(
            prepareAlterPolicyJson(
              it.name,
              it.schema,
              it.alteredPolicies[policyName].__old,
              it.alteredPolicies[policyName].__new
            )
          );
        });
        for (const table6 of Object.values(json2.tables)) {
          const policiesInCurrentState = Object.keys(table6.policies);
          const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
          if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) {
            jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
          }
          if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
          const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
          if (table6.isRLSEnabled !== wasRlsEnabled) {
            if (table6.isRLSEnabled) {
              jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
            } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) {
              jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
            }
          }
        }
        for (const table6 of Object.values(columnsPatchedSnap1.tables)) {
          const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          if (tableInCurrentState === void 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
        }
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesFoAlteredTables.push(
          ...preparePgCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull,
            action
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t4) => t4.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t4) => t4.type === "delete_reference"
      );
      const createEnums = createdEnums.map((it) => {
        return prepareCreateEnumJson(it.name, it.schema, it.values);
      }) ?? [];
      const dropEnums = deletedEnums.map((it) => {
        return prepareDropEnumJson(it.name, it.schema);
      });
      const moveEnums = movedEnums.map((it) => {
        return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameEnums = renamedEnums.map((it) => {
        return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
        return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
      }).flat() ?? [];
      const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
        return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
      }).flat() ?? [];
      const createSequences = createdSequences.map((it) => {
        return prepareCreateSequenceJson(it);
      }) ?? [];
      const dropSequences = deletedSequences.map((it) => {
        return prepareDropSequenceJson(it.name, it.schema);
      });
      const moveSequences = movedSequences.map((it) => {
        return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameSequences = renamedSequences.map((it) => {
        return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
        return prepareAlterSequenceJson(it);
      }).flat() ?? [];
      const createRoles = createdRoles.map((it) => {
        return prepareCreateRoleJson(it);
      }) ?? [];
      const dropRoles = deletedRoles.map((it) => {
        return prepareDropRoleJson(it.name);
      });
      const renameRoles = renamedRoles.map((it) => {
        return prepareRenameRoleJson(it.from.name, it.to.name);
      });
      const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
        return prepareAlterRoleJson(it);
      }).flat() ?? [];
      const createSchemas = prepareCreateSchemasJson(
        createdSchemas.map((it) => it.name)
      );
      const renameSchemas = prepareRenameSchemasJson(
        renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name }))
      );
      const dropSchemas = prepareDeleteSchemasJson(
        deletedSchemas.map((it) => it.name)
      );
      const createTables = createdTables.map((it) => {
        return preparePgCreateTableJson(it, curFull);
      });
      jsonCreatePoliciesStatements.push(...[].concat(
        ...createdTables.map(
          (it) => prepareCreatePolicyJsons(
            it.name,
            it.schema,
            Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
          )
        )
      ));
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return preparePgCreateViewJson(
            it.name,
            it.schema,
            it.definition,
            it.materialized,
            it.withNoData,
            it.with,
            it.using,
            it.tablespace
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name, it.schema, it.materialized);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
        })
      );
      alterViews.push(
        ...movedViews.filter(
          (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
        ).map((it) => {
          return preparePgAlterViewAlterSchemaJson(
            it.schemaTo,
            it.schemaFrom,
            it.name,
            json2.views[`${it.schemaTo}.${it.name}`].materialized
          );
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
      for (const alteredView of alteredViews) {
        const viewKey = `${alteredView.schema}.${alteredView.name}`;
        const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
          createViews.push(
            preparePgCreateViewJson(
              alteredView.name,
              alteredView.schema,
              definition,
              materialized,
              withNoData,
              withOption,
              using,
              tablespace
            )
          );
          continue;
        }
        if (alteredView.addedWithOption) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWithOption
            )
          );
        }
        if (alteredView.deletedWithOption) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWithOption
            )
          );
        }
        if (alteredView.addedWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWith
            )
          );
        }
        if (alteredView.deletedWith) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWith
            )
          );
        }
        if (alteredView.alteredWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredWith
            )
          );
        }
        if (alteredView.alteredTablespace) {
          alterViews.push(
            preparePgAlterViewAlterTablespaceJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredTablespace.__new
            )
          );
        }
        if (alteredView.alteredUsing) {
          alterViews.push(
            preparePgAlterViewAlterUsingJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredUsing.__new
            )
          );
        }
      }
      jsonStatements.push(...createSchemas);
      jsonStatements.push(...renameSchemas);
      jsonStatements.push(...createEnums);
      jsonStatements.push(...moveEnums);
      jsonStatements.push(...renameEnums);
      jsonStatements.push(...jsonAlterEnumsWithAddedValues);
      jsonStatements.push(...createSequences);
      jsonStatements.push(...moveSequences);
      jsonStatements.push(...renameSequences);
      jsonStatements.push(...jsonAlterSequences);
      jsonStatements.push(...renameRoles);
      jsonStatements.push(...dropRoles);
      jsonStatements.push(...createRoles);
      jsonStatements.push(...jsonAlterRoles);
      jsonStatements.push(...createTables);
      jsonStatements.push(...jsonEnableRLSStatements);
      jsonStatements.push(...jsonDisableRLSStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonSetTableSchemas);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesFoAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonRenamePoliciesStatements);
      jsonStatements.push(...jsonDropPoliciesStatements);
      jsonStatements.push(...jsonCreatePoliciesStatements);
      jsonStatements.push(...jsonAlterPoliciesStatements);
      jsonStatements.push(...jsonRenameIndPoliciesStatements);
      jsonStatements.push(...jsonDropIndPoliciesStatements);
      jsonStatements.push(...jsonCreateIndPoliciesStatements);
      jsonStatements.push(...jsonAlterIndPoliciesStatements);
      jsonStatements.push(...dropEnums);
      jsonStatements.push(...dropSequences);
      jsonStatements.push(...dropSchemas);
      const filteredJsonStatements = jsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_drop_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        if (st.type === "alter_table_alter_column_set_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
        if (st.type === "alter_type_add_value") {
          if (filteredJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_set_default") {
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find(
              (column11) => column11.default === st.newDefaultValue && column11.column === st.columnName && column11.table === st.tableName && column11.tableSchema === st.schema
            )
          )) {
            return false;
          }
        }
        return true;
      });
      const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action);
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rSchemas = renamedSchemas.map((it) => ({
        from: it.from.name,
        to: it.to.name
      }));
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
      return {
        statements: filteredEnums2JsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName6 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table6 = json2.tables[tableName];
        for (const indexName6 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json2.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column11) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column11.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeMysql.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonCreatedCheckConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
          it.name,
          it.addedCompositePKs,
          prevFull,
          curFull
        );
        deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
          it.name,
          it.deletedCompositePKs,
          prevFull
        );
        alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
          it.name,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredCheckConstraints)) {
            added[k3] = it.alteredCheckConstraints[k3].__new;
            deleted[k3] = it.alteredCheckConstraints[k3].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json2,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAllAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "delete_reference"
      );
      const jsonMySqlCreateTables = createdTables.map((it) => {
        return prepareMySqlCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareMySqlCreateViewJson(
            it.name,
            it.definition,
            it.meta
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition, meta } = json2.views[alteredView.name];
        if (alteredView.alteredExisting) {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta
            )
          );
          continue;
        }
        if (alteredView.alteredDefinition && action !== "push") {
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta,
              true
            )
          );
          continue;
        }
        if (alteredView.alteredMeta) {
          const view5 = curFull["views"][alteredView.name];
          alterViews.push(
            prepareMySqlAlterView(view5)
          );
        }
      }
      jsonStatements.push(...jsonMySqlCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const sqlStatements = fromJson(jsonStatements, "mysql");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: jsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName6 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table6 = json2.tables[tableName];
        for (const indexName6 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json2.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column11) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column11.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSingleStore.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredCheckConstraints)) {
            added[k3] = it.alteredCheckConstraints[k3].__new;
            deleted[k3] = it.alteredCheckConstraints[k3].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json2,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonSingleStoreCreateTables = createdTables.map((it) => {
        return prepareSingleStoreCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      jsonStatements.push(...jsonSingleStoreCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2);
      const sqlStatements = fromJson(combinedJsonStatements, "singlestore");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column11) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column11.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredCheckConstraints)) {
            added[k3] = it.alteredCheckConstraints[k3].__new;
            deleted[k3] = it.alteredCheckConstraints[k3].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json2.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
      const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column11) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column11.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
            added[k3] = it.alteredUniqueConstraints[k3].__new;
            deleted[k3] = it.alteredUniqueConstraints[k3].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k3 of Object.keys(it.alteredCheckConstraints)) {
            added[k3] = it.alteredCheckConstraints[k3].__new;
            deleted[k3] = it.alteredCheckConstraints[k3].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareLibSQLCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys,
          json2,
          action
        );
        const forAltered = prepareLibSQLDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys,
          json2,
          _meta,
          action
        );
        const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t4) => t4.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json2.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
      const sqlStatements = fromJson(
        combinedJsonStatements,
        "turso",
        action,
        json2
      );
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
  }
});

// src/utils/words.ts
var prepareMigrationMetadata, adjectives, heroes;
var init_words = __esm({
  "src/utils/words.ts"() {
    "use strict";
    prepareMigrationMetadata = (idx, prefixMode, name) => {
      const prefix2 = prefixMode === "index" ? idx.toFixed(0).padStart(4, "0") : prefixMode === "timestamp" || prefixMode === "supabase" ? (/* @__PURE__ */ new Date()).toISOString().replace("T", "").replaceAll("-", "").replaceAll(":", "").slice(0, 14) : prefixMode === "unix" ? Math.floor(Date.now() / 1e3) : "";
      const suffix = name || `${adjectives.random()}_${heroes.random()}`;
      const tag = `${prefix2}_${suffix}`;
      return { prefix: prefix2, suffix, tag };
    };
    adjectives = [
      "abandoned",
      "aberrant",
      "abnormal",
      "absent",
      "absurd",
      "acoustic",
      "adorable",
      "amazing",
      "ambiguous",
      "ambitious",
      "amused",
      "amusing",
      "ancient",
      "aromatic",
      "aspiring",
      "awesome",
      "bent",
      "big",
      "bitter",
      "bizarre",
      "black",
      "blue",
      "blushing",
      "bored",
      "boring",
      "bouncy",
      "brainy",
      "brave",
      "breezy",
      "brief",
      "bright",
      "broad",
      "broken",
      "brown",
      "bumpy",
      "burly",
      "busy",
      "calm",
      "careful",
      "careless",
      "certain",
      "charming",
      "cheerful",
      "chemical",
      "chief",
      "chilly",
      "chubby",
      "chunky",
      "clammy",
      "classy",
      "clean",
      "clear",
      "clever",
      "cloudy",
      "closed",
      "clumsy",
      "cold",
      "colorful",
      "colossal",
      "common",
      "complete",
      "complex",
      "concerned",
      "condemned",
      "confused",
      "conscious",
      "cooing",
      "cool",
      "crazy",
      "cuddly",
      "cultured",
      "curious",
      "curly",
      "curved",
      "curvy",
      "cute",
      "cynical",
      "daffy",
      "daily",
      "damp",
      "dapper",
      "dark",
      "dashing",
      "dazzling",
      "dear",
      "deep",
      "demonic",
      "dizzy",
      "dry",
      "dusty",
      "eager",
      "early",
      "easy",
      "elite",
      "eminent",
      "empty",
      "equal",
      "even",
      "exotic",
      "fair",
      "faithful",
      "familiar",
      "famous",
      "fancy",
      "fantastic",
      "far",
      "fast",
      "fat",
      "faulty",
      "fearless",
      "fine",
      "first",
      "fixed",
      "flaky",
      "flashy",
      "flat",
      "flawless",
      "flimsy",
      "flippant",
      "flowery",
      "fluffy",
      "foamy",
      "free",
      "freezing",
      "fresh",
      "friendly",
      "funny",
      "furry",
      "futuristic",
      "fuzzy",
      "giant",
      "gifted",
      "gigantic",
      "glamorous",
      "glorious",
      "glossy",
      "good",
      "goofy",
      "gorgeous",
      "graceful",
      "gray",
      "great",
      "greedy",
      "green",
      "grey",
      "groovy",
      "handy",
      "happy",
      "hard",
      "harsh",
      "heavy",
      "hesitant",
      "high",
      "hot",
      "huge",
      "icy",
      "illegal",
      "jazzy",
      "jittery",
      "keen",
      "kind",
      "known",
      "lame",
      "large",
      "last",
      "late",
      "lazy",
      "lean",
      "left",
      "legal",
      "lethal",
      "light",
      "little",
      "lively",
      "living",
      "lonely",
      "long",
      "loose",
      "loud",
      "lovely",
      "loving",
      "low",
      "lowly",
      "lucky",
      "lumpy",
      "lush",
      "luxuriant",
      "lying",
      "lyrical",
      "magenta",
      "magical",
      "majestic",
      "many",
      "massive",
      "married",
      "marvelous",
      "material",
      "mature",
      "mean",
      "medical",
      "melodic",
      "melted",
      "messy",
      "mighty",
      "military",
      "milky",
      "minor",
      "misty",
      "mixed",
      "moaning",
      "modern",
      "motionless",
      "mushy",
      "mute",
      "mysterious",
      "naive",
      "nappy",
      "narrow",
      "nasty",
      "natural",
      "neat",
      "nebulous",
      "needy",
      "nervous",
      "new",
      "next",
      "nice",
      "nifty",
      "noisy",
      "normal",
      "nostalgic",
      "nosy",
      "numerous",
      "odd",
      "old",
      "omniscient",
      "open",
      "opposite",
      "optimal",
      "orange",
      "ordinary",
      "organic",
      "outgoing",
      "outstanding",
      "oval",
      "overconfident",
      "overjoyed",
      "overrated",
      "pale",
      "panoramic",
      "parallel",
      "parched",
      "past",
      "peaceful",
      "perfect",
      "perpetual",
      "petite",
      "pink",
      "plain",
      "polite",
      "powerful",
      "premium",
      "pretty",
      "previous",
      "productive",
      "public",
      "purple",
      "puzzling",
      "quick",
      "quiet",
      "rainy",
      "rapid",
      "rare",
      "real",
      "red",
      "redundant",
      "reflective",
      "regular",
      "remarkable",
      "rich",
      "right",
      "robust",
      "romantic",
      "round",
      "sad",
      "safe",
      "salty",
      "same",
      "secret",
      "serious",
      "shallow",
      "sharp",
      "shiny",
      "shocking",
      "short",
      "silent",
      "silky",
      "silly",
      "simple",
      "skinny",
      "sleepy",
      "slim",
      "slimy",
      "slippery",
      "sloppy",
      "slow",
      "small",
      "smart",
      "smiling",
      "smooth",
      "soft",
      "solid",
      "sour",
      "sparkling",
      "special",
      "spicy",
      "spooky",
      "spotty",
      "square",
      "stale",
      "steady",
      "steep",
      "sticky",
      "stiff",
      "stormy",
      "strange",
      "striped",
      "strong",
      "sturdy",
      "sudden",
      "superb",
      "supreme",
      "sweet",
      "swift",
      "talented",
      "tan",
      "tearful",
      "tense",
      "thankful",
      "thick",
      "thin",
      "third",
      "tidy",
      "tiny",
      "tired",
      "tiresome",
      "tough",
      "tranquil",
      "tricky",
      "true",
      "typical",
      "uneven",
      "unique",
      "unknown",
      "unusual",
      "useful",
      "vengeful",
      "violet",
      "volatile",
      "wakeful",
      "wandering",
      "warm",
      "watery",
      "wealthy",
      "wet",
      "white",
      "whole",
      "wide",
      "wild",
      "windy",
      "wise",
      "wonderful",
      "wooden",
      "woozy",
      "workable",
      "worried",
      "worthless",
      "yellow",
      "yielding",
      "young",
      "youthful",
      "yummy",
      "zippy"
    ];
    heroes = [
      "aaron_stack",
      "abomination",
      "absorbing_man",
      "adam_destine",
      "adam_warlock",
      "agent_brand",
      "agent_zero",
      "albert_cleary",
      "alex_power",
      "alex_wilder",
      "alice",
      "amazoness",
      "amphibian",
      "angel",
      "anita_blake",
      "annihilus",
      "anthem",
      "apocalypse",
      "aqueduct",
      "arachne",
      "archangel",
      "arclight",
      "ares",
      "argent",
      "avengers",
      "azazel",
      "banshee",
      "baron_strucker",
      "baron_zemo",
      "barracuda",
      "bastion",
      "beast",
      "bedlam",
      "ben_grimm",
      "ben_parker",
      "ben_urich",
      "betty_brant",
      "betty_ross",
      "beyonder",
      "big_bertha",
      "bill_hollister",
      "bishop",
      "black_bird",
      "black_bolt",
      "black_cat",
      "black_crow",
      "black_knight",
      "black_panther",
      "black_queen",
      "black_tarantula",
      "black_tom",
      "black_widow",
      "blackheart",
      "blacklash",
      "blade",
      "blazing_skull",
      "blindfold",
      "blink",
      "blizzard",
      "blob",
      "blockbuster",
      "blonde_phantom",
      "bloodaxe",
      "bloodscream",
      "bloodstorm",
      "bloodstrike",
      "blue_blade",
      "blue_marvel",
      "blue_shield",
      "blur",
      "boom_boom",
      "boomer",
      "boomerang",
      "bromley",
      "brood",
      "brother_voodoo",
      "bruce_banner",
      "bucky",
      "bug",
      "bulldozer",
      "bullseye",
      "bushwacker",
      "butterfly",
      "cable",
      "callisto",
      "calypso",
      "cammi",
      "cannonball",
      "captain_america",
      "captain_britain",
      "captain_cross",
      "captain_flint",
      "captain_marvel",
      "captain_midlands",
      "captain_stacy",
      "captain_universe",
      "cardiac",
      "caretaker",
      "cargill",
      "carlie_cooper",
      "carmella_unuscione",
      "carnage",
      "cassandra_nova",
      "catseye",
      "celestials",
      "centennial",
      "cerebro",
      "cerise",
      "chamber",
      "chameleon",
      "champions",
      "changeling",
      "charles_xavier",
      "chat",
      "chimera",
      "christian_walker",
      "chronomancer",
      "clea",
      "clint_barton",
      "cloak",
      "cobalt_man",
      "colleen_wing",
      "colonel_america",
      "colossus",
      "corsair",
      "crusher_hogan",
      "crystal",
      "cyclops",
      "dagger",
      "daimon_hellstrom",
      "dakota_north",
      "daredevil",
      "dark_beast",
      "dark_phoenix",
      "darkhawk",
      "darkstar",
      "darwin",
      "dazzler",
      "deadpool",
      "deathbird",
      "deathstrike",
      "demogoblin",
      "devos",
      "dexter_bennett",
      "diamondback",
      "doctor_doom",
      "doctor_faustus",
      "doctor_octopus",
      "doctor_spectrum",
      "doctor_strange",
      "domino",
      "donald_blake",
      "doomsday",
      "doorman",
      "dorian_gray",
      "dormammu",
      "dracula",
      "dragon_lord",
      "dragon_man",
      "drax",
      "dreadnoughts",
      "dreaming_celestial",
      "dust",
      "earthquake",
      "echo",
      "eddie_brock",
      "edwin_jarvis",
      "ego",
      "electro",
      "elektra",
      "emma_frost",
      "enchantress",
      "ender_wiggin",
      "energizer",
      "epoch",
      "eternals",
      "eternity",
      "excalibur",
      "exiles",
      "exodus",
      "expediter",
      "ezekiel",
      "ezekiel_stane",
      "fabian_cortez",
      "falcon",
      "fallen_one",
      "famine",
      "fantastic_four",
      "fat_cobra",
      "felicia_hardy",
      "fenris",
      "firebird",
      "firebrand",
      "firedrake",
      "firelord",
      "firestar",
      "fixer",
      "flatman",
      "forge",
      "forgotten_one",
      "frank_castle",
      "franklin_richards",
      "franklin_storm",
      "freak",
      "frightful_four",
      "frog_thor",
      "gabe_jones",
      "galactus",
      "gambit",
      "gamma_corps",
      "gamora",
      "gargoyle",
      "garia",
      "gateway",
      "gauntlet",
      "genesis",
      "george_stacy",
      "gertrude_yorkes",
      "ghost_rider",
      "giant_girl",
      "giant_man",
      "gideon",
      "gladiator",
      "glorian",
      "goblin_queen",
      "golden_guardian",
      "goliath",
      "gorgon",
      "gorilla_man",
      "grandmaster",
      "gravity",
      "green_goblin",
      "gressill",
      "grey_gargoyle",
      "greymalkin",
      "grim_reaper",
      "groot",
      "guardian",
      "guardsmen",
      "gunslinger",
      "gwen_stacy",
      "hairball",
      "hammerhead",
      "hannibal_king",
      "hardball",
      "harpoon",
      "harrier",
      "harry_osborn",
      "havok",
      "hawkeye",
      "hedge_knight",
      "hellcat",
      "hellfire_club",
      "hellion",
      "hemingway",
      "hercules",
      "hex",
      "hiroim",
      "hitman",
      "hobgoblin",
      "hulk",
      "human_cannonball",
      "human_fly",
      "human_robot",
      "human_torch",
      "husk",
      "hydra",
      "iceman",
      "ikaris",
      "imperial_guard",
      "impossible_man",
      "inertia",
      "infant_terrible",
      "inhumans",
      "ink",
      "invaders",
      "invisible_woman",
      "iron_fist",
      "iron_lad",
      "iron_man",
      "iron_monger",
      "iron_patriot",
      "ironclad",
      "jack_flag",
      "jack_murdock",
      "jack_power",
      "jackal",
      "jackpot",
      "james_howlett",
      "jamie_braddock",
      "jane_foster",
      "jasper_sitwell",
      "jazinda",
      "jean_grey",
      "jetstream",
      "jigsaw",
      "jimmy_woo",
      "jocasta",
      "johnny_blaze",
      "johnny_storm",
      "joseph",
      "joshua_kane",
      "joystick",
      "jubilee",
      "juggernaut",
      "junta",
      "justice",
      "justin_hammer",
      "kabuki",
      "kang",
      "karen_page",
      "karma",
      "karnak",
      "kat_farrell",
      "kate_bishop",
      "katie_power",
      "ken_ellis",
      "khan",
      "kid_colt",
      "killer_shrike",
      "killmonger",
      "killraven",
      "king_bedlam",
      "king_cobra",
      "kingpin",
      "kinsey_walden",
      "kitty_pryde",
      "klaw",
      "komodo",
      "korath",
      "korg",
      "korvac",
      "kree",
      "krista_starr",
      "kronos",
      "kulan_gath",
      "kylun",
      "la_nuit",
      "lady_bullseye",
      "lady_deathstrike",
      "lady_mastermind",
      "lady_ursula",
      "lady_vermin",
      "lake",
      "landau",
      "layla_miller",
      "leader",
      "leech",
      "legion",
      "lenny_balinger",
      "leo",
      "leopardon",
      "leper_queen",
      "lester",
      "lethal_legion",
      "lifeguard",
      "lightspeed",
      "lila_cheney",
      "lilandra",
      "lilith",
      "lily_hollister",
      "lionheart",
      "living_lightning",
      "living_mummy",
      "living_tribunal",
      "liz_osborn",
      "lizard",
      "loa",
      "lockheed",
      "lockjaw",
      "logan",
      "loki",
      "loners",
      "longshot",
      "lord_hawal",
      "lord_tyger",
      "lorna_dane",
      "luckman",
      "lucky_pierre",
      "luke_cage",
      "luminals",
      "lyja",
      "ma_gnuci",
      "mac_gargan",
      "mach_iv",
      "machine_man",
      "mad_thinker",
      "madame_hydra",
      "madame_masque",
      "madame_web",
      "maddog",
      "madelyne_pryor",
      "madripoor",
      "madrox",
      "maelstrom",
      "maestro",
      "magdalene",
      "maggott",
      "magik",
      "maginty",
      "magma",
      "magneto",
      "magus",
      "major_mapleleaf",
      "makkari",
      "malcolm_colcord",
      "malice",
      "mandarin",
      "mandrill",
      "mandroid",
      "manta",
      "mantis",
      "marauders",
      "maria_hill",
      "mariko_yashida",
      "marrow",
      "marten_broadcloak",
      "martin_li",
      "marvel_apes",
      "marvel_boy",
      "marvel_zombies",
      "marvex",
      "masked_marvel",
      "masque",
      "master_chief",
      "master_mold",
      "mastermind",
      "mathemanic",
      "matthew_murdock",
      "mattie_franklin",
      "mauler",
      "maverick",
      "maximus",
      "may_parker",
      "medusa",
      "meggan",
      "meltdown",
      "menace",
      "mentallo",
      "mentor",
      "mephisto",
      "mephistopheles",
      "mercury",
      "mesmero",
      "metal_master",
      "meteorite",
      "micromacro",
      "microbe",
      "microchip",
      "micromax",
      "midnight",
      "miek",
      "mikhail_rasputin",
      "millenium_guard",
      "mimic",
      "mindworm",
      "miracleman",
      "miss_america",
      "mister_fear",
      "mister_sinister",
      "misty_knight",
      "mockingbird",
      "moira_mactaggert",
      "mojo",
      "mole_man",
      "molecule_man",
      "molly_hayes",
      "molten_man",
      "mongoose",
      "mongu",
      "monster_badoon",
      "moon_knight",
      "moondragon",
      "moonstone",
      "morbius",
      "mordo",
      "morg",
      "morgan_stark",
      "morlocks",
      "morlun",
      "morph",
      "mother_askani",
      "mulholland_black",
      "multiple_man",
      "mysterio",
      "mystique",
      "namor",
      "namora",
      "namorita",
      "naoko",
      "natasha_romanoff",
      "nebula",
      "nehzno",
      "nekra",
      "nemesis",
      "network",
      "newton_destine",
      "next_avengers",
      "nextwave",
      "nick_fury",
      "nico_minoru",
      "nicolaos",
      "night_nurse",
      "night_thrasher",
      "nightcrawler",
      "nighthawk",
      "nightmare",
      "nightshade",
      "nitro",
      "nocturne",
      "nomad",
      "norman_osborn",
      "norrin_radd",
      "northstar",
      "nova",
      "nuke",
      "obadiah_stane",
      "odin",
      "ogun",
      "old_lace",
      "omega_flight",
      "omega_red",
      "omega_sentinel",
      "onslaught",
      "oracle",
      "orphan",
      "otto_octavius",
      "outlaw_kid",
      "overlord",
      "owl",
      "ozymandias",
      "paibok",
      "paladin",
      "pandemic",
      "paper_doll",
      "patch",
      "patriot",
      "payback",
      "penance",
      "pepper_potts",
      "pestilence",
      "pet_avengers",
      "pete_wisdom",
      "peter_parker",
      "peter_quill",
      "phalanx",
      "phantom_reporter",
      "phil_sheldon",
      "photon",
      "piledriver",
      "pixie",
      "plazm",
      "polaris",
      "post",
      "power_man",
      "power_pack",
      "praxagora",
      "preak",
      "pretty_boy",
      "pride",
      "prima",
      "princess_powerful",
      "prism",
      "prodigy",
      "proemial_gods",
      "professor_monster",
      "proteus",
      "proudstar",
      "prowler",
      "psylocke",
      "psynapse",
      "puck",
      "puff_adder",
      "puma",
      "punisher",
      "puppet_master",
      "purifiers",
      "purple_man",
      "pyro",
      "quasar",
      "quasimodo",
      "queen_noir",
      "quentin_quire",
      "quicksilver",
      "rachel_grey",
      "radioactive_man",
      "rafael_vega",
      "rage",
      "raider",
      "randall",
      "randall_flagg",
      "random",
      "rattler",
      "ravenous",
      "rawhide_kid",
      "raza",
      "reaper",
      "reavers",
      "red_ghost",
      "red_hulk",
      "red_shift",
      "red_skull",
      "red_wolf",
      "redwing",
      "reptil",
      "retro_girl",
      "revanche",
      "rhino",
      "rhodey",
      "richard_fisk",
      "rick_jones",
      "ricochet",
      "rictor",
      "riptide",
      "risque",
      "robbie_robertson",
      "robin_chapel",
      "rocket_raccoon",
      "rocket_racer",
      "rockslide",
      "rogue",
      "roland_deschain",
      "romulus",
      "ronan",
      "roughhouse",
      "roulette",
      "roxanne_simpson",
      "rumiko_fujikawa",
      "runaways",
      "sabra",
      "sabretooth",
      "sage",
      "sally_floyd",
      "salo",
      "sandman",
      "santa_claus",
      "saracen",
      "sasquatch",
      "satana",
      "sauron",
      "scalphunter",
      "scarecrow",
      "scarlet_spider",
      "scarlet_witch",
      "scorpion",
      "scourge",
      "scrambler",
      "scream",
      "screwball",
      "sebastian_shaw",
      "secret_warriors",
      "selene",
      "senator_kelly",
      "sentinel",
      "sentinels",
      "sentry",
      "ser_duncan",
      "serpent_society",
      "sersi",
      "shadow_king",
      "shadowcat",
      "shaman",
      "shape",
      "shard",
      "sharon_carter",
      "sharon_ventura",
      "shatterstar",
      "shen",
      "sheva_callister",
      "shinko_yamashiro",
      "shinobi_shaw",
      "shiva",
      "shiver_man",
      "shocker",
      "shockwave",
      "shooting_star",
      "shotgun",
      "shriek",
      "silhouette",
      "silk_fever",
      "silver_centurion",
      "silver_fox",
      "silver_sable",
      "silver_samurai",
      "silver_surfer",
      "silverclaw",
      "silvermane",
      "sinister_six",
      "sir_ram",
      "siren",
      "sister_grimm",
      "skaar",
      "skin",
      "skreet",
      "skrulls",
      "skullbuster",
      "slapstick",
      "slayback",
      "sleeper",
      "sleepwalker",
      "slipstream",
      "slyde",
      "smasher",
      "smiling_tiger",
      "snowbird",
      "solo",
      "songbird",
      "spacker_dave",
      "spectrum",
      "speed",
      "speed_demon",
      "speedball",
      "spencer_smythe",
      "sphinx",
      "spiral",
      "spirit",
      "spitfire",
      "spot",
      "sprite",
      "spyke",
      "squadron_sinister",
      "squadron_supreme",
      "squirrel_girl",
      "star_brand",
      "starbolt",
      "stardust",
      "starfox",
      "starhawk",
      "starjammers",
      "stark_industries",
      "stature",
      "steel_serpent",
      "stellaris",
      "stepford_cuckoos",
      "stephen_strange",
      "steve_rogers",
      "stick",
      "stingray",
      "stone_men",
      "storm",
      "stranger",
      "strong_guy",
      "stryfe",
      "sue_storm",
      "sugar_man",
      "sumo",
      "sunfire",
      "sunset_bain",
      "sunspot",
      "supernaut",
      "supreme_intelligence",
      "surge",
      "susan_delgado",
      "swarm",
      "sway",
      "switch",
      "swordsman",
      "synch",
      "tag",
      "talisman",
      "talkback",
      "talon",
      "talos",
      "tana_nile",
      "tarantula",
      "tarot",
      "taskmaster",
      "tattoo",
      "ted_forrester",
      "tempest",
      "tenebrous",
      "terrax",
      "terror",
      "texas_twister",
      "thaddeus_ross",
      "thanos",
      "the_anarchist",
      "the_call",
      "the_captain",
      "the_enforcers",
      "the_executioner",
      "the_fallen",
      "the_fury",
      "the_hand",
      "the_hood",
      "the_hunter",
      "the_initiative",
      "the_leader",
      "the_liberteens",
      "the_order",
      "the_phantom",
      "the_professor",
      "the_renegades",
      "the_santerians",
      "the_spike",
      "the_stranger",
      "the_twelve",
      "the_watchers",
      "thena",
      "thing",
      "thor",
      "thor_girl",
      "thunderball",
      "thunderbird",
      "thunderbolt",
      "thunderbolt_ross",
      "thunderbolts",
      "thundra",
      "tiger_shark",
      "tigra",
      "timeslip",
      "tinkerer",
      "titania",
      "titanium_man",
      "toad",
      "toad_men",
      "tomas",
      "tombstone",
      "tomorrow_man",
      "tony_stark",
      "toro",
      "toxin",
      "trauma",
      "triathlon",
      "trish_tilby",
      "triton",
      "true_believers",
      "turbo",
      "tusk",
      "tyger_tiger",
      "typhoid_mary",
      "tyrannus",
      "ulik",
      "ultimates",
      "ultimatum",
      "ultimo",
      "ultragirl",
      "ultron",
      "umar",
      "unicorn",
      "union_jack",
      "unus",
      "valeria_richards",
      "valkyrie",
      "vampiro",
      "vance_astro",
      "vanisher",
      "vapor",
      "vargas",
      "vector",
      "veda",
      "vengeance",
      "venom",
      "venus",
      "vermin",
      "vertigo",
      "victor_mancha",
      "vin_gonzales",
      "vindicator",
      "violations",
      "viper",
      "virginia_dare",
      "vision",
      "vivisector",
      "vulcan",
      "vulture",
      "wallflower",
      "wallop",
      "wallow",
      "war_machine",
      "warbird",
      "warbound",
      "warhawk",
      "warlock",
      "warpath",
      "warstar",
      "wasp",
      "weapon_omega",
      "wendell_rand",
      "wendell_vaughn",
      "wendigo",
      "whiplash",
      "whirlwind",
      "whistler",
      "white_queen",
      "white_tiger",
      "whizzer",
      "wiccan",
      "wild_child",
      "wild_pack",
      "wildside",
      "william_stryker",
      "wilson_fisk",
      "wind_dancer",
      "winter_soldier",
      "wither",
      "wolf_cub",
      "wolfpack",
      "wolfsbane",
      "wolverine",
      "wonder_man",
      "wong",
      "wraith",
      "wrecker",
      "wrecking_crew",
      "xavin",
      "xorn",
      "yellow_claw",
      "yellowjacket",
      "young_avengers",
      "zaladane",
      "zaran",
      "zarda",
      "zarek",
      "zeigeist",
      "zemo",
      "zodiak",
      "zombie",
      "zuras",
      "zzzax"
    ];
  }
});

// src/cli/commands/migrate.ts
var migrate_exports = {};
__export(migrate_exports, {
  BREAKPOINT: () => BREAKPOINT,
  columnsResolver: () => columnsResolver,
  embeddedMigrations: () => embeddedMigrations,
  enumsResolver: () => enumsResolver,
  indPolicyResolver: () => indPolicyResolver,
  mySqlViewsResolver: () => mySqlViewsResolver,
  policyResolver: () => policyResolver,
  prepareAndExportLibSQL: () => prepareAndExportLibSQL,
  prepareAndExportMysql: () => prepareAndExportMysql,
  prepareAndExportPg: () => prepareAndExportPg,
  prepareAndExportSinglestore: () => prepareAndExportSinglestore,
  prepareAndExportSqlite: () => prepareAndExportSqlite,
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
  prepareAndMigratePg: () => prepareAndMigratePg,
  prepareAndMigrateSingleStore: () => prepareAndMigrateSingleStore,
  prepareAndMigrateSqlite: () => prepareAndMigrateSqlite,
  prepareLibSQLPush: () => prepareLibSQLPush,
  prepareMySQLPush: () => prepareMySQLPush,
  preparePgPush: () => preparePgPush,
  prepareSQLitePush: () => prepareSQLitePush,
  prepareSingleStorePush: () => prepareSingleStorePush,
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
  promptColumnsConflicts: () => promptColumnsConflicts,
  promptNamedConflict: () => promptNamedConflict,
  promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
  promptSchemasConflict: () => promptSchemasConflict,
  roleResolver: () => roleResolver,
  schemasResolver: () => schemasResolver,
  sequencesResolver: () => sequencesResolver,
  sqliteViewsResolver: () => sqliteViewsResolver,
  tablesResolver: () => tablesResolver,
  viewsResolver: () => viewsResolver,
  writeResult: () => writeResult
});
var import_fs6, import_hanji3, import_path5, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, prepareAndMigratePg, prepareAndExportPg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareSingleStorePush, prepareAndMigrateSingleStore, prepareAndExportSinglestore, prepareAndExportMysql, prepareAndMigrateSqlite, prepareAndExportSqlite, prepareAndMigrateLibSQL, prepareAndExportLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
var init_migrate = __esm({
  "src/cli/commands/migrate.ts"() {
    "use strict";
    import_fs6 = __toESM(require("fs"));
    init_migrationPreparator();
    init_source();
    import_hanji3 = __toESM(require_hanji());
    import_path5 = __toESM(require("path"));
    init_singlestoreSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_sqliteSchema();
    init_snapshotsDiffer();
    init_utils2();
    init_words();
    init_outputs();
    init_views();
    schemasResolver = async (input) => {
      try {
        const { created, deleted, renamed } = await promptSchemasConflict(
          input.created,
          input.deleted
        );
        return { created, deleted, renamed };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    tablesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "table"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    viewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    mySqlViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    sqliteViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    sequencesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "sequence"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    roleResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "role"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    policyResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    indPolicyResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "policy"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    enumsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "enum"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e4) {
        console.error(e4);
        throw e4;
      }
    };
    columnsResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    prepareAndMigratePg = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(
          outFolder,
          "postgresql"
        );
        const { prev, cur, custom: custom2 } = await preparePgMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = pgSchema.parse(prev);
        const validatedCur = pgSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashPgScheme(validatedPrev);
        const squashedCur = squashPgScheme(validatedCur);
        const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
          squashedPrev,
          squashedCur,
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndExportPg = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await preparePgMigrationSnapshot(
          [],
          // no snapshots before
          schemaPath,
          void 0
        );
        const validatedPrev = pgSchema.parse(prev);
        const validatedCur = pgSchema.parse(cur);
        const squashedPrev = squashPgScheme(validatedPrev);
        const squashedCur = squashPgScheme(validatedCur);
        const { sqlStatements } = await applyPgSnapshotsDiff(
          squashedPrev,
          squashedCur,
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e4) {
        console.error(e4);
      }
    };
    preparePgPush = async (cur, prev) => {
      const validatedPrev = pgSchema.parse(prev);
      const validatedCur = pgSchema.parse(cur);
      const squashedPrev = squashPgScheme(validatedPrev, "push");
      const squashedCur = squashPgScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applyPgSnapshotsDiff(
        squashedPrev,
        squashedCur,
        schemasResolver,
        enumsResolver,
        sequencesResolver,
        policyResolver,
        indPolicyResolver,
        roleResolver,
        tablesResolver,
        columnsResolver,
        viewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return { sqlStatements, statements, squashedPrev, squashedCur };
    };
    prepareMySQLPush = async (schemaPath, snapshot, casing2) => {
      try {
        const { prev, cur } = await prepareMySqlDbPushSnapshot(
          snapshot,
          schemaPath,
          casing2
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur,
          "push"
        );
        return { sqlStatements, statements, validatedCur, validatedPrev };
      } catch (e4) {
        console.error(e4);
        process.exit(1);
      }
    };
    prepareAndMigrateMysql = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "mysql");
        const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareSingleStorePush = async (schemaPath, snapshot, casing2) => {
      try {
        const { prev, cur } = await prepareSingleStoreDbPushSnapshot(
          snapshot,
          schemaPath,
          casing2
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, statements } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur,
          "push"
        );
        return { sqlStatements, statements, validatedCur, validatedPrev };
      } catch (e4) {
        console.error(e4);
        process.exit(1);
      }
    };
    prepareAndMigrateSingleStore = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "singlestore");
        const { prev, cur, custom: custom2 } = await prepareSingleStoreMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndExportSinglestore = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await prepareSingleStoreMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndExportMysql = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndMigrateSqlite = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            bundle: config.bundle,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          bundle: config.bundle,
          prefixMode: config.prefix,
          driver: config.driver
        });
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndExportSqlite = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await prepareSqliteMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndMigrateLibSQL = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            bundle: config.bundle,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          bundle: config.bundle,
          prefixMode: config.prefix
        });
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareAndExportLibSQL = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e4) {
        console.error(e4);
      }
    };
    prepareSQLitePush = async (schemaPath, snapshot, casing2) => {
      const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
      const validatedPrev = sqliteSchema.parse(prev);
      const validatedCur = sqliteSchema.parse(cur);
      const squashedPrev = squashSqliteScheme(validatedPrev, "push");
      const squashedCur = squashSqliteScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
        squashedPrev,
        squashedCur,
        tablesResolver,
        columnsResolver,
        sqliteViewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return {
        sqlStatements,
        statements,
        squashedPrev,
        squashedCur,
        meta: _meta
      };
    };
    prepareLibSQLPush = async (schemaPath, snapshot, casing2) => {
      const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
      const validatedPrev = sqliteSchema.parse(prev);
      const validatedCur = sqliteSchema.parse(cur);
      const squashedPrev = squashSqliteScheme(validatedPrev, "push");
      const squashedCur = squashSqliteScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
        squashedPrev,
        squashedCur,
        tablesResolver,
        columnsResolver,
        sqliteViewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return {
        sqlStatements,
        statements,
        squashedPrev,
        squashedCur,
        meta: _meta
      };
    };
    promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
      if (newColumns.length === 0 || missingColumns.length === 0) {
        return { created: newColumns, renamed: [], deleted: missingColumns };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingColumns];
      do {
        const created = newColumns[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.render)(
          new ResolveColumnSelect(tableName, created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "column will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "column will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newColumns.length);
      console.log(
        source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
`)
      );
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.render)(
          new ResolveSelectNamed(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          moved: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], moved: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.render)(
          new ResolveSelect(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
          const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
          console.log(
            `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          if (data.from.schema !== data.to.schema) {
            result.moved.push({
              name: data.from.name,
              schemaFrom: data.from.schema || "public",
              schemaTo: data.to.schema || "public"
            });
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptSchemasConflict = async (newSchemas, missingSchemas) => {
      if (missingSchemas.length === 0 || newSchemas.length === 0) {
        return { created: newSchemas, renamed: [], deleted: missingSchemas };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingSchemas];
      do {
        const created = newSchemas[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.render)(
          new ResolveSchemasSelect(created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "schema will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "schema will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newSchemas.length);
      console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
      result.deleted.push(...leftMissing);
      return result;
    };
    BREAKPOINT = "--> statement-breakpoint\n";
    writeResult = ({
      cur,
      sqlStatements,
      journal,
      _meta = {
        columns: {},
        schemas: {},
        tables: {}
      },
      outFolder,
      breakpoints,
      name,
      bundle = false,
      type = "none",
      prefixMode,
      driver: driver2
    }) => {
      if (type === "none") {
        console.log(schema4(cur));
        if (sqlStatements.length === 0) {
          console.log("No schema changes, nothing to migrate \u{1F634}");
          return;
        }
      }
      const lastEntryInJournal = journal.entries[journal.entries.length - 1];
      const idx = typeof lastEntryInJournal === "undefined" ? 0 : lastEntryInJournal.idx + 1;
      const { prefix: prefix2, tag } = prepareMigrationMetadata(idx, prefixMode, name);
      const toSave = JSON.parse(JSON.stringify(cur));
      toSave["_meta"] = _meta;
      const metaFolderPath = (0, import_path5.join)(outFolder, "meta");
      const metaJournal = (0, import_path5.join)(metaFolderPath, "_journal.json");
      import_fs6.default.writeFileSync(
        (0, import_path5.join)(metaFolderPath, `${prefix2}_snapshot.json`),
        JSON.stringify(toSave, null, 2)
      );
      const sqlDelimiter = breakpoints ? BREAKPOINT : "\n";
      let sql = sqlStatements.join(sqlDelimiter);
      if (type === "introspect") {
        sql = `-- Current sql file was generated after introspecting the database
-- If you want to run this migration please uncomment this code before executing migrations
/*
${sql}
*/`;
      }
      if (type === "custom") {
        console.log("Prepared empty file for your custom SQL migration!");
        sql = "-- Custom SQL migration file, put your code below! --";
      }
      journal.entries.push({
        idx,
        version: cur.version,
        when: +/* @__PURE__ */ new Date(),
        tag,
        breakpoints
      });
      import_fs6.default.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
      import_fs6.default.writeFileSync(`${outFolder}/${tag}.sql`, sql);
      if (bundle) {
        const js = embeddedMigrations(journal, driver2);
        import_fs6.default.writeFileSync(`${outFolder}/migrations.js`, js);
      }
      (0, import_hanji3.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your SQL migration file \u279C ${source_default.bold.underline.blue(
          import_path5.default.join(`${outFolder}/${tag}.sql`)
        )} \u{1F680}`
      );
    };
    embeddedMigrations = (journal, driver2) => {
      let content = driver2 === "expo" ? "// This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo\n\n" : "";
      content += "import journal from './meta/_journal.json';\n";
      journal.entries.forEach((entry) => {
        content += `import m${entry.idx.toString().padStart(4, "0")} from './${entry.tag}.sql';
`;
      });
      content += `
  export default {
    journal,
    migrations: {
      ${journal.entries.map((it) => `m${it.idx.toString().padStart(4, "0")}`).join(",\n")}
    }
  }
  `;
      return content;
    };
    prepareSnapshotFolderName = () => {
      const now = /* @__PURE__ */ new Date();
      return `${now.getFullYear()}${two(now.getUTCMonth() + 1)}${two(
        now.getUTCDate()
      )}${two(now.getUTCHours())}${two(now.getUTCMinutes())}${two(
        now.getUTCSeconds()
      )}`;
    };
    two = (input) => {
      return input.toString().padStart(2, "0");
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js
var require_constants = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports2, module2) {
    "use strict";
    var SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module2.exports = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports2, module2) {
    "use strict";
    var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module2.exports = debug;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js
var require_re = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports2, module2) {
    "use strict";
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants();
    var debug = require_debug();
    exports2 = module2.exports = {};
    var re = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var safeSrc = exports2.safeSrc = [];
    var t4 = exports2.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = (value) => {
      for (const [token, max] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
      }
      return value;
    };
    var createToken = (name, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index6 = R++;
      debug(name, index6, value);
      t4[name] = index6;
      src[index6] = value;
      safeSrc[index6] = safe;
      re[index6] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0);
    };
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`);
    createToken("FULL", `^${src[t4.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`);
    createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t4.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?(?:${src[t4.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t4.COERCE], true);
    createToken("COERCERTLFULL", src[t4.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true);
    exports2.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true);
    exports2.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true);
    exports2.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})\\s+-\\s+(${src[t4.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t4.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports2, module2) {
    "use strict";
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions2 = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module2.exports = parseOptions2;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports2, module2) {
    "use strict";
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = (a3, b3) => {
      const anum = numeric.test(a3);
      const bnum = numeric.test(b3);
      if (anum && bnum) {
        a3 = +a3;
        b3 = +b3;
      }
      return a3 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a3 < b3 ? -1 : 1;
    };
    var rcompareIdentifiers = (a3, b3) => compareIdentifiers(b3, a3);
    module2.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports2, module2) {
    "use strict";
    var debug = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
    var { safeRe: re, t: t4 } = require_re();
    var parseOptions2 = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version3, options) {
        options = parseOptions2(options);
        if (version3 instanceof _SemVer) {
          if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) {
            return version3;
          } else {
            version3 = version3.version;
          }
        } else if (typeof version3 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`);
        }
        if (version3.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version3, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m4 = version3.trim().match(options.loose ? re[t4.LOOSE] : re[t4.FULL]);
        if (!m4) {
          throw new TypeError(`Invalid Version: ${version3}`);
        }
        this.raw = version3;
        this.major = +m4[1];
        this.minor = +m4[2];
        this.patch = +m4[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m4[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m4[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m4[5] ? m4[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof _SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new _SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
      }
      comparePre(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i4 = 0;
        do {
          const a3 = this.prerelease[i4];
          const b3 = other.prerelease[i4];
          debug("prerelease compare", i4, a3, b3);
          if (a3 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a3 === void 0) {
            return -1;
          } else if (a3 === b3) {
            continue;
          } else {
            return compareIdentifiers(a3, b3);
          }
        } while (++i4);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i4 = 0;
        do {
          const a3 = this.build[i4];
          const b3 = other.build[i4];
          debug("build compare", i4, a3, b3);
          if (a3 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a3 === void 0) {
            return -1;
          } else if (a3 === b3) {
            continue;
          } else {
            return compareIdentifiers(a3, b3);
          }
        } while (++i4);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        if (release.startsWith("pre")) {
          if (!identifier && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier) {
            const match2 = `-${identifier}`.match(this.options.loose ? re[t4.PRERELEASELOOSE] : re[t4.PRERELEASE]);
            if (!match2 || match2[1] !== identifier) {
              throw new Error(`invalid identifier: ${identifier}`);
            }
          }
        }
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i4 = this.prerelease.length;
              while (--i4 >= 0) {
                if (typeof this.prerelease[i4] === "number") {
                  this.prerelease[i4]++;
                  i4 = -2;
                }
              }
              if (i4 === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

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

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    var parse4 = require_parse2();
    var valid = (version3, options) => {
      const v6 = parse4(version3, options);
      return v6 ? v6.version : null;
    };
    module2.exports = valid;
  }
});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// src/cli/utils.ts
var import_semver, ormVersionGt, assertStudioNodeVersion, checkPackage, assertPackages, requiredApiVersion, assertOrmCoreVersion, ormCoreVersions;
var init_utils5 = __esm({
  "src/cli/utils.ts"() {
    "use strict";
    import_semver = __toESM(require_semver2());
    init_views();
    ormVersionGt = async (version3) => {
      const { npmVersion } = await import("drizzle-orm/version");
      if (!import_semver.default.gte(npmVersion, version3)) {
        return false;
      }
      return true;
    };
    assertStudioNodeVersion = () => {
      if (import_semver.default.gte(process.version, "18.0.0")) return;
      err("Drizzle Studio requires NodeJS v18 or above");
      process.exit(1);
    };
    checkPackage = async (it) => {
      try {
        await import(it);
        return true;
      } catch (e4) {
        return false;
      }
    };
    assertPackages = async (...pkgs) => {
      try {
        for (let i4 = 0; i4 < pkgs.length; i4++) {
          const it = pkgs[i4];
          await import(it);
        }
      } catch (e4) {
        err(
          `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}`
        );
        process.exit(1);
      }
    };
    requiredApiVersion = 10;
    assertOrmCoreVersion = async () => {
      try {
        const { compatibilityVersion } = await import("drizzle-orm/version");
        await import("drizzle-orm/relations");
        if (compatibilityVersion && compatibilityVersion === requiredApiVersion) {
          return;
        }
        if (!compatibilityVersion || compatibilityVersion < requiredApiVersion) {
          console.log(
            "This version of drizzle-kit requires newer version of drizzle-orm\nPlease update drizzle-orm package to the latest version \u{1F44D}"
          );
        } else {
          console.log(
            "This version of drizzle-kit is outdated\nPlease update drizzle-kit package to the latest version \u{1F44D}"
          );
        }
      } catch (e4) {
        console.log("Please install latest version of drizzle-orm");
      }
      process.exit(1);
    };
    ormCoreVersions = async () => {
      try {
        const { compatibilityVersion, npmVersion } = await import("drizzle-orm/version");
        return { compatibilityVersion, npmVersion };
      } catch (e4) {
        return {};
      }
    };
  }
});

// ../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
function dataUriToBuffer(uri) {
  if (!/^data:/i.test(uri)) {
    throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  }
  uri = uri.replace(/\r?\n/g, "");
  const firstComma = uri.indexOf(",");
  if (firstComma === -1 || firstComma <= 4) {
    throw new TypeError("malformed data: URI");
  }
  const meta = uri.substring(5, firstComma).split(";");
  let charset = "";
  let base64 = false;
  const type = meta[0] || "text/plain";
  let typeFull = type;
  for (let i4 = 1; i4 < meta.length; i4++) {
    if (meta[i4] === "base64") {
      base64 = true;
    } else if (meta[i4]) {
      typeFull += `;${meta[i4]}`;
      if (meta[i4].indexOf("charset=") === 0) {
        charset = meta[i4].substring(8);
      }
    }
  }
  if (!meta[0] && !charset.length) {
    typeFull += ";charset=US-ASCII";
    charset = "US-ASCII";
  }
  const encoding = base64 ? "base64" : "ascii";
  const data = unescape(uri.substring(firstComma + 1));
  const buffer = Buffer.from(data, encoding);
  buffer.type = type;
  buffer.typeFull = typeFull;
  buffer.charset = charset;
  return buffer;
}
var dist_default;
var init_dist = __esm({
  "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() {
    dist_default = dataUriToBuffer;
  }
});

// ../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
var require_ponyfill_es2018 = __commonJS({
  "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) {
    (function(global2, factory) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {}));
    })(exports2, function(exports3) {
      "use strict";
      function noop2() {
        return void 0;
      }
      function typeIsObject(x4) {
        return typeof x4 === "object" && x4 !== null || typeof x4 === "function";
      }
      const rethrowAssertionErrorRejection = noop2;
      function setFunctionName(fn, name) {
        try {
          Object.defineProperty(fn, "name", {
            value: name,
            configurable: true
          });
        } catch (_a3) {
        }
      }
      const originalPromise = Promise;
      const originalPromiseThen = Promise.prototype.then;
      const originalPromiseReject = Promise.reject.bind(originalPromise);
      function newPromise(executor) {
        return new originalPromise(executor);
      }
      function promiseResolvedWith(value) {
        return newPromise((resolve2) => resolve2(value));
      }
      function promiseRejectedWith(reason) {
        return originalPromiseReject(reason);
      }
      function PerformPromiseThen(promise, onFulfilled, onRejected) {
        return originalPromiseThen.call(promise, onFulfilled, onRejected);
      }
      function uponPromise(promise, onFulfilled, onRejected) {
        PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
      }
      function uponFulfillment(promise, onFulfilled) {
        uponPromise(promise, onFulfilled);
      }
      function uponRejection(promise, onRejected) {
        uponPromise(promise, void 0, onRejected);
      }
      function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
        return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
      }
      function setPromiseIsHandledToTrue(promise) {
        PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection);
      }
      let _queueMicrotask = (callback) => {
        if (typeof queueMicrotask === "function") {
          _queueMicrotask = queueMicrotask;
        } else {
          const resolvedPromise = promiseResolvedWith(void 0);
          _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb);
        }
        return _queueMicrotask(callback);
      };
      function reflectCall(F3, V, args) {
        if (typeof F3 !== "function") {
          throw new TypeError("Argument is not a function");
        }
        return Function.prototype.apply.call(F3, V, args);
      }
      function promiseCall(F3, V, args) {
        try {
          return promiseResolvedWith(reflectCall(F3, V, args));
        } catch (value) {
          return promiseRejectedWith(value);
        }
      }
      const QUEUE_MAX_ARRAY_SIZE = 16384;
      class SimpleQueue {
        constructor() {
          this._cursor = 0;
          this._size = 0;
          this._front = {
            _elements: [],
            _next: void 0
          };
          this._back = this._front;
          this._cursor = 0;
          this._size = 0;
        }
        get length() {
          return this._size;
        }
        // For exception safety, this method is structured in order:
        // 1. Read state
        // 2. Calculate required state mutations
        // 3. Perform state mutations
        push(element) {
          const oldBack = this._back;
          let newBack = oldBack;
          if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
            newBack = {
              _elements: [],
              _next: void 0
            };
          }
          oldBack._elements.push(element);
          if (newBack !== oldBack) {
            this._back = newBack;
            oldBack._next = newBack;
          }
          ++this._size;
        }
        // Like push(), shift() follows the read -> calculate -> mutate pattern for
        // exception safety.
        shift() {
          const oldFront = this._front;
          let newFront = oldFront;
          const oldCursor = this._cursor;
          let newCursor = oldCursor + 1;
          const elements = oldFront._elements;
          const element = elements[oldCursor];
          if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
            newFront = oldFront._next;
            newCursor = 0;
          }
          --this._size;
          this._cursor = newCursor;
          if (oldFront !== newFront) {
            this._front = newFront;
          }
          elements[oldCursor] = void 0;
          return element;
        }
        // The tricky thing about forEach() is that it can be called
        // re-entrantly. The queue may be mutated inside the callback. It is easy to
        // see that push() within the callback has no negative effects since the end
        // of the queue is checked for on every iteration. If shift() is called
        // repeatedly within the callback then the next iteration may return an
        // element that has been removed. In this case the callback will be called
        // with undefined values until we either "catch up" with elements that still
        // exist or reach the back of the queue.
        forEach(callback) {
          let i4 = this._cursor;
          let node = this._front;
          let elements = node._elements;
          while (i4 !== elements.length || node._next !== void 0) {
            if (i4 === elements.length) {
              node = node._next;
              elements = node._elements;
              i4 = 0;
              if (elements.length === 0) {
                break;
              }
            }
            callback(elements[i4]);
            ++i4;
          }
        }
        // Return the element that would be returned if shift() was called now,
        // without modifying the queue.
        peek() {
          const front = this._front;
          const cursor = this._cursor;
          return front._elements[cursor];
        }
      }
      const AbortSteps = Symbol("[[AbortSteps]]");
      const ErrorSteps = Symbol("[[ErrorSteps]]");
      const CancelSteps = Symbol("[[CancelSteps]]");
      const PullSteps = Symbol("[[PullSteps]]");
      const ReleaseSteps = Symbol("[[ReleaseSteps]]");
      function ReadableStreamReaderGenericInitialize(reader, stream) {
        reader._ownerReadableStream = stream;
        stream._reader = reader;
        if (stream._state === "readable") {
          defaultReaderClosedPromiseInitialize(reader);
        } else if (stream._state === "closed") {
          defaultReaderClosedPromiseInitializeAsResolved(reader);
        } else {
          defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
        }
      }
      function ReadableStreamReaderGenericCancel(reader, reason) {
        const stream = reader._ownerReadableStream;
        return ReadableStreamCancel(stream, reason);
      }
      function ReadableStreamReaderGenericRelease(reader) {
        const stream = reader._ownerReadableStream;
        if (stream._state === "readable") {
          defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
        } else {
          defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
        }
        stream._readableStreamController[ReleaseSteps]();
        stream._reader = void 0;
        reader._ownerReadableStream = void 0;
      }
      function readerLockException(name) {
        return new TypeError("Cannot " + name + " a stream using a released reader");
      }
      function defaultReaderClosedPromiseInitialize(reader) {
        reader._closedPromise = newPromise((resolve2, reject) => {
          reader._closedPromise_resolve = resolve2;
          reader._closedPromise_reject = reject;
        });
      }
      function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseReject(reader, reason);
      }
      function defaultReaderClosedPromiseInitializeAsResolved(reader) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseResolve(reader);
      }
      function defaultReaderClosedPromiseReject(reader, reason) {
        if (reader._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(reader._closedPromise);
        reader._closedPromise_reject(reason);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      function defaultReaderClosedPromiseResetToRejected(reader, reason) {
        defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
      }
      function defaultReaderClosedPromiseResolve(reader) {
        if (reader._closedPromise_resolve === void 0) {
          return;
        }
        reader._closedPromise_resolve(void 0);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      const NumberIsFinite = Number.isFinite || function(x4) {
        return typeof x4 === "number" && isFinite(x4);
      };
      const MathTrunc = Math.trunc || function(v6) {
        return v6 < 0 ? Math.ceil(v6) : Math.floor(v6);
      };
      function isDictionary(x4) {
        return typeof x4 === "object" || typeof x4 === "function";
      }
      function assertDictionary(obj, context) {
        if (obj !== void 0 && !isDictionary(obj)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertFunction(x4, context) {
        if (typeof x4 !== "function") {
          throw new TypeError(`${context} is not a function.`);
        }
      }
      function isObject(x4) {
        return typeof x4 === "object" && x4 !== null || typeof x4 === "function";
      }
      function assertObject(x4, context) {
        if (!isObject(x4)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertRequiredArgument(x4, position, context) {
        if (x4 === void 0) {
          throw new TypeError(`Parameter ${position} is required in '${context}'.`);
        }
      }
      function assertRequiredField(x4, field, context) {
        if (x4 === void 0) {
          throw new TypeError(`${field} is required in '${context}'.`);
        }
      }
      function convertUnrestrictedDouble(value) {
        return Number(value);
      }
      function censorNegativeZero(x4) {
        return x4 === 0 ? 0 : x4;
      }
      function integerPart(x4) {
        return censorNegativeZero(MathTrunc(x4));
      }
      function convertUnsignedLongLongWithEnforceRange(value, context) {
        const lowerBound = 0;
        const upperBound = Number.MAX_SAFE_INTEGER;
        let x4 = Number(value);
        x4 = censorNegativeZero(x4);
        if (!NumberIsFinite(x4)) {
          throw new TypeError(`${context} is not a finite number`);
        }
        x4 = integerPart(x4);
        if (x4 < lowerBound || x4 > upperBound) {
          throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
        }
        if (!NumberIsFinite(x4) || x4 === 0) {
          return 0;
        }
        return x4;
      }
      function assertReadableStream(x4, context) {
        if (!IsReadableStream(x4)) {
          throw new TypeError(`${context} is not a ReadableStream.`);
        }
      }
      function AcquireReadableStreamDefaultReader(stream) {
        return new ReadableStreamDefaultReader(stream);
      }
      function ReadableStreamAddReadRequest(stream, readRequest) {
        stream._reader._readRequests.push(readRequest);
      }
      function ReadableStreamFulfillReadRequest(stream, chunk, done) {
        const reader = stream._reader;
        const readRequest = reader._readRequests.shift();
        if (done) {
          readRequest._closeSteps();
        } else {
          readRequest._chunkSteps(chunk);
        }
      }
      function ReadableStreamGetNumReadRequests(stream) {
        return stream._reader._readRequests.length;
      }
      function ReadableStreamHasDefaultReader(stream) {
        const reader = stream._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamDefaultReader(reader)) {
          return false;
        }
        return true;
      }
      class ReadableStreamDefaultReader {
        constructor(stream) {
          assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader");
          assertReadableStream(stream, "First parameter");
          if (IsReadableStreamLocked(stream)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          ReadableStreamReaderGenericInitialize(this, stream);
          this._readRequests = new SimpleQueue();
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed,
         * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
         */
        cancel(reason = void 0) {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("cancel"));
          }
          return ReadableStreamReaderGenericCancel(this, reason);
        }
        /**
         * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
         *
         * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
         */
        read() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("read"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: () => resolvePromise({ value: void 0, done: true }),
            _errorSteps: (e4) => rejectPromise(e4)
          };
          ReadableStreamDefaultReaderRead(this, readRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamDefaultReader(this)) {
            throw defaultReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamDefaultReaderRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamDefaultReader.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel");
      setFunctionName(ReadableStreamDefaultReader.prototype.read, "read");
      setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {
          value: "ReadableStreamDefaultReader",
          configurable: true
        });
      }
      function IsReadableStreamDefaultReader(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_readRequests")) {
          return false;
        }
        return x4 instanceof ReadableStreamDefaultReader;
      }
      function ReadableStreamDefaultReaderRead(reader, readRequest) {
        const stream = reader._ownerReadableStream;
        stream._disturbed = true;
        if (stream._state === "closed") {
          readRequest._closeSteps();
        } else if (stream._state === "errored") {
          readRequest._errorSteps(stream._storedError);
        } else {
          stream._readableStreamController[PullSteps](readRequest);
        }
      }
      function ReadableStreamDefaultReaderRelease(reader) {
        ReadableStreamReaderGenericRelease(reader);
        const e4 = new TypeError("Reader was released");
        ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
      }
      function ReadableStreamDefaultReaderErrorReadRequests(reader, e4) {
        const readRequests = reader._readRequests;
        reader._readRequests = new SimpleQueue();
        readRequests.forEach((readRequest) => {
          readRequest._errorSteps(e4);
        });
      }
      function defaultReaderBrandCheckException(name) {
        return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
      }
      const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
      }).prototype);
      class ReadableStreamAsyncIteratorImpl {
        constructor(reader, preventCancel) {
          this._ongoingPromise = void 0;
          this._isFinished = false;
          this._reader = reader;
          this._preventCancel = preventCancel;
        }
        next() {
          const nextSteps = () => this._nextSteps();
          this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps();
          return this._ongoingPromise;
        }
        return(value) {
          const returnSteps = () => this._returnSteps(value);
          return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps();
        }
        _nextSteps() {
          if (this._isFinished) {
            return Promise.resolve({ value: void 0, done: true });
          }
          const reader = this._reader;
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: (chunk) => {
              this._ongoingPromise = void 0;
              _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
            },
            _closeSteps: () => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              resolvePromise({ value: void 0, done: true });
            },
            _errorSteps: (reason) => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              rejectPromise(reason);
            }
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promise;
        }
        _returnSteps(value) {
          if (this._isFinished) {
            return Promise.resolve({ value, done: true });
          }
          this._isFinished = true;
          const reader = this._reader;
          if (!this._preventCancel) {
            const result = ReadableStreamReaderGenericCancel(reader, value);
            ReadableStreamReaderGenericRelease(reader);
            return transformPromiseWith(result, () => ({ value, done: true }));
          }
          ReadableStreamReaderGenericRelease(reader);
          return promiseResolvedWith({ value, done: true });
        }
      }
      const ReadableStreamAsyncIteratorPrototype = {
        next() {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
          }
          return this._asyncIteratorImpl.next();
        },
        return(value) {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
          }
          return this._asyncIteratorImpl.return(value);
        }
      };
      Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
      function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
        const reader = AcquireReadableStreamDefaultReader(stream);
        const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
        const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
        iterator._asyncIteratorImpl = impl;
        return iterator;
      }
      function IsReadableStreamAsyncIterator(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_asyncIteratorImpl")) {
          return false;
        }
        try {
          return x4._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
        } catch (_a3) {
          return false;
        }
      }
      function streamAsyncIteratorBrandCheckException(name) {
        return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
      }
      const NumberIsNaN = Number.isNaN || function(x4) {
        return x4 !== x4;
      };
      var _a2, _b, _c;
      function CreateArrayFromList(elements) {
        return elements.slice();
      }
      function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n3) {
        new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n3), destOffset);
      }
      let TransferArrayBuffer = (O) => {
        if (typeof O.transfer === "function") {
          TransferArrayBuffer = (buffer) => buffer.transfer();
        } else if (typeof structuredClone === "function") {
          TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] });
        } else {
          TransferArrayBuffer = (buffer) => buffer;
        }
        return TransferArrayBuffer(O);
      };
      let IsDetachedBuffer = (O) => {
        if (typeof O.detached === "boolean") {
          IsDetachedBuffer = (buffer) => buffer.detached;
        } else {
          IsDetachedBuffer = (buffer) => buffer.byteLength === 0;
        }
        return IsDetachedBuffer(O);
      };
      function ArrayBufferSlice(buffer, begin, end) {
        if (buffer.slice) {
          return buffer.slice(begin, end);
        }
        const length = end - begin;
        const slice = new ArrayBuffer(length);
        CopyDataBlockBytes(slice, 0, buffer, begin, length);
        return slice;
      }
      function GetMethod(receiver, prop) {
        const func = receiver[prop];
        if (func === void 0 || func === null) {
          return void 0;
        }
        if (typeof func !== "function") {
          throw new TypeError(`${String(prop)} is not a function`);
        }
        return func;
      }
      function CreateAsyncFromSyncIterator(syncIteratorRecord) {
        const syncIterable = {
          [Symbol.iterator]: () => syncIteratorRecord.iterator
        };
        const asyncIterator = async function* () {
          return yield* syncIterable;
        }();
        const nextMethod = asyncIterator.next;
        return { iterator: asyncIterator, nextMethod, done: false };
      }
      const SymbolAsyncIterator = (_c = (_a2 = Symbol.asyncIterator) !== null && _a2 !== void 0 ? _a2 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator";
      function GetIterator(obj, hint = "sync", method) {
        if (method === void 0) {
          if (hint === "async") {
            method = GetMethod(obj, SymbolAsyncIterator);
            if (method === void 0) {
              const syncMethod = GetMethod(obj, Symbol.iterator);
              const syncIteratorRecord = GetIterator(obj, "sync", syncMethod);
              return CreateAsyncFromSyncIterator(syncIteratorRecord);
            }
          } else {
            method = GetMethod(obj, Symbol.iterator);
          }
        }
        if (method === void 0) {
          throw new TypeError("The object is not iterable");
        }
        const iterator = reflectCall(method, obj, []);
        if (!typeIsObject(iterator)) {
          throw new TypeError("The iterator method must return an object");
        }
        const nextMethod = iterator.next;
        return { iterator, nextMethod, done: false };
      }
      function IteratorNext(iteratorRecord) {
        const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
        if (!typeIsObject(result)) {
          throw new TypeError("The iterator.next() method must return an object");
        }
        return result;
      }
      function IteratorComplete(iterResult) {
        return Boolean(iterResult.done);
      }
      function IteratorValue(iterResult) {
        return iterResult.value;
      }
      function IsNonNegativeNumber(v6) {
        if (typeof v6 !== "number") {
          return false;
        }
        if (NumberIsNaN(v6)) {
          return false;
        }
        if (v6 < 0) {
          return false;
        }
        return true;
      }
      function CloneAsUint8Array(O) {
        const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
        return new Uint8Array(buffer);
      }
      function DequeueValue(container) {
        const pair = container._queue.shift();
        container._queueTotalSize -= pair.size;
        if (container._queueTotalSize < 0) {
          container._queueTotalSize = 0;
        }
        return pair.value;
      }
      function EnqueueValueWithSize(container, value, size) {
        if (!IsNonNegativeNumber(size) || size === Infinity) {
          throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
        }
        container._queue.push({ value, size });
        container._queueTotalSize += size;
      }
      function PeekQueueValue(container) {
        const pair = container._queue.peek();
        return pair.value;
      }
      function ResetQueue(container) {
        container._queue = new SimpleQueue();
        container._queueTotalSize = 0;
      }
      function isDataViewConstructor(ctor) {
        return ctor === DataView;
      }
      function isDataView(view5) {
        return isDataViewConstructor(view5.constructor);
      }
      function arrayBufferViewElementSize(ctor) {
        if (isDataViewConstructor(ctor)) {
          return 1;
        }
        return ctor.BYTES_PER_ELEMENT;
      }
      class ReadableStreamBYOBRequest {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
         */
        get view() {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("view");
          }
          return this._view;
        }
        respond(bytesWritten) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respond");
          }
          assertRequiredArgument(bytesWritten, 1, "respond");
          bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter");
          if (this._associatedReadableByteStreamController === void 0) {
            throw new TypeError("This BYOB request has been invalidated");
          }
          if (IsDetachedBuffer(this._view.buffer)) {
            throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
          }
          ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
        }
        respondWithNewView(view5) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respondWithNewView");
          }
          assertRequiredArgument(view5, 1, "respondWithNewView");
          if (!ArrayBuffer.isView(view5)) {
            throw new TypeError("You can only respond with array buffer views");
          }
          if (this._associatedReadableByteStreamController === void 0) {
            throw new TypeError("This BYOB request has been invalidated");
          }
          if (IsDetachedBuffer(view5.buffer)) {
            throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
          }
          ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5);
        }
      }
      Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
        respond: { enumerable: true },
        respondWithNewView: { enumerable: true },
        view: { enumerable: true }
      });
      setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond");
      setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {
          value: "ReadableStreamBYOBRequest",
          configurable: true
        });
      }
      class ReadableByteStreamController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the current BYOB pull request, or `null` if there isn't one.
         */
        get byobRequest() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("byobRequest");
          }
          return ReadableByteStreamControllerGetBYOBRequest(this);
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("desiredSize");
          }
          return ReadableByteStreamControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("close");
          }
          if (this._closeRequested) {
            throw new TypeError("The stream has already been closed; do not close it again!");
          }
          const state2 = this._controlledReadableByteStream._state;
          if (state2 !== "readable") {
            throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be closed`);
          }
          ReadableByteStreamControllerClose(this);
        }
        enqueue(chunk) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("enqueue");
          }
          assertRequiredArgument(chunk, 1, "enqueue");
          if (!ArrayBuffer.isView(chunk)) {
            throw new TypeError("chunk must be an array buffer view");
          }
          if (chunk.byteLength === 0) {
            throw new TypeError("chunk must have non-zero byteLength");
          }
          if (chunk.buffer.byteLength === 0) {
            throw new TypeError(`chunk's buffer must have non-zero byteLength`);
          }
          if (this._closeRequested) {
            throw new TypeError("stream is closed or draining");
          }
          const state2 = this._controlledReadableByteStream._state;
          if (state2 !== "readable") {
            throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be enqueued to`);
          }
          ReadableByteStreamControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e4 = void 0) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("error");
          }
          ReadableByteStreamControllerError(this, e4);
        }
        /** @internal */
        [CancelSteps](reason) {
          ReadableByteStreamControllerClearPendingPullIntos(this);
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableByteStreamControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream = this._controlledReadableByteStream;
          if (this._queueTotalSize > 0) {
            ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
            return;
          }
          const autoAllocateChunkSize = this._autoAllocateChunkSize;
          if (autoAllocateChunkSize !== void 0) {
            let buffer;
            try {
              buffer = new ArrayBuffer(autoAllocateChunkSize);
            } catch (bufferE) {
              readRequest._errorSteps(bufferE);
              return;
            }
            const pullIntoDescriptor = {
              buffer,
              bufferByteLength: autoAllocateChunkSize,
              byteOffset: 0,
              byteLength: autoAllocateChunkSize,
              bytesFilled: 0,
              minimumFill: 1,
              elementSize: 1,
              viewConstructor: Uint8Array,
              readerType: "default"
            };
            this._pendingPullIntos.push(pullIntoDescriptor);
          }
          ReadableStreamAddReadRequest(stream, readRequest);
          ReadableByteStreamControllerCallPullIfNeeded(this);
        }
        /** @internal */
        [ReleaseSteps]() {
          if (this._pendingPullIntos.length > 0) {
            const firstPullInto = this._pendingPullIntos.peek();
            firstPullInto.readerType = "none";
            this._pendingPullIntos = new SimpleQueue();
            this._pendingPullIntos.push(firstPullInto);
          }
        }
      }
      Object.defineProperties(ReadableByteStreamController.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        byobRequest: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(ReadableByteStreamController.prototype.close, "close");
      setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue");
      setFunctionName(ReadableByteStreamController.prototype.error, "error");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {
          value: "ReadableByteStreamController",
          configurable: true
        });
      }
      function IsReadableByteStreamController(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableByteStream")) {
          return false;
        }
        return x4 instanceof ReadableByteStreamController;
      }
      function IsReadableStreamBYOBRequest(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_associatedReadableByteStreamController")) {
          return false;
        }
        return x4 instanceof ReadableStreamBYOBRequest;
      }
      function ReadableByteStreamControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableByteStreamControllerCallPullIfNeeded(controller);
          }
          return null;
        }, (e4) => {
          ReadableByteStreamControllerError(controller, e4);
          return null;
        });
      }
      function ReadableByteStreamControllerClearPendingPullIntos(controller) {
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        controller._pendingPullIntos = new SimpleQueue();
      }
      function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
        let done = false;
        if (stream._state === "closed") {
          done = true;
        }
        const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
        if (pullIntoDescriptor.readerType === "default") {
          ReadableStreamFulfillReadRequest(stream, filledView, done);
        } else {
          ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
        }
      }
      function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
        const bytesFilled = pullIntoDescriptor.bytesFilled;
        const elementSize = pullIntoDescriptor.elementSize;
        return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
      }
      function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
        controller._queue.push({ buffer, byteOffset, byteLength });
        controller._queueTotalSize += byteLength;
      }
      function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
        let clonedChunk;
        try {
          clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
        } catch (cloneE) {
          ReadableByteStreamControllerError(controller, cloneE);
          throw cloneE;
        }
        ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
      }
      function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
        if (firstDescriptor.bytesFilled > 0) {
          ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
        }
        ReadableByteStreamControllerShiftPendingPullInto(controller);
      }
      function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
        const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
        const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
        let totalBytesToCopyRemaining = maxBytesToCopy;
        let ready = false;
        const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
        const maxAlignedBytes = maxBytesFilled - remainderBytes;
        if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
          totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
          ready = true;
        }
        const queue = controller._queue;
        while (totalBytesToCopyRemaining > 0) {
          const headOfQueue = queue.peek();
          const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
          const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
          CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
          if (headOfQueue.byteLength === bytesToCopy) {
            queue.shift();
          } else {
            headOfQueue.byteOffset += bytesToCopy;
            headOfQueue.byteLength -= bytesToCopy;
          }
          controller._queueTotalSize -= bytesToCopy;
          ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
          totalBytesToCopyRemaining -= bytesToCopy;
        }
        return ready;
      }
      function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
        pullIntoDescriptor.bytesFilled += size;
      }
      function ReadableByteStreamControllerHandleQueueDrain(controller) {
        if (controller._queueTotalSize === 0 && controller._closeRequested) {
          ReadableByteStreamControllerClearAlgorithms(controller);
          ReadableStreamClose(controller._controlledReadableByteStream);
        } else {
          ReadableByteStreamControllerCallPullIfNeeded(controller);
        }
      }
      function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
        if (controller._byobRequest === null) {
          return;
        }
        controller._byobRequest._associatedReadableByteStreamController = void 0;
        controller._byobRequest._view = null;
        controller._byobRequest = null;
      }
      function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
        while (controller._pendingPullIntos.length > 0) {
          if (controller._queueTotalSize === 0) {
            return;
          }
          const pullIntoDescriptor = controller._pendingPullIntos.peek();
          if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
            ReadableByteStreamControllerShiftPendingPullInto(controller);
            ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
          }
        }
      }
      function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
        const reader = controller._controlledReadableByteStream._reader;
        while (reader._readRequests.length > 0) {
          if (controller._queueTotalSize === 0) {
            return;
          }
          const readRequest = reader._readRequests.shift();
          ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
        }
      }
      function ReadableByteStreamControllerPullInto(controller, view5, min, readIntoRequest) {
        const stream = controller._controlledReadableByteStream;
        const ctor = view5.constructor;
        const elementSize = arrayBufferViewElementSize(ctor);
        const { byteOffset, byteLength } = view5;
        const minimumFill = min * elementSize;
        let buffer;
        try {
          buffer = TransferArrayBuffer(view5.buffer);
        } catch (e4) {
          readIntoRequest._errorSteps(e4);
          return;
        }
        const pullIntoDescriptor = {
          buffer,
          bufferByteLength: buffer.byteLength,
          byteOffset,
          byteLength,
          bytesFilled: 0,
          minimumFill,
          elementSize,
          viewConstructor: ctor,
          readerType: "byob"
        };
        if (controller._pendingPullIntos.length > 0) {
          controller._pendingPullIntos.push(pullIntoDescriptor);
          ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
          return;
        }
        if (stream._state === "closed") {
          const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
          readIntoRequest._closeSteps(emptyView);
          return;
        }
        if (controller._queueTotalSize > 0) {
          if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
            const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
            ReadableByteStreamControllerHandleQueueDrain(controller);
            readIntoRequest._chunkSteps(filledView);
            return;
          }
          if (controller._closeRequested) {
            const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e4);
            readIntoRequest._errorSteps(e4);
            return;
          }
        }
        controller._pendingPullIntos.push(pullIntoDescriptor);
        ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
        if (firstDescriptor.readerType === "none") {
          ReadableByteStreamControllerShiftPendingPullInto(controller);
        }
        const stream = controller._controlledReadableByteStream;
        if (ReadableStreamHasBYOBReader(stream)) {
          while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
            const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
            ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
          }
        }
      }
      function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
        ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
        if (pullIntoDescriptor.readerType === "none") {
          ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
          return;
        }
        if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
          return;
        }
        ReadableByteStreamControllerShiftPendingPullInto(controller);
        const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
        if (remainderSize > 0) {
          const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
          ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
        }
        pullIntoDescriptor.bytesFilled -= remainderSize;
        ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
        ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
      }
      function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "closed") {
          ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
        } else {
          ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      function ReadableByteStreamControllerShiftPendingPullInto(controller) {
        const descriptor = controller._pendingPullIntos.shift();
        return descriptor;
      }
      function ReadableByteStreamControllerShouldCallPull(controller) {
        const stream = controller._controlledReadableByteStream;
        if (stream._state !== "readable") {
          return false;
        }
        if (controller._closeRequested) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
          return true;
        }
        if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
          return true;
        }
        const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
        if (desiredSize > 0) {
          return true;
        }
        return false;
      }
      function ReadableByteStreamControllerClearAlgorithms(controller) {
        controller._pullAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
      }
      function ReadableByteStreamControllerClose(controller) {
        const stream = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream._state !== "readable") {
          return;
        }
        if (controller._queueTotalSize > 0) {
          controller._closeRequested = true;
          return;
        }
        if (controller._pendingPullIntos.length > 0) {
          const firstPendingPullInto = controller._pendingPullIntos.peek();
          if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
            const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e4);
            throw e4;
          }
        }
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamClose(stream);
      }
      function ReadableByteStreamControllerEnqueue(controller, chunk) {
        const stream = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream._state !== "readable") {
          return;
        }
        const { buffer, byteOffset, byteLength } = chunk;
        if (IsDetachedBuffer(buffer)) {
          throw new TypeError("chunk's buffer is detached and so cannot be enqueued");
        }
        const transferredBuffer = TransferArrayBuffer(buffer);
        if (controller._pendingPullIntos.length > 0) {
          const firstPendingPullInto = controller._pendingPullIntos.peek();
          if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
            throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");
          }
          ReadableByteStreamControllerInvalidateBYOBRequest(controller);
          firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
          if (firstPendingPullInto.readerType === "none") {
            ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
          }
        }
        if (ReadableStreamHasDefaultReader(stream)) {
          ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
          if (ReadableStreamGetNumReadRequests(stream) === 0) {
            ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          } else {
            if (controller._pendingPullIntos.length > 0) {
              ReadableByteStreamControllerShiftPendingPullInto(controller);
            }
            const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
            ReadableStreamFulfillReadRequest(stream, transferredView, false);
          }
        } else if (ReadableStreamHasBYOBReader(stream)) {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
        } else {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      function ReadableByteStreamControllerError(controller, e4) {
        const stream = controller._controlledReadableByteStream;
        if (stream._state !== "readable") {
          return;
        }
        ReadableByteStreamControllerClearPendingPullIntos(controller);
        ResetQueue(controller);
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e4);
      }
      function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
        const entry = controller._queue.shift();
        controller._queueTotalSize -= entry.byteLength;
        ReadableByteStreamControllerHandleQueueDrain(controller);
        const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
        readRequest._chunkSteps(view5);
      }
      function ReadableByteStreamControllerGetBYOBRequest(controller) {
        if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
          const firstDescriptor = controller._pendingPullIntos.peek();
          const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
          const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
          SetUpReadableStreamBYOBRequest(byobRequest, controller, view5);
          controller._byobRequest = byobRequest;
        }
        return controller._byobRequest;
      }
      function ReadableByteStreamControllerGetDesiredSize(controller) {
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "errored") {
          return null;
        }
        if (state2 === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableByteStreamControllerRespond(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "closed") {
          if (bytesWritten !== 0) {
            throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
          }
        } else {
          if (bytesWritten === 0) {
            throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
          }
          if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
            throw new RangeError("bytesWritten out of range");
          }
        }
        firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
        ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
      }
      function ReadableByteStreamControllerRespondWithNewView(controller, view5) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "closed") {
          if (view5.byteLength !== 0) {
            throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
          }
        } else {
          if (view5.byteLength === 0) {
            throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
          }
        }
        if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view5.byteOffset) {
          throw new RangeError("The region specified by view does not match byobRequest");
        }
        if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) {
          throw new RangeError("The buffer of view has different capacity than byobRequest");
        }
        if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) {
          throw new RangeError("The region specified by view is larger than byobRequest");
        }
        const viewByteLength = view5.byteLength;
        firstDescriptor.buffer = TransferArrayBuffer(view5.buffer);
        ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
      }
      function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
        controller._controlledReadableByteStream = stream;
        controller._pullAgain = false;
        controller._pulling = false;
        controller._byobRequest = null;
        controller._queue = controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._closeRequested = false;
        controller._started = false;
        controller._strategyHWM = highWaterMark;
        controller._pullAlgorithm = pullAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        controller._autoAllocateChunkSize = autoAllocateChunkSize;
        controller._pendingPullIntos = new SimpleQueue();
        stream._readableStreamController = controller;
        const startResult = startAlgorithm();
        uponPromise(promiseResolvedWith(startResult), () => {
          controller._started = true;
          ReadableByteStreamControllerCallPullIfNeeded(controller);
          return null;
        }, (r4) => {
          ReadableByteStreamControllerError(controller, r4);
          return null;
        });
      }
      function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
        const controller = Object.create(ReadableByteStreamController.prototype);
        let startAlgorithm;
        let pullAlgorithm;
        let cancelAlgorithm;
        if (underlyingByteSource.start !== void 0) {
          startAlgorithm = () => underlyingByteSource.start(controller);
        } else {
          startAlgorithm = () => void 0;
        }
        if (underlyingByteSource.pull !== void 0) {
          pullAlgorithm = () => underlyingByteSource.pull(controller);
        } else {
          pullAlgorithm = () => promiseResolvedWith(void 0);
        }
        if (underlyingByteSource.cancel !== void 0) {
          cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason);
        } else {
          cancelAlgorithm = () => promiseResolvedWith(void 0);
        }
        const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
        if (autoAllocateChunkSize === 0) {
          throw new TypeError("autoAllocateChunkSize must be greater than 0");
        }
        SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
      }
      function SetUpReadableStreamBYOBRequest(request, controller, view5) {
        request._associatedReadableByteStreamController = controller;
        request._view = view5;
      }
      function byobRequestBrandCheckException(name) {
        return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
      }
      function byteStreamControllerBrandCheckException(name) {
        return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
      }
      function convertReaderOptions(options, context) {
        assertDictionary(options, context);
        const mode = options === null || options === void 0 ? void 0 : options.mode;
        return {
          mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
        };
      }
      function convertReadableStreamReaderMode(mode, context) {
        mode = `${mode}`;
        if (mode !== "byob") {
          throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
        }
        return mode;
      }
      function convertByobReadOptions(options, context) {
        var _a3;
        assertDictionary(options, context);
        const min = (_a3 = options === null || options === void 0 ? void 0 : options.min) !== null && _a3 !== void 0 ? _a3 : 1;
        return {
          min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
        };
      }
      function AcquireReadableStreamBYOBReader(stream) {
        return new ReadableStreamBYOBReader(stream);
      }
      function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
        stream._reader._readIntoRequests.push(readIntoRequest);
      }
      function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
        const reader = stream._reader;
        const readIntoRequest = reader._readIntoRequests.shift();
        if (done) {
          readIntoRequest._closeSteps(chunk);
        } else {
          readIntoRequest._chunkSteps(chunk);
        }
      }
      function ReadableStreamGetNumReadIntoRequests(stream) {
        return stream._reader._readIntoRequests.length;
      }
      function ReadableStreamHasBYOBReader(stream) {
        const reader = stream._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamBYOBReader(reader)) {
          return false;
        }
        return true;
      }
      class ReadableStreamBYOBReader {
        constructor(stream) {
          assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader");
          assertReadableStream(stream, "First parameter");
          if (IsReadableStreamLocked(stream)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          if (!IsReadableByteStreamController(stream._readableStreamController)) {
            throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
          }
          ReadableStreamReaderGenericInitialize(this, stream);
          this._readIntoRequests = new SimpleQueue();
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
         * the reader's lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
         */
        cancel(reason = void 0) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("cancel"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("cancel"));
          }
          return ReadableStreamReaderGenericCancel(this, reason);
        }
        read(view5, rawOptions = {}) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("read"));
          }
          if (!ArrayBuffer.isView(view5)) {
            return promiseRejectedWith(new TypeError("view must be an array buffer view"));
          }
          if (view5.byteLength === 0) {
            return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
          }
          if (view5.buffer.byteLength === 0) {
            return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
          }
          if (IsDetachedBuffer(view5.buffer)) {
            return promiseRejectedWith(new TypeError("view's buffer has been detached"));
          }
          let options;
          try {
            options = convertByobReadOptions(rawOptions, "options");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const min = options.min;
          if (min === 0) {
            return promiseRejectedWith(new TypeError("options.min must be greater than 0"));
          }
          if (!isDataView(view5)) {
            if (min > view5.length) {
              return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length"));
            }
          } else if (min > view5.byteLength) {
            return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readIntoRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
            _errorSteps: (e4) => rejectPromise(e4)
          };
          ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamBYOBReader(this)) {
            throw byobReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamBYOBReaderRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamBYOBReader.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel");
      setFunctionName(ReadableStreamBYOBReader.prototype.read, "read");
      setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {
          value: "ReadableStreamBYOBReader",
          configurable: true
        });
      }
      function IsReadableStreamBYOBReader(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_readIntoRequests")) {
          return false;
        }
        return x4 instanceof ReadableStreamBYOBReader;
      }
      function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) {
        const stream = reader._ownerReadableStream;
        stream._disturbed = true;
        if (stream._state === "errored") {
          readIntoRequest._errorSteps(stream._storedError);
        } else {
          ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest);
        }
      }
      function ReadableStreamBYOBReaderRelease(reader) {
        ReadableStreamReaderGenericRelease(reader);
        const e4 = new TypeError("Reader was released");
        ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
      }
      function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4) {
        const readIntoRequests = reader._readIntoRequests;
        reader._readIntoRequests = new SimpleQueue();
        readIntoRequests.forEach((readIntoRequest) => {
          readIntoRequest._errorSteps(e4);
        });
      }
      function byobReaderBrandCheckException(name) {
        return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
      }
      function ExtractHighWaterMark(strategy, defaultHWM) {
        const { highWaterMark } = strategy;
        if (highWaterMark === void 0) {
          return defaultHWM;
        }
        if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
          throw new RangeError("Invalid highWaterMark");
        }
        return highWaterMark;
      }
      function ExtractSizeAlgorithm(strategy) {
        const { size } = strategy;
        if (!size) {
          return () => 1;
        }
        return size;
      }
      function convertQueuingStrategy(init2, context) {
        assertDictionary(init2, context);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
        const size = init2 === null || init2 === void 0 ? void 0 : init2.size;
        return {
          highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
          size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`)
        };
      }
      function convertQueuingStrategySize(fn, context) {
        assertFunction(fn, context);
        return (chunk) => convertUnrestrictedDouble(fn(chunk));
      }
      function convertUnderlyingSink(original, context) {
        assertDictionary(original, context);
        const abort = original === null || original === void 0 ? void 0 : original.abort;
        const close = original === null || original === void 0 ? void 0 : original.close;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const type = original === null || original === void 0 ? void 0 : original.type;
        const write = original === null || original === void 0 ? void 0 : original.write;
        return {
          abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
          close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
          start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
          write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
          type
        };
      }
      function convertUnderlyingSinkAbortCallback(fn, original, context) {
        assertFunction(fn, context);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      function convertUnderlyingSinkCloseCallback(fn, original, context) {
        assertFunction(fn, context);
        return () => promiseCall(fn, original, []);
      }
      function convertUnderlyingSinkStartCallback(fn, original, context) {
        assertFunction(fn, context);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      function convertUnderlyingSinkWriteCallback(fn, original, context) {
        assertFunction(fn, context);
        return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
      }
      function assertWritableStream(x4, context) {
        if (!IsWritableStream(x4)) {
          throw new TypeError(`${context} is not a WritableStream.`);
        }
      }
      function isAbortSignal2(value) {
        if (typeof value !== "object" || value === null) {
          return false;
        }
        try {
          return typeof value.aborted === "boolean";
        } catch (_a3) {
          return false;
        }
      }
      const supportsAbortController = typeof AbortController === "function";
      function createAbortController() {
        if (supportsAbortController) {
          return new AbortController();
        }
        return void 0;
      }
      class WritableStream {
        constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
          if (rawUnderlyingSink === void 0) {
            rawUnderlyingSink = null;
          } else {
            assertObject(rawUnderlyingSink, "First parameter");
          }
          const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
          const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter");
          InitializeWritableStream(this);
          const type = underlyingSink.type;
          if (type !== void 0) {
            throw new RangeError("Invalid type is specified");
          }
          const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
          const highWaterMark = ExtractHighWaterMark(strategy, 1);
          SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
        }
        /**
         * Returns whether or not the writable stream is locked to a writer.
         */
        get locked() {
          if (!IsWritableStream(this)) {
            throw streamBrandCheckException$2("locked");
          }
          return IsWritableStreamLocked(this);
        }
        /**
         * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
         * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
         * mechanism of the underlying sink.
         *
         * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
         * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
         * the stream) if the stream is currently locked.
         */
        abort(reason = void 0) {
          if (!IsWritableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$2("abort"));
          }
          if (IsWritableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer"));
          }
          return WritableStreamAbort(this, reason);
        }
        /**
         * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
         * close behavior. During this time any further attempts to write will fail (without erroring the stream).
         *
         * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
         * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
         * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
         */
        close() {
          if (!IsWritableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$2("close"));
          }
          if (IsWritableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer"));
          }
          if (WritableStreamCloseQueuedOrInFlight(this)) {
            return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
          }
          return WritableStreamClose(this);
        }
        /**
         * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
         * is locked, no other writer can be acquired until this one is released.
         *
         * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
         * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
         * the same time, which would cause the resulting written data to be unpredictable and probably useless.
         */
        getWriter() {
          if (!IsWritableStream(this)) {
            throw streamBrandCheckException$2("getWriter");
          }
          return AcquireWritableStreamDefaultWriter(this);
        }
      }
      Object.defineProperties(WritableStream.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        getWriter: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(WritableStream.prototype.abort, "abort");
      setFunctionName(WritableStream.prototype.close, "close");
      setFunctionName(WritableStream.prototype.getWriter, "getWriter");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {
          value: "WritableStream",
          configurable: true
        });
      }
      function AcquireWritableStreamDefaultWriter(stream) {
        return new WritableStreamDefaultWriter(stream);
      }
      function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream = Object.create(WritableStream.prototype);
        InitializeWritableStream(stream);
        const controller = Object.create(WritableStreamDefaultController.prototype);
        SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
        return stream;
      }
      function InitializeWritableStream(stream) {
        stream._state = "writable";
        stream._storedError = void 0;
        stream._writer = void 0;
        stream._writableStreamController = void 0;
        stream._writeRequests = new SimpleQueue();
        stream._inFlightWriteRequest = void 0;
        stream._closeRequest = void 0;
        stream._inFlightCloseRequest = void 0;
        stream._pendingAbortRequest = void 0;
        stream._backpressure = false;
      }
      function IsWritableStream(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_writableStreamController")) {
          return false;
        }
        return x4 instanceof WritableStream;
      }
      function IsWritableStreamLocked(stream) {
        if (stream._writer === void 0) {
          return false;
        }
        return true;
      }
      function WritableStreamAbort(stream, reason) {
        var _a3;
        if (stream._state === "closed" || stream._state === "errored") {
          return promiseResolvedWith(void 0);
        }
        stream._writableStreamController._abortReason = reason;
        (_a3 = stream._writableStreamController._abortController) === null || _a3 === void 0 ? void 0 : _a3.abort(reason);
        const state2 = stream._state;
        if (state2 === "closed" || state2 === "errored") {
          return promiseResolvedWith(void 0);
        }
        if (stream._pendingAbortRequest !== void 0) {
          return stream._pendingAbortRequest._promise;
        }
        let wasAlreadyErroring = false;
        if (state2 === "erroring") {
          wasAlreadyErroring = true;
          reason = void 0;
        }
        const promise = newPromise((resolve2, reject) => {
          stream._pendingAbortRequest = {
            _promise: void 0,
            _resolve: resolve2,
            _reject: reject,
            _reason: reason,
            _wasAlreadyErroring: wasAlreadyErroring
          };
        });
        stream._pendingAbortRequest._promise = promise;
        if (!wasAlreadyErroring) {
          WritableStreamStartErroring(stream, reason);
        }
        return promise;
      }
      function WritableStreamClose(stream) {
        const state2 = stream._state;
        if (state2 === "closed" || state2 === "errored") {
          return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`));
        }
        const promise = newPromise((resolve2, reject) => {
          const closeRequest = {
            _resolve: resolve2,
            _reject: reject
          };
          stream._closeRequest = closeRequest;
        });
        const writer = stream._writer;
        if (writer !== void 0 && stream._backpressure && state2 === "writable") {
          defaultWriterReadyPromiseResolve(writer);
        }
        WritableStreamDefaultControllerClose(stream._writableStreamController);
        return promise;
      }
      function WritableStreamAddWriteRequest(stream) {
        const promise = newPromise((resolve2, reject) => {
          const writeRequest = {
            _resolve: resolve2,
            _reject: reject
          };
          stream._writeRequests.push(writeRequest);
        });
        return promise;
      }
      function WritableStreamDealWithRejection(stream, error2) {
        const state2 = stream._state;
        if (state2 === "writable") {
          WritableStreamStartErroring(stream, error2);
          return;
        }
        WritableStreamFinishErroring(stream);
      }
      function WritableStreamStartErroring(stream, reason) {
        const controller = stream._writableStreamController;
        stream._state = "erroring";
        stream._storedError = reason;
        const writer = stream._writer;
        if (writer !== void 0) {
          WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
        }
        if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
          WritableStreamFinishErroring(stream);
        }
      }
      function WritableStreamFinishErroring(stream) {
        stream._state = "errored";
        stream._writableStreamController[ErrorSteps]();
        const storedError = stream._storedError;
        stream._writeRequests.forEach((writeRequest) => {
          writeRequest._reject(storedError);
        });
        stream._writeRequests = new SimpleQueue();
        if (stream._pendingAbortRequest === void 0) {
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
          return;
        }
        const abortRequest = stream._pendingAbortRequest;
        stream._pendingAbortRequest = void 0;
        if (abortRequest._wasAlreadyErroring) {
          abortRequest._reject(storedError);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
          return;
        }
        const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
        uponPromise(promise, () => {
          abortRequest._resolve();
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
          return null;
        }, (reason) => {
          abortRequest._reject(reason);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
          return null;
        });
      }
      function WritableStreamFinishInFlightWrite(stream) {
        stream._inFlightWriteRequest._resolve(void 0);
        stream._inFlightWriteRequest = void 0;
      }
      function WritableStreamFinishInFlightWriteWithError(stream, error2) {
        stream._inFlightWriteRequest._reject(error2);
        stream._inFlightWriteRequest = void 0;
        WritableStreamDealWithRejection(stream, error2);
      }
      function WritableStreamFinishInFlightClose(stream) {
        stream._inFlightCloseRequest._resolve(void 0);
        stream._inFlightCloseRequest = void 0;
        const state2 = stream._state;
        if (state2 === "erroring") {
          stream._storedError = void 0;
          if (stream._pendingAbortRequest !== void 0) {
            stream._pendingAbortRequest._resolve();
            stream._pendingAbortRequest = void 0;
          }
        }
        stream._state = "closed";
        const writer = stream._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseResolve(writer);
        }
      }
      function WritableStreamFinishInFlightCloseWithError(stream, error2) {
        stream._inFlightCloseRequest._reject(error2);
        stream._inFlightCloseRequest = void 0;
        if (stream._pendingAbortRequest !== void 0) {
          stream._pendingAbortRequest._reject(error2);
          stream._pendingAbortRequest = void 0;
        }
        WritableStreamDealWithRejection(stream, error2);
      }
      function WritableStreamCloseQueuedOrInFlight(stream) {
        if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      function WritableStreamHasOperationMarkedInFlight(stream) {
        if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      function WritableStreamMarkCloseRequestInFlight(stream) {
        stream._inFlightCloseRequest = stream._closeRequest;
        stream._closeRequest = void 0;
      }
      function WritableStreamMarkFirstWriteRequestInFlight(stream) {
        stream._inFlightWriteRequest = stream._writeRequests.shift();
      }
      function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
        if (stream._closeRequest !== void 0) {
          stream._closeRequest._reject(stream._storedError);
          stream._closeRequest = void 0;
        }
        const writer = stream._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseReject(writer, stream._storedError);
        }
      }
      function WritableStreamUpdateBackpressure(stream, backpressure) {
        const writer = stream._writer;
        if (writer !== void 0 && backpressure !== stream._backpressure) {
          if (backpressure) {
            defaultWriterReadyPromiseReset(writer);
          } else {
            defaultWriterReadyPromiseResolve(writer);
          }
        }
        stream._backpressure = backpressure;
      }
      class WritableStreamDefaultWriter {
        constructor(stream) {
          assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter");
          assertWritableStream(stream, "First parameter");
          if (IsWritableStreamLocked(stream)) {
            throw new TypeError("This stream has already been locked for exclusive writing by another writer");
          }
          this._ownerWritableStream = stream;
          stream._writer = this;
          const state2 = stream._state;
          if (state2 === "writable") {
            if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
              defaultWriterReadyPromiseInitialize(this);
            } else {
              defaultWriterReadyPromiseInitializeAsResolved(this);
            }
            defaultWriterClosedPromiseInitialize(this);
          } else if (state2 === "erroring") {
            defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
            defaultWriterClosedPromiseInitialize(this);
          } else if (state2 === "closed") {
            defaultWriterReadyPromiseInitializeAsResolved(this);
            defaultWriterClosedPromiseInitializeAsResolved(this);
          } else {
            const storedError = stream._storedError;
            defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
            defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
          }
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
         * the writer’s lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
         * A producer can use this information to determine the right amount of data to write.
         *
         * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
         * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
         * the writer’s lock is released.
         */
        get desiredSize() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("desiredSize");
          }
          if (this._ownerWritableStream === void 0) {
            throw defaultWriterLockException("desiredSize");
          }
          return WritableStreamDefaultWriterGetDesiredSize(this);
        }
        /**
         * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
         * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
         * back to zero or below, the getter will return a new promise that stays pending until the next transition.
         *
         * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
         * rejected.
         */
        get ready() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
          }
          return this._readyPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
         */
        abort(reason = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("abort"));
          }
          return WritableStreamDefaultWriterAbort(this, reason);
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
         */
        close() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("close"));
          }
          const stream = this._ownerWritableStream;
          if (stream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("close"));
          }
          if (WritableStreamCloseQueuedOrInFlight(stream)) {
            return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
          }
          return WritableStreamDefaultWriterClose(this);
        }
        /**
         * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
         * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
         * now on; otherwise, the writer will appear closed.
         *
         * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
         * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
         * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
         * other producers from writing in an interleaved manner.
         */
        releaseLock() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("releaseLock");
          }
          const stream = this._ownerWritableStream;
          if (stream === void 0) {
            return;
          }
          WritableStreamDefaultWriterRelease(this);
        }
        write(chunk = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("write"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("write to"));
          }
          return WritableStreamDefaultWriterWrite(this, chunk);
        }
      }
      Object.defineProperties(WritableStreamDefaultWriter.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        releaseLock: { enumerable: true },
        write: { enumerable: true },
        closed: { enumerable: true },
        desiredSize: { enumerable: true },
        ready: { enumerable: true }
      });
      setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort");
      setFunctionName(WritableStreamDefaultWriter.prototype.close, "close");
      setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock");
      setFunctionName(WritableStreamDefaultWriter.prototype.write, "write");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {
          value: "WritableStreamDefaultWriter",
          configurable: true
        });
      }
      function IsWritableStreamDefaultWriter(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_ownerWritableStream")) {
          return false;
        }
        return x4 instanceof WritableStreamDefaultWriter;
      }
      function WritableStreamDefaultWriterAbort(writer, reason) {
        const stream = writer._ownerWritableStream;
        return WritableStreamAbort(stream, reason);
      }
      function WritableStreamDefaultWriterClose(writer) {
        const stream = writer._ownerWritableStream;
        return WritableStreamClose(stream);
      }
      function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
        const stream = writer._ownerWritableStream;
        const state2 = stream._state;
        if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (state2 === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        return WritableStreamDefaultWriterClose(writer);
      }
      function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) {
        if (writer._closedPromiseState === "pending") {
          defaultWriterClosedPromiseReject(writer, error2);
        } else {
          defaultWriterClosedPromiseResetToRejected(writer, error2);
        }
      }
      function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) {
        if (writer._readyPromiseState === "pending") {
          defaultWriterReadyPromiseReject(writer, error2);
        } else {
          defaultWriterReadyPromiseResetToRejected(writer, error2);
        }
      }
      function WritableStreamDefaultWriterGetDesiredSize(writer) {
        const stream = writer._ownerWritableStream;
        const state2 = stream._state;
        if (state2 === "errored" || state2 === "erroring") {
          return null;
        }
        if (state2 === "closed") {
          return 0;
        }
        return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
      }
      function WritableStreamDefaultWriterRelease(writer) {
        const stream = writer._ownerWritableStream;
        const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
        WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
        WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
        stream._writer = void 0;
        writer._ownerWritableStream = void 0;
      }
      function WritableStreamDefaultWriterWrite(writer, chunk) {
        const stream = writer._ownerWritableStream;
        const controller = stream._writableStreamController;
        const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
        if (stream !== writer._ownerWritableStream) {
          return promiseRejectedWith(defaultWriterLockException("write to"));
        }
        const state2 = stream._state;
        if (state2 === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
          return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
        }
        if (state2 === "erroring") {
          return promiseRejectedWith(stream._storedError);
        }
        const promise = WritableStreamAddWriteRequest(stream);
        WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
        return promise;
      }
      const closeSentinel = {};
      class WritableStreamDefaultController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
         *
         * @deprecated
         *  This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
         *  Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
         */
        get abortReason() {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("abortReason");
          }
          return this._abortReason;
        }
        /**
         * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
         */
        get signal() {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("signal");
          }
          if (this._abortController === void 0) {
            throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
          }
          return this._abortController.signal;
        }
        /**
         * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
         *
         * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
         * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
         * normal lifecycle of interactions with the underlying sink.
         */
        error(e4 = void 0) {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("error");
          }
          const state2 = this._controlledWritableStream._state;
          if (state2 !== "writable") {
            return;
          }
          WritableStreamDefaultControllerError(this, e4);
        }
        /** @internal */
        [AbortSteps](reason) {
          const result = this._abortAlgorithm(reason);
          WritableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [ErrorSteps]() {
          ResetQueue(this);
        }
      }
      Object.defineProperties(WritableStreamDefaultController.prototype, {
        abortReason: { enumerable: true },
        signal: { enumerable: true },
        error: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {
          value: "WritableStreamDefaultController",
          configurable: true
        });
      }
      function IsWritableStreamDefaultController(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_controlledWritableStream")) {
          return false;
        }
        return x4 instanceof WritableStreamDefaultController;
      }
      function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledWritableStream = stream;
        stream._writableStreamController = controller;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._abortReason = void 0;
        controller._abortController = createAbortController();
        controller._started = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._writeAlgorithm = writeAlgorithm;
        controller._closeAlgorithm = closeAlgorithm;
        controller._abortAlgorithm = abortAlgorithm;
        const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
        WritableStreamUpdateBackpressure(stream, backpressure);
        const startResult = startAlgorithm();
        const startPromise = promiseResolvedWith(startResult);
        uponPromise(startPromise, () => {
          controller._started = true;
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (r4) => {
          controller._started = true;
          WritableStreamDealWithRejection(stream, r4);
          return null;
        });
      }
      function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(WritableStreamDefaultController.prototype);
        let startAlgorithm;
        let writeAlgorithm;
        let closeAlgorithm;
        let abortAlgorithm;
        if (underlyingSink.start !== void 0) {
          startAlgorithm = () => underlyingSink.start(controller);
        } else {
          startAlgorithm = () => void 0;
        }
        if (underlyingSink.write !== void 0) {
          writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller);
        } else {
          writeAlgorithm = () => promiseResolvedWith(void 0);
        }
        if (underlyingSink.close !== void 0) {
          closeAlgorithm = () => underlyingSink.close();
        } else {
          closeAlgorithm = () => promiseResolvedWith(void 0);
        }
        if (underlyingSink.abort !== void 0) {
          abortAlgorithm = (reason) => underlyingSink.abort(reason);
        } else {
          abortAlgorithm = () => promiseResolvedWith(void 0);
        }
        SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
      }
      function WritableStreamDefaultControllerClearAlgorithms(controller) {
        controller._writeAlgorithm = void 0;
        controller._closeAlgorithm = void 0;
        controller._abortAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      function WritableStreamDefaultControllerClose(controller) {
        EnqueueValueWithSize(controller, closeSentinel, 0);
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
        try {
          return controller._strategySizeAlgorithm(chunk);
        } catch (chunkSizeE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
          return 1;
        }
      }
      function WritableStreamDefaultControllerGetDesiredSize(controller) {
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
        try {
          EnqueueValueWithSize(controller, chunk, chunkSize);
        } catch (enqueueE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
          return;
        }
        const stream = controller._controlledWritableStream;
        if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") {
          const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
          WritableStreamUpdateBackpressure(stream, backpressure);
        }
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
        const stream = controller._controlledWritableStream;
        if (!controller._started) {
          return;
        }
        if (stream._inFlightWriteRequest !== void 0) {
          return;
        }
        const state2 = stream._state;
        if (state2 === "erroring") {
          WritableStreamFinishErroring(stream);
          return;
        }
        if (controller._queue.length === 0) {
          return;
        }
        const value = PeekQueueValue(controller);
        if (value === closeSentinel) {
          WritableStreamDefaultControllerProcessClose(controller);
        } else {
          WritableStreamDefaultControllerProcessWrite(controller, value);
        }
      }
      function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) {
        if (controller._controlledWritableStream._state === "writable") {
          WritableStreamDefaultControllerError(controller, error2);
        }
      }
      function WritableStreamDefaultControllerProcessClose(controller) {
        const stream = controller._controlledWritableStream;
        WritableStreamMarkCloseRequestInFlight(stream);
        DequeueValue(controller);
        const sinkClosePromise = controller._closeAlgorithm();
        WritableStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(sinkClosePromise, () => {
          WritableStreamFinishInFlightClose(stream);
          return null;
        }, (reason) => {
          WritableStreamFinishInFlightCloseWithError(stream, reason);
          return null;
        });
      }
      function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
        const stream = controller._controlledWritableStream;
        WritableStreamMarkFirstWriteRequestInFlight(stream);
        const sinkWritePromise = controller._writeAlgorithm(chunk);
        uponPromise(sinkWritePromise, () => {
          WritableStreamFinishInFlightWrite(stream);
          const state2 = stream._state;
          DequeueValue(controller);
          if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "writable") {
            const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
            WritableStreamUpdateBackpressure(stream, backpressure);
          }
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (reason) => {
          if (stream._state === "writable") {
            WritableStreamDefaultControllerClearAlgorithms(controller);
          }
          WritableStreamFinishInFlightWriteWithError(stream, reason);
          return null;
        });
      }
      function WritableStreamDefaultControllerGetBackpressure(controller) {
        const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
        return desiredSize <= 0;
      }
      function WritableStreamDefaultControllerError(controller, error2) {
        const stream = controller._controlledWritableStream;
        WritableStreamDefaultControllerClearAlgorithms(controller);
        WritableStreamStartErroring(stream, error2);
      }
      function streamBrandCheckException$2(name) {
        return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
      }
      function defaultControllerBrandCheckException$2(name) {
        return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
      }
      function defaultWriterBrandCheckException(name) {
        return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
      }
      function defaultWriterLockException(name) {
        return new TypeError("Cannot " + name + " a stream using a released writer");
      }
      function defaultWriterClosedPromiseInitialize(writer) {
        writer._closedPromise = newPromise((resolve2, reject) => {
          writer._closedPromise_resolve = resolve2;
          writer._closedPromise_reject = reject;
          writer._closedPromiseState = "pending";
        });
      }
      function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseReject(writer, reason);
      }
      function defaultWriterClosedPromiseInitializeAsResolved(writer) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseResolve(writer);
      }
      function defaultWriterClosedPromiseReject(writer, reason) {
        if (writer._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._closedPromise);
        writer._closedPromise_reject(reason);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "rejected";
      }
      function defaultWriterClosedPromiseResetToRejected(writer, reason) {
        defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
      }
      function defaultWriterClosedPromiseResolve(writer) {
        if (writer._closedPromise_resolve === void 0) {
          return;
        }
        writer._closedPromise_resolve(void 0);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "resolved";
      }
      function defaultWriterReadyPromiseInitialize(writer) {
        writer._readyPromise = newPromise((resolve2, reject) => {
          writer._readyPromise_resolve = resolve2;
          writer._readyPromise_reject = reject;
        });
        writer._readyPromiseState = "pending";
      }
      function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseReject(writer, reason);
      }
      function defaultWriterReadyPromiseInitializeAsResolved(writer) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseResolve(writer);
      }
      function defaultWriterReadyPromiseReject(writer, reason) {
        if (writer._readyPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._readyPromise);
        writer._readyPromise_reject(reason);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "rejected";
      }
      function defaultWriterReadyPromiseReset(writer) {
        defaultWriterReadyPromiseInitialize(writer);
      }
      function defaultWriterReadyPromiseResetToRejected(writer, reason) {
        defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
      }
      function defaultWriterReadyPromiseResolve(writer) {
        if (writer._readyPromise_resolve === void 0) {
          return;
        }
        writer._readyPromise_resolve(void 0);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "fulfilled";
      }
      function getGlobals() {
        if (typeof globalThis !== "undefined") {
          return globalThis;
        } else if (typeof self !== "undefined") {
          return self;
        } else if (typeof global !== "undefined") {
          return global;
        }
        return void 0;
      }
      const globals = getGlobals();
      function isDOMExceptionConstructor(ctor) {
        if (!(typeof ctor === "function" || typeof ctor === "object")) {
          return false;
        }
        if (ctor.name !== "DOMException") {
          return false;
        }
        try {
          new ctor();
          return true;
        } catch (_a3) {
          return false;
        }
      }
      function getFromGlobal() {
        const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
        return isDOMExceptionConstructor(ctor) ? ctor : void 0;
      }
      function createPolyfill() {
        const ctor = function DOMException3(message, name) {
          this.message = message || "";
          this.name = name || "Error";
          if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
          }
        };
        setFunctionName(ctor, "DOMException");
        ctor.prototype = Object.create(Error.prototype);
        Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true });
        return ctor;
      }
      const DOMException2 = getFromGlobal() || createPolyfill();
      function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
        const reader = AcquireReadableStreamDefaultReader(source);
        const writer = AcquireWritableStreamDefaultWriter(dest);
        source._disturbed = true;
        let shuttingDown = false;
        let currentWrite = promiseResolvedWith(void 0);
        return newPromise((resolve2, reject) => {
          let abortAlgorithm;
          if (signal !== void 0) {
            abortAlgorithm = () => {
              const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError");
              const actions = [];
              if (!preventAbort) {
                actions.push(() => {
                  if (dest._state === "writable") {
                    return WritableStreamAbort(dest, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              if (!preventCancel) {
                actions.push(() => {
                  if (source._state === "readable") {
                    return ReadableStreamCancel(source, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2);
            };
            if (signal.aborted) {
              abortAlgorithm();
              return;
            }
            signal.addEventListener("abort", abortAlgorithm);
          }
          function pipeLoop() {
            return newPromise((resolveLoop, rejectLoop) => {
              function next(done) {
                if (done) {
                  resolveLoop();
                } else {
                  PerformPromiseThen(pipeStep(), next, rejectLoop);
                }
              }
              next(false);
            });
          }
          function pipeStep() {
            if (shuttingDown) {
              return promiseResolvedWith(true);
            }
            return PerformPromiseThen(writer._readyPromise, () => {
              return newPromise((resolveRead, rejectRead) => {
                ReadableStreamDefaultReaderRead(reader, {
                  _chunkSteps: (chunk) => {
                    currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2);
                    resolveRead(false);
                  },
                  _closeSteps: () => resolveRead(true),
                  _errorSteps: rejectRead
                });
              });
            });
          }
          isOrBecomesErrored(source, reader._closedPromise, (storedError) => {
            if (!preventAbort) {
              shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
            } else {
              shutdown(true, storedError);
            }
            return null;
          });
          isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
            if (!preventCancel) {
              shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
            } else {
              shutdown(true, storedError);
            }
            return null;
          });
          isOrBecomesClosed(source, reader._closedPromise, () => {
            if (!preventClose) {
              shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
            } else {
              shutdown();
            }
            return null;
          });
          if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") {
            const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it");
            if (!preventCancel) {
              shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
            } else {
              shutdown(true, destClosed);
            }
          }
          setPromiseIsHandledToTrue(pipeLoop());
          function waitForWritesToFinish() {
            const oldCurrentWrite = currentWrite;
            return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0);
          }
          function isOrBecomesErrored(stream, promise, action) {
            if (stream._state === "errored") {
              action(stream._storedError);
            } else {
              uponRejection(promise, action);
            }
          }
          function isOrBecomesClosed(stream, promise, action) {
            if (stream._state === "closed") {
              action();
            } else {
              uponFulfillment(promise, action);
            }
          }
          function shutdownWithAction(action, originalIsError, originalError) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), doTheRest);
            } else {
              doTheRest();
            }
            function doTheRest() {
              uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
              return null;
            }
          }
          function shutdown(isError, error2) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2));
            } else {
              finalize(isError, error2);
            }
          }
          function finalize(isError, error2) {
            WritableStreamDefaultWriterRelease(writer);
            ReadableStreamReaderGenericRelease(reader);
            if (signal !== void 0) {
              signal.removeEventListener("abort", abortAlgorithm);
            }
            if (isError) {
              reject(error2);
            } else {
              resolve2(void 0);
            }
            return null;
          }
        });
      }
      class ReadableStreamDefaultController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("desiredSize");
          }
          return ReadableStreamDefaultControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("close");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits close");
          }
          ReadableStreamDefaultControllerClose(this);
        }
        enqueue(chunk = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("enqueue");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits enqueue");
          }
          return ReadableStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e4 = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("error");
          }
          ReadableStreamDefaultControllerError(this, e4);
        }
        /** @internal */
        [CancelSteps](reason) {
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream = this._controlledReadableStream;
          if (this._queue.length > 0) {
            const chunk = DequeueValue(this);
            if (this._closeRequested && this._queue.length === 0) {
              ReadableStreamDefaultControllerClearAlgorithms(this);
              ReadableStreamClose(stream);
            } else {
              ReadableStreamDefaultControllerCallPullIfNeeded(this);
            }
            readRequest._chunkSteps(chunk);
          } else {
            ReadableStreamAddReadRequest(stream, readRequest);
            ReadableStreamDefaultControllerCallPullIfNeeded(this);
          }
        }
        /** @internal */
        [ReleaseSteps]() {
        }
      }
      Object.defineProperties(ReadableStreamDefaultController.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(ReadableStreamDefaultController.prototype.close, "close");
      setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue");
      setFunctionName(ReadableStreamDefaultController.prototype.error, "error");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {
          value: "ReadableStreamDefaultController",
          configurable: true
        });
      }
      function IsReadableStreamDefaultController(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableStream")) {
          return false;
        }
        return x4 instanceof ReadableStreamDefaultController;
      }
      function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableStreamDefaultControllerCallPullIfNeeded(controller);
          }
          return null;
        }, (e4) => {
          ReadableStreamDefaultControllerError(controller, e4);
          return null;
        });
      }
      function ReadableStreamDefaultControllerShouldCallPull(controller) {
        const stream = controller._controlledReadableStream;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
          return true;
        }
        const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
        if (desiredSize > 0) {
          return true;
        }
        return false;
      }
      function ReadableStreamDefaultControllerClearAlgorithms(controller) {
        controller._pullAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      function ReadableStreamDefaultControllerClose(controller) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream = controller._controlledReadableStream;
        controller._closeRequested = true;
        if (controller._queue.length === 0) {
          ReadableStreamDefaultControllerClearAlgorithms(controller);
          ReadableStreamClose(stream);
        }
      }
      function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream = controller._controlledReadableStream;
        if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
          ReadableStreamFulfillReadRequest(stream, chunk, false);
        } else {
          let chunkSize;
          try {
            chunkSize = controller._strategySizeAlgorithm(chunk);
          } catch (chunkSizeE) {
            ReadableStreamDefaultControllerError(controller, chunkSizeE);
            throw chunkSizeE;
          }
          try {
            EnqueueValueWithSize(controller, chunk, chunkSize);
          } catch (enqueueE) {
            ReadableStreamDefaultControllerError(controller, enqueueE);
            throw enqueueE;
          }
        }
        ReadableStreamDefaultControllerCallPullIfNeeded(controller);
      }
      function ReadableStreamDefaultControllerError(controller, e4) {
        const stream = controller._controlledReadableStream;
        if (stream._state !== "readable") {
          return;
        }
        ResetQueue(controller);
        ReadableStreamDefaultControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e4);
      }
      function ReadableStreamDefaultControllerGetDesiredSize(controller) {
        const state2 = controller._controlledReadableStream._state;
        if (state2 === "errored") {
          return null;
        }
        if (state2 === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableStreamDefaultControllerHasBackpressure(controller) {
        if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
          return false;
        }
        return true;
      }
      function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
        const state2 = controller._controlledReadableStream._state;
        if (!controller._closeRequested && state2 === "readable") {
          return true;
        }
        return false;
      }
      function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledReadableStream = stream;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._started = false;
        controller._closeRequested = false;
        controller._pullAgain = false;
        controller._pulling = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._pullAlgorithm = pullAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        stream._readableStreamController = controller;
        const startResult = startAlgorithm();
        uponPromise(promiseResolvedWith(startResult), () => {
          controller._started = true;
          ReadableStreamDefaultControllerCallPullIfNeeded(controller);
          return null;
        }, (r4) => {
          ReadableStreamDefaultControllerError(controller, r4);
          return null;
        });
      }
      function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(ReadableStreamDefaultController.prototype);
        let startAlgorithm;
        let pullAlgorithm;
        let cancelAlgorithm;
        if (underlyingSource.start !== void 0) {
          startAlgorithm = () => underlyingSource.start(controller);
        } else {
          startAlgorithm = () => void 0;
        }
        if (underlyingSource.pull !== void 0) {
          pullAlgorithm = () => underlyingSource.pull(controller);
        } else {
          pullAlgorithm = () => promiseResolvedWith(void 0);
        }
        if (underlyingSource.cancel !== void 0) {
          cancelAlgorithm = (reason) => underlyingSource.cancel(reason);
        } else {
          cancelAlgorithm = () => promiseResolvedWith(void 0);
        }
        SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
      }
      function defaultControllerBrandCheckException$1(name) {
        return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
      }
      function ReadableStreamTee(stream, cloneForBranch2) {
        if (IsReadableByteStreamController(stream._readableStreamController)) {
          return ReadableByteStreamTee(stream);
        }
        return ReadableStreamDefaultTee(stream);
      }
      function ReadableStreamDefaultTee(stream, cloneForBranch2) {
        const reader = AcquireReadableStreamDefaultReader(stream);
        let reading = false;
        let readAgain = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve2) => {
          resolveCancelPromise = resolve2;
        });
        function pullAlgorithm() {
          if (reading) {
            readAgain = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const readRequest = {
            _chunkSteps: (chunk) => {
              _queueMicrotask(() => {
                readAgain = false;
                const chunk1 = chunk;
                const chunk2 = chunk;
                if (!canceled1) {
                  ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
                }
                if (!canceled2) {
                  ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
                }
                reading = false;
                if (readAgain) {
                  pullAlgorithm();
                }
              });
            },
            _closeSteps: () => {
              reading = false;
              if (!canceled1) {
                ReadableStreamDefaultControllerClose(branch1._readableStreamController);
              }
              if (!canceled2) {
                ReadableStreamDefaultControllerClose(branch2._readableStreamController);
              }
              if (!canceled1 || !canceled2) {
                resolveCancelPromise(void 0);
              }
            },
            _errorSteps: () => {
              reading = false;
            }
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promiseResolvedWith(void 0);
        }
        function cancel1Algorithm(reason) {
          canceled1 = true;
          reason1 = reason;
          if (canceled2) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function cancel2Algorithm(reason) {
          canceled2 = true;
          reason2 = reason;
          if (canceled1) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function startAlgorithm() {
        }
        branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
        branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
        uponRejection(reader._closedPromise, (r4) => {
          ReadableStreamDefaultControllerError(branch1._readableStreamController, r4);
          ReadableStreamDefaultControllerError(branch2._readableStreamController, r4);
          if (!canceled1 || !canceled2) {
            resolveCancelPromise(void 0);
          }
          return null;
        });
        return [branch1, branch2];
      }
      function ReadableByteStreamTee(stream) {
        let reader = AcquireReadableStreamDefaultReader(stream);
        let reading = false;
        let readAgainForBranch1 = false;
        let readAgainForBranch2 = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve2) => {
          resolveCancelPromise = resolve2;
        });
        function forwardReaderError(thisReader) {
          uponRejection(thisReader._closedPromise, (r4) => {
            if (thisReader !== reader) {
              return null;
            }
            ReadableByteStreamControllerError(branch1._readableStreamController, r4);
            ReadableByteStreamControllerError(branch2._readableStreamController, r4);
            if (!canceled1 || !canceled2) {
              resolveCancelPromise(void 0);
            }
            return null;
          });
        }
        function pullWithDefaultReader() {
          if (IsReadableStreamBYOBReader(reader)) {
            ReadableStreamReaderGenericRelease(reader);
            reader = AcquireReadableStreamDefaultReader(stream);
            forwardReaderError(reader);
          }
          const readRequest = {
            _chunkSteps: (chunk) => {
              _queueMicrotask(() => {
                readAgainForBranch1 = false;
                readAgainForBranch2 = false;
                const chunk1 = chunk;
                let chunk2 = chunk;
                if (!canceled1 && !canceled2) {
                  try {
                    chunk2 = CloneAsUint8Array(chunk);
                  } catch (cloneE) {
                    ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
                    ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
                    resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
                    return;
                  }
                }
                if (!canceled1) {
                  ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
                }
                if (!canceled2) {
                  ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
                }
                reading = false;
                if (readAgainForBranch1) {
                  pull1Algorithm();
                } else if (readAgainForBranch2) {
                  pull2Algorithm();
                }
              });
            },
            _closeSteps: () => {
              reading = false;
              if (!canceled1) {
                ReadableByteStreamControllerClose(branch1._readableStreamController);
              }
              if (!canceled2) {
                ReadableByteStreamControllerClose(branch2._readableStreamController);
              }
              if (branch1._readableStreamController._pendingPullIntos.length > 0) {
                ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
              }
              if (branch2._readableStreamController._pendingPullIntos.length > 0) {
                ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
              }
              if (!canceled1 || !canceled2) {
                resolveCancelPromise(void 0);
              }
            },
            _errorSteps: () => {
              reading = false;
            }
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
        }
        function pullWithBYOBReader(view5, forBranch2) {
          if (IsReadableStreamDefaultReader(reader)) {
            ReadableStreamReaderGenericRelease(reader);
            reader = AcquireReadableStreamBYOBReader(stream);
            forwardReaderError(reader);
          }
          const byobBranch = forBranch2 ? branch2 : branch1;
          const otherBranch = forBranch2 ? branch1 : branch2;
          const readIntoRequest = {
            _chunkSteps: (chunk) => {
              _queueMicrotask(() => {
                readAgainForBranch1 = false;
                readAgainForBranch2 = false;
                const byobCanceled = forBranch2 ? canceled2 : canceled1;
                const otherCanceled = forBranch2 ? canceled1 : canceled2;
                if (!otherCanceled) {
                  let clonedChunk;
                  try {
                    clonedChunk = CloneAsUint8Array(chunk);
                  } catch (cloneE) {
                    ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
                    ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
                    resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
                    return;
                  }
                  if (!byobCanceled) {
                    ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                  }
                  ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
                } else if (!byobCanceled) {
                  ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                }
                reading = false;
                if (readAgainForBranch1) {
                  pull1Algorithm();
                } else if (readAgainForBranch2) {
                  pull2Algorithm();
                }
              });
            },
            _closeSteps: (chunk) => {
              reading = false;
              const byobCanceled = forBranch2 ? canceled2 : canceled1;
              const otherCanceled = forBranch2 ? canceled1 : canceled2;
              if (!byobCanceled) {
                ReadableByteStreamControllerClose(byobBranch._readableStreamController);
              }
              if (!otherCanceled) {
                ReadableByteStreamControllerClose(otherBranch._readableStreamController);
              }
              if (chunk !== void 0) {
                if (!byobCanceled) {
                  ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                }
                if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
                  ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
                }
              }
              if (!byobCanceled || !otherCanceled) {
                resolveCancelPromise(void 0);
              }
            },
            _errorSteps: () => {
              reading = false;
            }
          };
          ReadableStreamBYOBReaderRead(reader, view5, 1, readIntoRequest);
        }
        function pull1Algorithm() {
          if (reading) {
            readAgainForBranch1 = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
          if (byobRequest === null) {
            pullWithDefaultReader();
          } else {
            pullWithBYOBReader(byobRequest._view, false);
          }
          return promiseResolvedWith(void 0);
        }
        function pull2Algorithm() {
          if (reading) {
            readAgainForBranch2 = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
          if (byobRequest === null) {
            pullWithDefaultReader();
          } else {
            pullWithBYOBReader(byobRequest._view, true);
          }
          return promiseResolvedWith(void 0);
        }
        function cancel1Algorithm(reason) {
          canceled1 = true;
          reason1 = reason;
          if (canceled2) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function cancel2Algorithm(reason) {
          canceled2 = true;
          reason2 = reason;
          if (canceled1) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function startAlgorithm() {
          return;
        }
        branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
        branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
        forwardReaderError(reader);
        return [branch1, branch2];
      }
      function isReadableStreamLike(stream) {
        return typeIsObject(stream) && typeof stream.getReader !== "undefined";
      }
      function ReadableStreamFrom(source) {
        if (isReadableStreamLike(source)) {
          return ReadableStreamFromDefaultReader(source.getReader());
        }
        return ReadableStreamFromIterable(source);
      }
      function ReadableStreamFromIterable(asyncIterable) {
        let stream;
        const iteratorRecord = GetIterator(asyncIterable, "async");
        const startAlgorithm = noop2;
        function pullAlgorithm() {
          let nextResult;
          try {
            nextResult = IteratorNext(iteratorRecord);
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const nextPromise = promiseResolvedWith(nextResult);
          return transformPromiseWith(nextPromise, (iterResult) => {
            if (!typeIsObject(iterResult)) {
              throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");
            }
            const done = IteratorComplete(iterResult);
            if (done) {
              ReadableStreamDefaultControllerClose(stream._readableStreamController);
            } else {
              const value = IteratorValue(iterResult);
              ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
            }
          });
        }
        function cancelAlgorithm(reason) {
          const iterator = iteratorRecord.iterator;
          let returnMethod;
          try {
            returnMethod = GetMethod(iterator, "return");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          if (returnMethod === void 0) {
            return promiseResolvedWith(void 0);
          }
          let returnResult;
          try {
            returnResult = reflectCall(returnMethod, iterator, [reason]);
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const returnPromise = promiseResolvedWith(returnResult);
          return transformPromiseWith(returnPromise, (iterResult) => {
            if (!typeIsObject(iterResult)) {
              throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object");
            }
            return void 0;
          });
        }
        stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream;
      }
      function ReadableStreamFromDefaultReader(reader) {
        let stream;
        const startAlgorithm = noop2;
        function pullAlgorithm() {
          let readPromise;
          try {
            readPromise = reader.read();
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          return transformPromiseWith(readPromise, (readResult) => {
            if (!typeIsObject(readResult)) {
              throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");
            }
            if (readResult.done) {
              ReadableStreamDefaultControllerClose(stream._readableStreamController);
            } else {
              const value = readResult.value;
              ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
            }
          });
        }
        function cancelAlgorithm(reason) {
          try {
            return promiseResolvedWith(reader.cancel(reason));
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
        }
        stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream;
      }
      function convertUnderlyingDefaultOrByteSource(source, context) {
        assertDictionary(source, context);
        const original = source;
        const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
        const cancel = original === null || original === void 0 ? void 0 : original.cancel;
        const pull2 = original === null || original === void 0 ? void 0 : original.pull;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const type = original === null || original === void 0 ? void 0 : original.type;
        return {
          autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
          cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
          pull: pull2 === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull2, original, `${context} has member 'pull' that`),
          start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
          type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`)
        };
      }
      function convertUnderlyingSourceCancelCallback(fn, original, context) {
        assertFunction(fn, context);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      function convertUnderlyingSourcePullCallback(fn, original, context) {
        assertFunction(fn, context);
        return (controller) => promiseCall(fn, original, [controller]);
      }
      function convertUnderlyingSourceStartCallback(fn, original, context) {
        assertFunction(fn, context);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      function convertReadableStreamType(type, context) {
        type = `${type}`;
        if (type !== "bytes") {
          throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
        }
        return type;
      }
      function convertIteratorOptions(options, context) {
        assertDictionary(options, context);
        const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
        return { preventCancel: Boolean(preventCancel) };
      }
      function convertPipeOptions(options, context) {
        assertDictionary(options, context);
        const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
        const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
        const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
        const signal = options === null || options === void 0 ? void 0 : options.signal;
        if (signal !== void 0) {
          assertAbortSignal(signal, `${context} has member 'signal' that`);
        }
        return {
          preventAbort: Boolean(preventAbort),
          preventCancel: Boolean(preventCancel),
          preventClose: Boolean(preventClose),
          signal
        };
      }
      function assertAbortSignal(signal, context) {
        if (!isAbortSignal2(signal)) {
          throw new TypeError(`${context} is not an AbortSignal.`);
        }
      }
      function convertReadableWritablePair(pair, context) {
        assertDictionary(pair, context);
        const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
        assertRequiredField(readable, "readable", "ReadableWritablePair");
        assertReadableStream(readable, `${context} has member 'readable' that`);
        const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
        assertRequiredField(writable, "writable", "ReadableWritablePair");
        assertWritableStream(writable, `${context} has member 'writable' that`);
        return { readable, writable };
      }
      class ReadableStream2 {
        constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
          if (rawUnderlyingSource === void 0) {
            rawUnderlyingSource = null;
          } else {
            assertObject(rawUnderlyingSource, "First parameter");
          }
          const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
          const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter");
          InitializeReadableStream(this);
          if (underlyingSource.type === "bytes") {
            if (strategy.size !== void 0) {
              throw new RangeError("The strategy for a byte stream cannot have a size function");
            }
            const highWaterMark = ExtractHighWaterMark(strategy, 0);
            SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
          } else {
            const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
            const highWaterMark = ExtractHighWaterMark(strategy, 1);
            SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
          }
        }
        /**
         * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
         */
        get locked() {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("locked");
          }
          return IsReadableStreamLocked(this);
        }
        /**
         * Cancels the stream, signaling a loss of interest in the stream by a consumer.
         *
         * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
         * method, which might or might not use it.
         */
        cancel(reason = void 0) {
          if (!IsReadableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$1("cancel"));
          }
          if (IsReadableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader"));
          }
          return ReadableStreamCancel(this, reason);
        }
        getReader(rawOptions = void 0) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("getReader");
          }
          const options = convertReaderOptions(rawOptions, "First parameter");
          if (options.mode === void 0) {
            return AcquireReadableStreamDefaultReader(this);
          }
          return AcquireReadableStreamBYOBReader(this);
        }
        pipeThrough(rawTransform, rawOptions = {}) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("pipeThrough");
          }
          assertRequiredArgument(rawTransform, 1, "pipeThrough");
          const transform = convertReadableWritablePair(rawTransform, "First parameter");
          const options = convertPipeOptions(rawOptions, "Second parameter");
          if (IsReadableStreamLocked(this)) {
            throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
          }
          if (IsWritableStreamLocked(transform.writable)) {
            throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
          }
          const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
          setPromiseIsHandledToTrue(promise);
          return transform.readable;
        }
        pipeTo(destination, rawOptions = {}) {
          if (!IsReadableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$1("pipeTo"));
          }
          if (destination === void 0) {
            return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
          }
          if (!IsWritableStream(destination)) {
            return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
          }
          let options;
          try {
            options = convertPipeOptions(rawOptions, "Second parameter");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          if (IsReadableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
          }
          if (IsWritableStreamLocked(destination)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
          }
          return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
        }
        /**
         * Tees this readable stream, returning a two-element array containing the two resulting branches as
         * new {@link ReadableStream} instances.
         *
         * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
         * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
         * propagated to the stream's underlying source.
         *
         * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
         * this could allow interference between the two branches.
         */
        tee() {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("tee");
          }
          const branches = ReadableStreamTee(this);
          return CreateArrayFromList(branches);
        }
        values(rawOptions = void 0) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("values");
          }
          const options = convertIteratorOptions(rawOptions, "First parameter");
          return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
        }
        [SymbolAsyncIterator](options) {
          return this.values(options);
        }
        /**
         * Creates a new ReadableStream wrapping the provided iterable or async iterable.
         *
         * This can be used to adapt various kinds of objects into a readable stream,
         * such as an array, an async generator, or a Node.js readable stream.
         */
        static from(asyncIterable) {
          return ReadableStreamFrom(asyncIterable);
        }
      }
      Object.defineProperties(ReadableStream2, {
        from: { enumerable: true }
      });
      Object.defineProperties(ReadableStream2.prototype, {
        cancel: { enumerable: true },
        getReader: { enumerable: true },
        pipeThrough: { enumerable: true },
        pipeTo: { enumerable: true },
        tee: { enumerable: true },
        values: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(ReadableStream2.from, "from");
      setFunctionName(ReadableStream2.prototype.cancel, "cancel");
      setFunctionName(ReadableStream2.prototype.getReader, "getReader");
      setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough");
      setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo");
      setFunctionName(ReadableStream2.prototype.tee, "tee");
      setFunctionName(ReadableStream2.prototype.values, "values");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, {
          value: "ReadableStream",
          configurable: true
        });
      }
      Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, {
        value: ReadableStream2.prototype.values,
        writable: true,
        configurable: true
      });
      function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream = Object.create(ReadableStream2.prototype);
        InitializeReadableStream(stream);
        const controller = Object.create(ReadableStreamDefaultController.prototype);
        SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
        return stream;
      }
      function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
        const stream = Object.create(ReadableStream2.prototype);
        InitializeReadableStream(stream);
        const controller = Object.create(ReadableByteStreamController.prototype);
        SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
        return stream;
      }
      function InitializeReadableStream(stream) {
        stream._state = "readable";
        stream._reader = void 0;
        stream._storedError = void 0;
        stream._disturbed = false;
      }
      function IsReadableStream(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_readableStreamController")) {
          return false;
        }
        return x4 instanceof ReadableStream2;
      }
      function IsReadableStreamLocked(stream) {
        if (stream._reader === void 0) {
          return false;
        }
        return true;
      }
      function ReadableStreamCancel(stream, reason) {
        stream._disturbed = true;
        if (stream._state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (stream._state === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        ReadableStreamClose(stream);
        const reader = stream._reader;
        if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
          const readIntoRequests = reader._readIntoRequests;
          reader._readIntoRequests = new SimpleQueue();
          readIntoRequests.forEach((readIntoRequest) => {
            readIntoRequest._closeSteps(void 0);
          });
        }
        const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
        return transformPromiseWith(sourceCancelPromise, noop2);
      }
      function ReadableStreamClose(stream) {
        stream._state = "closed";
        const reader = stream._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseResolve(reader);
        if (IsReadableStreamDefaultReader(reader)) {
          const readRequests = reader._readRequests;
          reader._readRequests = new SimpleQueue();
          readRequests.forEach((readRequest) => {
            readRequest._closeSteps();
          });
        }
      }
      function ReadableStreamError(stream, e4) {
        stream._state = "errored";
        stream._storedError = e4;
        const reader = stream._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseReject(reader, e4);
        if (IsReadableStreamDefaultReader(reader)) {
          ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
        } else {
          ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
        }
      }
      function streamBrandCheckException$1(name) {
        return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
      }
      function convertQueuingStrategyInit(init2, context) {
        assertDictionary(init2, context);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
        assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit");
        return {
          highWaterMark: convertUnrestrictedDouble(highWaterMark)
        };
      }
      const byteLengthSizeFunction = (chunk) => {
        return chunk.byteLength;
      };
      setFunctionName(byteLengthSizeFunction, "size");
      class ByteLengthQueuingStrategy {
        constructor(options) {
          assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy");
          options = convertQueuingStrategyInit(options, "First parameter");
          this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
        }
        /**
         * Returns the high water mark provided to the constructor.
         */
        get highWaterMark() {
          if (!IsByteLengthQueuingStrategy(this)) {
            throw byteLengthBrandCheckException("highWaterMark");
          }
          return this._byteLengthQueuingStrategyHighWaterMark;
        }
        /**
         * Measures the size of `chunk` by returning the value of its `byteLength` property.
         */
        get size() {
          if (!IsByteLengthQueuingStrategy(this)) {
            throw byteLengthBrandCheckException("size");
          }
          return byteLengthSizeFunction;
        }
      }
      Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
        highWaterMark: { enumerable: true },
        size: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {
          value: "ByteLengthQueuingStrategy",
          configurable: true
        });
      }
      function byteLengthBrandCheckException(name) {
        return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
      }
      function IsByteLengthQueuingStrategy(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_byteLengthQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x4 instanceof ByteLengthQueuingStrategy;
      }
      const countSizeFunction = () => {
        return 1;
      };
      setFunctionName(countSizeFunction, "size");
      class CountQueuingStrategy {
        constructor(options) {
          assertRequiredArgument(options, 1, "CountQueuingStrategy");
          options = convertQueuingStrategyInit(options, "First parameter");
          this._countQueuingStrategyHighWaterMark = options.highWaterMark;
        }
        /**
         * Returns the high water mark provided to the constructor.
         */
        get highWaterMark() {
          if (!IsCountQueuingStrategy(this)) {
            throw countBrandCheckException("highWaterMark");
          }
          return this._countQueuingStrategyHighWaterMark;
        }
        /**
         * Measures the size of `chunk` by always returning 1.
         * This ensures that the total queue size is a count of the number of chunks in the queue.
         */
        get size() {
          if (!IsCountQueuingStrategy(this)) {
            throw countBrandCheckException("size");
          }
          return countSizeFunction;
        }
      }
      Object.defineProperties(CountQueuingStrategy.prototype, {
        highWaterMark: { enumerable: true },
        size: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {
          value: "CountQueuingStrategy",
          configurable: true
        });
      }
      function countBrandCheckException(name) {
        return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
      }
      function IsCountQueuingStrategy(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_countQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x4 instanceof CountQueuingStrategy;
      }
      function convertTransformer(original, context) {
        assertDictionary(original, context);
        const cancel = original === null || original === void 0 ? void 0 : original.cancel;
        const flush = original === null || original === void 0 ? void 0 : original.flush;
        const readableType = original === null || original === void 0 ? void 0 : original.readableType;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const transform = original === null || original === void 0 ? void 0 : original.transform;
        const writableType = original === null || original === void 0 ? void 0 : original.writableType;
        return {
          cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
          flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
          readableType,
          start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
          transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
          writableType
        };
      }
      function convertTransformerFlushCallback(fn, original, context) {
        assertFunction(fn, context);
        return (controller) => promiseCall(fn, original, [controller]);
      }
      function convertTransformerStartCallback(fn, original, context) {
        assertFunction(fn, context);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      function convertTransformerTransformCallback(fn, original, context) {
        assertFunction(fn, context);
        return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
      }
      function convertTransformerCancelCallback(fn, original, context) {
        assertFunction(fn, context);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      class TransformStream2 {
        constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
          if (rawTransformer === void 0) {
            rawTransformer = null;
          }
          const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
          const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
          const transformer = convertTransformer(rawTransformer, "First parameter");
          if (transformer.readableType !== void 0) {
            throw new RangeError("Invalid readableType specified");
          }
          if (transformer.writableType !== void 0) {
            throw new RangeError("Invalid writableType specified");
          }
          const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
          const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
          const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
          const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
          let startPromise_resolve;
          const startPromise = newPromise((resolve2) => {
            startPromise_resolve = resolve2;
          });
          InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
          SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
          if (transformer.start !== void 0) {
            startPromise_resolve(transformer.start(this._transformStreamController));
          } else {
            startPromise_resolve(void 0);
          }
        }
        /**
         * The readable side of the transform stream.
         */
        get readable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("readable");
          }
          return this._readable;
        }
        /**
         * The writable side of the transform stream.
         */
        get writable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("writable");
          }
          return this._writable;
        }
      }
      Object.defineProperties(TransformStream2.prototype, {
        readable: { enumerable: true },
        writable: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, {
          value: "TransformStream",
          configurable: true
        });
      }
      function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
        function startAlgorithm() {
          return startPromise;
        }
        function writeAlgorithm(chunk) {
          return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
        }
        function abortAlgorithm(reason) {
          return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
        }
        function closeAlgorithm() {
          return TransformStreamDefaultSinkCloseAlgorithm(stream);
        }
        stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
        function pullAlgorithm() {
          return TransformStreamDefaultSourcePullAlgorithm(stream);
        }
        function cancelAlgorithm(reason) {
          return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
        }
        stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
        stream._backpressure = void 0;
        stream._backpressureChangePromise = void 0;
        stream._backpressureChangePromise_resolve = void 0;
        TransformStreamSetBackpressure(stream, true);
        stream._transformStreamController = void 0;
      }
      function IsTransformStream(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_transformStreamController")) {
          return false;
        }
        return x4 instanceof TransformStream2;
      }
      function TransformStreamError(stream, e4) {
        ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e4);
        TransformStreamErrorWritableAndUnblockWrite(stream, e4);
      }
      function TransformStreamErrorWritableAndUnblockWrite(stream, e4) {
        TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
        WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e4);
        TransformStreamUnblockWrite(stream);
      }
      function TransformStreamUnblockWrite(stream) {
        if (stream._backpressure) {
          TransformStreamSetBackpressure(stream, false);
        }
      }
      function TransformStreamSetBackpressure(stream, backpressure) {
        if (stream._backpressureChangePromise !== void 0) {
          stream._backpressureChangePromise_resolve();
        }
        stream._backpressureChangePromise = newPromise((resolve2) => {
          stream._backpressureChangePromise_resolve = resolve2;
        });
        stream._backpressure = backpressure;
      }
      class TransformStreamDefaultController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
         */
        get desiredSize() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("desiredSize");
          }
          const readableController = this._controlledTransformStream._readable._readableStreamController;
          return ReadableStreamDefaultControllerGetDesiredSize(readableController);
        }
        enqueue(chunk = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("enqueue");
          }
          TransformStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors both the readable side and the writable side of the controlled transform stream, making all future
         * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
         */
        error(reason = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("error");
          }
          TransformStreamDefaultControllerError(this, reason);
        }
        /**
         * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
         * transformer only needs to consume a portion of the chunks written to the writable side.
         */
        terminate() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("terminate");
          }
          TransformStreamDefaultControllerTerminate(this);
        }
      }
      Object.defineProperties(TransformStreamDefaultController.prototype, {
        enqueue: { enumerable: true },
        error: { enumerable: true },
        terminate: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue");
      setFunctionName(TransformStreamDefaultController.prototype.error, "error");
      setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {
          value: "TransformStreamDefaultController",
          configurable: true
        });
      }
      function IsTransformStreamDefaultController(x4) {
        if (!typeIsObject(x4)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x4, "_controlledTransformStream")) {
          return false;
        }
        return x4 instanceof TransformStreamDefaultController;
      }
      function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
        controller._controlledTransformStream = stream;
        stream._transformStreamController = controller;
        controller._transformAlgorithm = transformAlgorithm;
        controller._flushAlgorithm = flushAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        controller._finishPromise = void 0;
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
        const controller = Object.create(TransformStreamDefaultController.prototype);
        let transformAlgorithm;
        let flushAlgorithm;
        let cancelAlgorithm;
        if (transformer.transform !== void 0) {
          transformAlgorithm = (chunk) => transformer.transform(chunk, controller);
        } else {
          transformAlgorithm = (chunk) => {
            try {
              TransformStreamDefaultControllerEnqueue(controller, chunk);
              return promiseResolvedWith(void 0);
            } catch (transformResultE) {
              return promiseRejectedWith(transformResultE);
            }
          };
        }
        if (transformer.flush !== void 0) {
          flushAlgorithm = () => transformer.flush(controller);
        } else {
          flushAlgorithm = () => promiseResolvedWith(void 0);
        }
        if (transformer.cancel !== void 0) {
          cancelAlgorithm = (reason) => transformer.cancel(reason);
        } else {
          cancelAlgorithm = () => promiseResolvedWith(void 0);
        }
        SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
      }
      function TransformStreamDefaultControllerClearAlgorithms(controller) {
        controller._transformAlgorithm = void 0;
        controller._flushAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
      }
      function TransformStreamDefaultControllerEnqueue(controller, chunk) {
        const stream = controller._controlledTransformStream;
        const readableController = stream._readable._readableStreamController;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
          throw new TypeError("Readable side is not in a state that permits enqueue");
        }
        try {
          ReadableStreamDefaultControllerEnqueue(readableController, chunk);
        } catch (e4) {
          TransformStreamErrorWritableAndUnblockWrite(stream, e4);
          throw stream._readable._storedError;
        }
        const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
        if (backpressure !== stream._backpressure) {
          TransformStreamSetBackpressure(stream, true);
        }
      }
      function TransformStreamDefaultControllerError(controller, e4) {
        TransformStreamError(controller._controlledTransformStream, e4);
      }
      function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
        const transformPromise = controller._transformAlgorithm(chunk);
        return transformPromiseWith(transformPromise, void 0, (r4) => {
          TransformStreamError(controller._controlledTransformStream, r4);
          throw r4;
        });
      }
      function TransformStreamDefaultControllerTerminate(controller) {
        const stream = controller._controlledTransformStream;
        const readableController = stream._readable._readableStreamController;
        ReadableStreamDefaultControllerClose(readableController);
        const error2 = new TypeError("TransformStream terminated");
        TransformStreamErrorWritableAndUnblockWrite(stream, error2);
      }
      function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
        const controller = stream._transformStreamController;
        if (stream._backpressure) {
          const backpressureChangePromise = stream._backpressureChangePromise;
          return transformPromiseWith(backpressureChangePromise, () => {
            const writable = stream._writable;
            const state2 = writable._state;
            if (state2 === "erroring") {
              throw writable._storedError;
            }
            return TransformStreamDefaultControllerPerformTransform(controller, chunk);
          });
        }
        return TransformStreamDefaultControllerPerformTransform(controller, chunk);
      }
      function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
        const controller = stream._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream._readable;
        controller._finishPromise = newPromise((resolve2, reject) => {
          controller._finishPromise_resolve = resolve2;
          controller._finishPromise_reject = reject;
        });
        const cancelPromise = controller._cancelAlgorithm(reason);
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(cancelPromise, () => {
          if (readable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, readable._storedError);
          } else {
            ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r4) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r4);
          defaultControllerFinishPromiseReject(controller, r4);
          return null;
        });
        return controller._finishPromise;
      }
      function TransformStreamDefaultSinkCloseAlgorithm(stream) {
        const controller = stream._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream._readable;
        controller._finishPromise = newPromise((resolve2, reject) => {
          controller._finishPromise_resolve = resolve2;
          controller._finishPromise_reject = reject;
        });
        const flushPromise = controller._flushAlgorithm();
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(flushPromise, () => {
          if (readable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, readable._storedError);
          } else {
            ReadableStreamDefaultControllerClose(readable._readableStreamController);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r4) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r4);
          defaultControllerFinishPromiseReject(controller, r4);
          return null;
        });
        return controller._finishPromise;
      }
      function TransformStreamDefaultSourcePullAlgorithm(stream) {
        TransformStreamSetBackpressure(stream, false);
        return stream._backpressureChangePromise;
      }
      function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
        const controller = stream._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const writable = stream._writable;
        controller._finishPromise = newPromise((resolve2, reject) => {
          controller._finishPromise_resolve = resolve2;
          controller._finishPromise_reject = reject;
        });
        const cancelPromise = controller._cancelAlgorithm(reason);
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(cancelPromise, () => {
          if (writable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, writable._storedError);
          } else {
            WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
            TransformStreamUnblockWrite(stream);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r4) => {
          WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r4);
          TransformStreamUnblockWrite(stream);
          defaultControllerFinishPromiseReject(controller, r4);
          return null;
        });
        return controller._finishPromise;
      }
      function defaultControllerBrandCheckException(name) {
        return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
      }
      function defaultControllerFinishPromiseResolve(controller) {
        if (controller._finishPromise_resolve === void 0) {
          return;
        }
        controller._finishPromise_resolve();
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      function defaultControllerFinishPromiseReject(controller, reason) {
        if (controller._finishPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(controller._finishPromise);
        controller._finishPromise_reject(reason);
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      function streamBrandCheckException(name) {
        return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
      }
      exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
      exports3.CountQueuingStrategy = CountQueuingStrategy;
      exports3.ReadableByteStreamController = ReadableByteStreamController;
      exports3.ReadableStream = ReadableStream2;
      exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
      exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
      exports3.ReadableStreamDefaultController = ReadableStreamDefaultController;
      exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
      exports3.TransformStream = TransformStream2;
      exports3.TransformStreamDefaultController = TransformStreamDefaultController;
      exports3.WritableStream = WritableStream;
      exports3.WritableStreamDefaultController = WritableStreamDefaultController;
      exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
    });
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs
var require_streams = __commonJS({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() {
    var POOL_SIZE2 = 65536;
    if (!globalThis.ReadableStream) {
      try {
        const process4 = require("node:process");
        const { emitWarning } = process4;
        try {
          process4.emitWarning = () => {
          };
          Object.assign(globalThis, require("node:stream/web"));
          process4.emitWarning = emitWarning;
        } catch (error2) {
          process4.emitWarning = emitWarning;
          throw error2;
        }
      } catch (error2) {
        Object.assign(globalThis, require_ponyfill_es2018());
      }
    }
    try {
      const { Blob: Blob4 } = require("buffer");
      if (Blob4 && !Blob4.prototype.stream) {
        Blob4.prototype.stream = function name(params) {
          let position = 0;
          const blob = this;
          return new ReadableStream({
            type: "bytes",
            async pull(ctrl) {
              const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2));
              const buffer = await chunk.arrayBuffer();
              position += buffer.byteLength;
              ctrl.enqueue(new Uint8Array(buffer));
              if (position === blob.size) {
                ctrl.close();
              }
            }
          });
        };
      }
    } catch (error2) {
    }
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js
async function* toIterator(parts, clone2 = true) {
  for (const part of parts) {
    if ("stream" in part) {
      yield* (
        /** @type {AsyncIterableIterator<Uint8Array>} */
        part.stream()
      );
    } else if (ArrayBuffer.isView(part)) {
      if (clone2) {
        let position = part.byteOffset;
        const end = part.byteOffset + part.byteLength;
        while (position !== end) {
          const size = Math.min(end - position, POOL_SIZE);
          const chunk = part.buffer.slice(position, position + size);
          position += chunk.byteLength;
          yield new Uint8Array(chunk);
        }
      } else {
        yield part;
      }
    } else {
      let position = 0, b3 = (
        /** @type {Blob} */
        part
      );
      while (position !== b3.size) {
        const chunk = b3.slice(position, Math.min(b3.size, position + POOL_SIZE));
        const buffer = await chunk.arrayBuffer();
        position += buffer.byteLength;
        yield new Uint8Array(buffer);
      }
    }
  }
}
var import_streams, POOL_SIZE, _Blob, Blob3, fetch_blob_default;
var init_fetch_blob = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js"() {
    import_streams = __toESM(require_streams(), 1);
    POOL_SIZE = 65536;
    _Blob = class Blob2 {
      /** @type {Array.<(Blob|Uint8Array)>} */
      #parts = [];
      #type = "";
      #size = 0;
      #endings = "transparent";
      /**
       * The Blob() constructor returns a new Blob object. The content
       * of the blob consists of the concatenation of the values given
       * in the parameter array.
       *
       * @param {*} blobParts
       * @param {{ type?: string, endings?: string }} [options]
       */
      constructor(blobParts = [], options = {}) {
        if (typeof blobParts !== "object" || blobParts === null) {
          throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
        }
        if (typeof blobParts[Symbol.iterator] !== "function") {
          throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
        }
        if (typeof options !== "object" && typeof options !== "function") {
          throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
        }
        if (options === null) options = {};
        const encoder = new TextEncoder();
        for (const element of blobParts) {
          let part;
          if (ArrayBuffer.isView(element)) {
            part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
          } else if (element instanceof ArrayBuffer) {
            part = new Uint8Array(element.slice(0));
          } else if (element instanceof Blob2) {
            part = element;
          } else {
            part = encoder.encode(`${element}`);
          }
          this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
          this.#parts.push(part);
        }
        this.#endings = `${options.endings === void 0 ? "transparent" : options.endings}`;
        const type = options.type === void 0 ? "" : String(options.type);
        this.#type = /^[\x20-\x7E]*$/.test(type) ? type : "";
      }
      /**
       * The Blob interface's size property returns the
       * size of the Blob in bytes.
       */
      get size() {
        return this.#size;
      }
      /**
       * The type property of a Blob object returns the MIME type of the file.
       */
      get type() {
        return this.#type;
      }
      /**
       * The text() method in the Blob interface returns a Promise
       * that resolves with a string containing the contents of
       * the blob, interpreted as UTF-8.
       *
       * @return {Promise<string>}
       */
      async text() {
        const decoder = new TextDecoder();
        let str = "";
        for await (const part of toIterator(this.#parts, false)) {
          str += decoder.decode(part, { stream: true });
        }
        str += decoder.decode();
        return str;
      }
      /**
       * The arrayBuffer() method in the Blob interface returns a
       * Promise that resolves with the contents of the blob as
       * binary data contained in an ArrayBuffer.
       *
       * @return {Promise<ArrayBuffer>}
       */
      async arrayBuffer() {
        const data = new Uint8Array(this.size);
        let offset = 0;
        for await (const chunk of toIterator(this.#parts, false)) {
          data.set(chunk, offset);
          offset += chunk.length;
        }
        return data.buffer;
      }
      stream() {
        const it = toIterator(this.#parts, true);
        return new globalThis.ReadableStream({
          // @ts-ignore
          type: "bytes",
          async pull(ctrl) {
            const chunk = await it.next();
            chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
          },
          async cancel() {
            await it.return();
          }
        });
      }
      /**
       * The Blob interface's slice() method creates and returns a
       * new Blob object which contains data from a subset of the
       * blob on which it's called.
       *
       * @param {number} [start]
       * @param {number} [end]
       * @param {string} [type]
       */
      slice(start = 0, end = this.size, type = "") {
        const { size } = this;
        let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
        let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
        const span = Math.max(relativeEnd - relativeStart, 0);
        const parts = this.#parts;
        const blobParts = [];
        let added = 0;
        for (const part of parts) {
          if (added >= span) {
            break;
          }
          const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size;
          if (relativeStart && size2 <= relativeStart) {
            relativeStart -= size2;
            relativeEnd -= size2;
          } else {
            let chunk;
            if (ArrayBuffer.isView(part)) {
              chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd));
              added += chunk.byteLength;
            } else {
              chunk = part.slice(relativeStart, Math.min(size2, relativeEnd));
              added += chunk.size;
            }
            relativeEnd -= size2;
            blobParts.push(chunk);
            relativeStart = 0;
          }
        }
        const blob = new Blob2([], { type: String(type).toLowerCase() });
        blob.#size = span;
        blob.#parts = blobParts;
        return blob;
      }
      get [Symbol.toStringTag]() {
        return "Blob";
      }
      static [Symbol.hasInstance](object) {
        return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
      }
    };
    Object.defineProperties(_Blob.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Blob3 = _Blob;
    fetch_blob_default = Blob3;
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js
var _File, File3, file_default;
var init_file = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js"() {
    init_fetch_blob();
    _File = class File2 extends fetch_blob_default {
      #lastModified = 0;
      #name = "";
      /**
       * @param {*[]} fileBits
       * @param {string} fileName
       * @param {{lastModified?: number, type?: string}} options
       */
      // @ts-ignore
      constructor(fileBits, fileName, options = {}) {
        if (arguments.length < 2) {
          throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
        }
        super(fileBits, options);
        if (options === null) options = {};
        const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
        if (!Number.isNaN(lastModified)) {
          this.#lastModified = lastModified;
        }
        this.#name = String(fileName);
      }
      get name() {
        return this.#name;
      }
      get lastModified() {
        return this.#lastModified;
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
      static [Symbol.hasInstance](object) {
        return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]);
      }
    };
    File3 = _File;
    file_default = File3;
  }
});

// ../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js
function formDataToBlob(F3, B2 = fetch_blob_default) {
  var b3 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c3 = [], p3 = `--${b3}\r
Content-Disposition: form-data; name="`;
  F3.forEach((v6, n3) => typeof v6 == "string" ? c3.push(p3 + e(n3) + `"\r
\r
${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r
`) : c3.push(p3 + e(n3) + `"; filename="${e(v6.name, 1)}"\r
Content-Type: ${v6.type || "application/octet-stream"}\r
\r
`, v6, "\r\n"));
  c3.push(`--${b3}--`);
  return new B2(c3, { type: "multipart/form-data; boundary=" + b3 });
}
var t, i, h, r, m, f, e, x, FormData;
var init_esm_min = __esm({
  "../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js"() {
    init_fetch_blob();
    init_file();
    ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol);
    r = Math.random;
    m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(",");
    f = (a3, b3, c3) => (a3 += "", /^(Blob|File)$/.test(b3 && b3[t]) ? [(c3 = c3 !== void 0 ? c3 + "" : b3[t] == "File" ? b3.name : "blob", a3), b3.name !== c3 || b3[t] == "blob" ? new file_default([b3], c3, b3) : b3] : [a3, b3 + ""]);
    e = (c3, f5) => (f5 ? c3 : c3.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
    x = (n3, a3, e4) => {
      if (a3.length < e4) {
        throw new TypeError(`Failed to execute '${n3}' on 'FormData': ${e4} arguments required, but only ${a3.length} present.`);
      }
    };
    FormData = class FormData2 {
      #d = [];
      constructor(...a3) {
        if (a3.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`);
      }
      get [t]() {
        return "FormData";
      }
      [i]() {
        return this.entries();
      }
      static [h](o3) {
        return o3 && typeof o3 === "object" && o3[t] === "FormData" && !m.some((m4) => typeof o3[m4] != "function");
      }
      append(...a3) {
        x("append", arguments, 2);
        this.#d.push(f(...a3));
      }
      delete(a3) {
        x("delete", arguments, 1);
        a3 += "";
        this.#d = this.#d.filter(([b3]) => b3 !== a3);
      }
      get(a3) {
        x("get", arguments, 1);
        a3 += "";
        for (var b3 = this.#d, l3 = b3.length, c3 = 0; c3 < l3; c3++) if (b3[c3][0] === a3) return b3[c3][1];
        return null;
      }
      getAll(a3, b3) {
        x("getAll", arguments, 1);
        b3 = [];
        a3 += "";
        this.#d.forEach((c3) => c3[0] === a3 && b3.push(c3[1]));
        return b3;
      }
      has(a3) {
        x("has", arguments, 1);
        a3 += "";
        return this.#d.some((b3) => b3[0] === a3);
      }
      forEach(a3, b3) {
        x("forEach", arguments, 1);
        for (var [c3, d3] of this) a3.call(b3, d3, c3, this);
      }
      set(...a3) {
        x("set", arguments, 2);
        var b3 = [], c3 = true;
        a3 = f(...a3);
        this.#d.forEach((d3) => {
          d3[0] === a3[0] ? c3 && (c3 = !b3.push(a3)) : b3.push(d3);
        });
        c3 && b3.push(a3);
        this.#d = b3;
      }
      *entries() {
        yield* this.#d;
      }
      *keys() {
        for (var [a3] of this) yield a3;
      }
      *values() {
        for (var [, a3] of this) yield a3;
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
var FetchBaseError;
var init_base = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js"() {
    FetchBaseError = class extends Error {
      constructor(message, type) {
        super(message);
        Error.captureStackTrace(this, this.constructor);
        this.type = type;
      }
      get name() {
        return this.constructor.name;
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
var FetchError;
var init_fetch_error = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js"() {
    init_base();
    FetchError = class extends FetchBaseError {
      /**
       * @param  {string} message -      Error message for human
       * @param  {string} [type] -        Error type for machine
       * @param  {SystemError} [systemError] - For Node.js system error
       */
      constructor(message, type, systemError) {
        super(message, type);
        if (systemError) {
          this.code = this.errno = systemError.code;
          this.erroredSysCall = systemError.syscall;
        }
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
var NAME, isURLSearchParameters, isBlob2, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
var init_is = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js"() {
    NAME = Symbol.toStringTag;
    isURLSearchParameters = (object) => {
      return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
    };
    isBlob2 = (object) => {
      return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
    };
    isAbortSignal = (object) => {
      return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
    };
    isDomainOrSubdomain = (destination, original) => {
      const orig = new URL(original).hostname;
      const dest = new URL(destination).hostname;
      return orig === dest || orig.endsWith(`.${dest}`);
    };
    isSameProtocol = (destination, original) => {
      const orig = new URL(original).protocol;
      const dest = new URL(destination).protocol;
      return orig === dest;
    };
  }
});

// ../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js
var require_node_domexception = __commonJS({
  "../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js"(exports2, module2) {
    if (!globalThis.DOMException) {
      try {
        const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer();
        port.postMessage(ab, [ab, ab]);
      } catch (err2) {
        err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor);
      }
    }
    module2.exports = globalThis.DOMException;
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js
var import_node_fs, import_node_domexception, stat;
var init_from = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js"() {
    import_node_fs = require("node:fs");
    import_node_domexception = __toESM(require_node_domexception(), 1);
    init_file();
    init_fetch_blob();
    ({ stat } = import_node_fs.promises);
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js
var multipart_parser_exports = {};
__export(multipart_parser_exports, {
  toFormData: () => toFormData
});
function _fileName(headerValue) {
  const m4 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  if (!m4) {
    return;
  }
  const match2 = m4[2] || m4[3] || "";
  let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#(\d{4});/g, (m5, code) => {
    return String.fromCharCode(code);
  });
  return filename;
}
async function toFormData(Body2, ct) {
  if (!/multipart/i.test(ct)) {
    throw new TypeError("Failed to fetch");
  }
  const m4 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  if (!m4) {
    throw new TypeError("no or bad content-type header, no multipart boundary");
  }
  const parser = new MultipartParser(m4[1] || m4[2]);
  let headerField;
  let headerValue;
  let entryValue;
  let entryName;
  let contentType;
  let filename;
  const entryChunks = [];
  const formData = new FormData();
  const onPartData = (ui8a) => {
    entryValue += decoder.decode(ui8a, { stream: true });
  };
  const appendToFile = (ui8a) => {
    entryChunks.push(ui8a);
  };
  const appendFileToFormData = () => {
    const file = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file);
  };
  const appendEntryToFormData = () => {
    formData.append(entryName, entryValue);
  };
  const decoder = new TextDecoder("utf-8");
  decoder.decode();
  parser.onPartBegin = function() {
    parser.onPartData = onPartData;
    parser.onPartEnd = appendEntryToFormData;
    headerField = "";
    headerValue = "";
    entryValue = "";
    entryName = "";
    contentType = "";
    filename = null;
    entryChunks.length = 0;
  };
  parser.onHeaderField = function(ui8a) {
    headerField += decoder.decode(ui8a, { stream: true });
  };
  parser.onHeaderValue = function(ui8a) {
    headerValue += decoder.decode(ui8a, { stream: true });
  };
  parser.onHeaderEnd = function() {
    headerValue += decoder.decode();
    headerField = headerField.toLowerCase();
    if (headerField === "content-disposition") {
      const m5 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
      if (m5) {
        entryName = m5[2] || m5[3] || "";
      }
      filename = _fileName(headerValue);
      if (filename) {
        parser.onPartData = appendToFile;
        parser.onPartEnd = appendFileToFormData;
      }
    } else if (headerField === "content-type") {
      contentType = headerValue;
    }
    headerValue = "";
    headerField = "";
  };
  for await (const chunk of Body2) {
    parser.write(chunk);
  }
  parser.end();
  return formData;
}
var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser;
var init_multipart_parser = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"() {
    init_from();
    init_esm_min();
    s = 0;
    S = {
      START_BOUNDARY: s++,
      HEADER_FIELD_START: s++,
      HEADER_FIELD: s++,
      HEADER_VALUE_START: s++,
      HEADER_VALUE: s++,
      HEADER_VALUE_ALMOST_DONE: s++,
      HEADERS_ALMOST_DONE: s++,
      PART_DATA_START: s++,
      PART_DATA: s++,
      END: s++
    };
    f2 = 1;
    F = {
      PART_BOUNDARY: f2,
      LAST_BOUNDARY: f2 *= 2
    };
    LF = 10;
    CR = 13;
    SPACE = 32;
    HYPHEN = 45;
    COLON = 58;
    A = 97;
    Z = 122;
    lower = (c3) => c3 | 32;
    noop = () => {
    };
    MultipartParser = class {
      /**
       * @param {string} boundary
       */
      constructor(boundary) {
        this.index = 0;
        this.flags = 0;
        this.onHeaderEnd = noop;
        this.onHeaderField = noop;
        this.onHeadersEnd = noop;
        this.onHeaderValue = noop;
        this.onPartBegin = noop;
        this.onPartData = noop;
        this.onPartEnd = noop;
        this.boundaryChars = {};
        boundary = "\r\n--" + boundary;
        const ui8a = new Uint8Array(boundary.length);
        for (let i4 = 0; i4 < boundary.length; i4++) {
          ui8a[i4] = boundary.charCodeAt(i4);
          this.boundaryChars[ui8a[i4]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i4 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c3;
        let cl;
        const mark = (name) => {
          this[name + "Mark"] = i4;
        };
        const clear = (name) => {
          delete this[name + "Mark"];
        };
        const callback = (callbackSymbol, start, end, ui8a) => {
          if (start === void 0 || start !== end) {
            this[callbackSymbol](ui8a && ui8a.subarray(start, end));
          }
        };
        const dataCallback = (name, clear2) => {
          const markSymbol = name + "Mark";
          if (!(markSymbol in this)) {
            return;
          }
          if (clear2) {
            callback(name, this[markSymbol], i4, data);
            delete this[markSymbol];
          } else {
            callback(name, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        };
        for (i4 = 0; i4 < length_; i4++) {
          c3 = data[i4];
          switch (state2) {
            case S.START_BOUNDARY:
              if (index6 === boundary.length - 2) {
                if (c3 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else if (c3 !== CR) {
                  return;
                }
                index6++;
                break;
              } else if (index6 - 1 === boundary.length - 2) {
                if (flags & F.LAST_BOUNDARY && c3 === HYPHEN) {
                  state2 = S.END;
                  flags = 0;
                } else if (!(flags & F.LAST_BOUNDARY) && c3 === LF) {
                  index6 = 0;
                  callback("onPartBegin");
                  state2 = S.HEADER_FIELD_START;
                } else {
                  return;
                }
                break;
              }
              if (c3 !== boundary[index6 + 2]) {
                index6 = -2;
              }
              if (c3 === boundary[index6 + 2]) {
                index6++;
              }
              break;
            case S.HEADER_FIELD_START:
              state2 = S.HEADER_FIELD;
              mark("onHeaderField");
              index6 = 0;
            // falls through
            case S.HEADER_FIELD:
              if (c3 === CR) {
                clear("onHeaderField");
                state2 = S.HEADERS_ALMOST_DONE;
                break;
              }
              index6++;
              if (c3 === HYPHEN) {
                break;
              }
              if (c3 === COLON) {
                if (index6 === 1) {
                  return;
                }
                dataCallback("onHeaderField", true);
                state2 = S.HEADER_VALUE_START;
                break;
              }
              cl = lower(c3);
              if (cl < A || cl > Z) {
                return;
              }
              break;
            case S.HEADER_VALUE_START:
              if (c3 === SPACE) {
                break;
              }
              mark("onHeaderValue");
              state2 = S.HEADER_VALUE;
            // falls through
            case S.HEADER_VALUE:
              if (c3 === CR) {
                dataCallback("onHeaderValue", true);
                callback("onHeaderEnd");
                state2 = S.HEADER_VALUE_ALMOST_DONE;
              }
              break;
            case S.HEADER_VALUE_ALMOST_DONE:
              if (c3 !== LF) {
                return;
              }
              state2 = S.HEADER_FIELD_START;
              break;
            case S.HEADERS_ALMOST_DONE:
              if (c3 !== LF) {
                return;
              }
              callback("onHeadersEnd");
              state2 = S.PART_DATA_START;
              break;
            case S.PART_DATA_START:
              state2 = S.PART_DATA;
              mark("onPartData");
            // falls through
            case S.PART_DATA:
              previousIndex = index6;
              if (index6 === 0) {
                i4 += boundaryEnd;
                while (i4 < bufferLength && !(data[i4] in boundaryChars)) {
                  i4 += boundaryLength;
                }
                i4 -= boundaryEnd;
                c3 = data[i4];
              }
              if (index6 < boundary.length) {
                if (boundary[index6] === c3) {
                  if (index6 === 0) {
                    dataCallback("onPartData", true);
                  }
                  index6++;
                } else {
                  index6 = 0;
                }
              } else if (index6 === boundary.length) {
                index6++;
                if (c3 === CR) {
                  flags |= F.PART_BOUNDARY;
                } else if (c3 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else {
                  index6 = 0;
                }
              } else if (index6 - 1 === boundary.length) {
                if (flags & F.PART_BOUNDARY) {
                  index6 = 0;
                  if (c3 === LF) {
                    flags &= ~F.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state2 = S.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags & F.LAST_BOUNDARY) {
                  if (c3 === HYPHEN) {
                    callback("onPartEnd");
                    state2 = S.END;
                    flags = 0;
                  } else {
                    index6 = 0;
                  }
                } else {
                  index6 = 0;
                }
              }
              if (index6 > 0) {
                lookbehind[index6 - 1] = c3;
              } else if (previousIndex > 0) {
                const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
                callback("onPartData", 0, previousIndex, _lookbehind);
                previousIndex = 0;
                mark("onPartData");
                i4--;
              }
              break;
            case S.END:
              break;
            default:
              throw new Error(`Unexpected state entered: ${state2}`);
          }
        }
        dataCallback("onHeaderField");
        dataCallback("onHeaderValue");
        dataCallback("onPartData");
        this.index = index6;
        this.state = state2;
        this.flags = flags;
      }
      end() {
        if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) {
          this.onPartEnd();
        } else if (this.state !== S.END) {
          throw new Error("MultipartParser.end(): stream ended unexpectedly");
        }
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
async function consumeBody(data) {
  if (data[INTERNALS].disturbed) {
    throw new TypeError(`body used already for: ${data.url}`);
  }
  data[INTERNALS].disturbed = true;
  if (data[INTERNALS].error) {
    throw data[INTERNALS].error;
  }
  const { body } = data;
  if (body === null) {
    return import_node_buffer.Buffer.alloc(0);
  }
  if (!(body instanceof import_node_stream.default)) {
    return import_node_buffer.Buffer.alloc(0);
  }
  const accum = [];
  let accumBytes = 0;
  try {
    for await (const chunk of body) {
      if (data.size > 0 && accumBytes + chunk.length > data.size) {
        const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body.destroy(error2);
        throw error2;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error2) {
    const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
    throw error_;
  }
  if (body.readableEnded === true || body._readableState.ended === true) {
    try {
      if (accum.every((c3) => typeof c3 === "string")) {
        return import_node_buffer.Buffer.from(accum.join(""));
      }
      return import_node_buffer.Buffer.concat(accum, accumBytes);
    } catch (error2) {
      throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
    }
  } else {
    throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
  }
}
var import_node_stream, import_node_util, import_node_buffer, pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
var init_body = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() {
    import_node_stream = __toESM(require("node:stream"), 1);
    import_node_util = require("node:util");
    import_node_buffer = require("node:buffer");
    init_fetch_blob();
    init_esm_min();
    init_fetch_error();
    init_base();
    init_is();
    pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline);
    INTERNALS = Symbol("Body internals");
    Body = class {
      constructor(body, {
        size = 0
      } = {}) {
        let boundary = null;
        if (body === null) {
          body = null;
        } else if (isURLSearchParameters(body)) {
          body = import_node_buffer.Buffer.from(body.toString());
        } else if (isBlob2(body)) {
        } else if (import_node_buffer.Buffer.isBuffer(body)) {
        } else if (import_node_util.types.isAnyArrayBuffer(body)) {
          body = import_node_buffer.Buffer.from(body);
        } else if (ArrayBuffer.isView(body)) {
          body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength);
        } else if (body instanceof import_node_stream.default) {
        } else if (body instanceof FormData) {
          body = formDataToBlob(body);
          boundary = body.type.split("=")[1];
        } else {
          body = import_node_buffer.Buffer.from(String(body));
        }
        let stream = body;
        if (import_node_buffer.Buffer.isBuffer(body)) {
          stream = import_node_stream.default.Readable.from(body);
        } else if (isBlob2(body)) {
          stream = import_node_stream.default.Readable.from(body.stream());
        }
        this[INTERNALS] = {
          body,
          stream,
          boundary,
          disturbed: false,
          error: null
        };
        this.size = size;
        if (body instanceof import_node_stream.default) {
          body.on("error", (error_) => {
            const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS].error = error2;
          });
        }
      }
      get body() {
        return this[INTERNALS].stream;
      }
      get bodyUsed() {
        return this[INTERNALS].disturbed;
      }
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      async arrayBuffer() {
        const { buffer, byteOffset, byteLength } = await consumeBody(this);
        return buffer.slice(byteOffset, byteOffset + byteLength);
      }
      async formData() {
        const ct = this.headers.get("content-type");
        if (ct.startsWith("application/x-www-form-urlencoded")) {
          const formData = new FormData();
          const parameters = new URLSearchParams(await this.text());
          for (const [name, value] of parameters) {
            formData.append(name, value);
          }
          return formData;
        }
        const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports));
        return toFormData2(this.body, ct);
      }
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      async blob() {
        const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
        const buf = await this.arrayBuffer();
        return new fetch_blob_default([buf], {
          type: ct
        });
      }
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      async json() {
        const text = await this.text();
        return JSON.parse(text);
      }
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      async text() {
        const buffer = await consumeBody(this);
        return new TextDecoder().decode(buffer);
      }
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody(this);
      }
    };
    Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
    Object.defineProperties(Body.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true },
      data: { get: (0, import_node_util.deprecate)(
        () => {
        },
        "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
        "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
      ) }
    });
    clone = (instance, highWaterMark) => {
      let p1;
      let p22;
      let { body } = instance[INTERNALS];
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") {
        p1 = new import_node_stream.PassThrough({ highWaterMark });
        p22 = new import_node_stream.PassThrough({ highWaterMark });
        body.pipe(p1);
        body.pipe(p22);
        instance[INTERNALS].stream = p1;
        body = p22;
      }
      return body;
    };
    getNonSpecFormDataBoundary = (0, import_node_util.deprecate)(
      (body) => body.getBoundary(),
      "form-data doesn't follow the spec and requires special treatment. Use alternative package",
      "https://github.com/node-fetch/node-fetch/issues/1167"
    );
    extractContentType = (body, request) => {
      if (body === null) {
        return null;
      }
      if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob2(body)) {
        return body.type || null;
      }
      if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
        return null;
      }
      if (body instanceof FormData) {
        return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
      }
      if (body && typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
      }
      if (body instanceof import_node_stream.default) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    };
    getTotalBytes = (request) => {
      const { body } = request[INTERNALS];
      if (body === null) {
        return 0;
      }
      if (isBlob2(body)) {
        return body.size;
      }
      if (import_node_buffer.Buffer.isBuffer(body)) {
        return body.length;
      }
      if (body && typeof body.getLengthSync === "function") {
        return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
      }
      return null;
    };
    writeToStream = async (dest, { body }) => {
      if (body === null) {
        dest.end();
      } else {
        await pipeline(body, dest);
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
function fromRawHeaders(headers = []) {
  return new Headers2(
    headers.reduce((result, value, index6, array2) => {
      if (index6 % 2 === 0) {
        result.push(array2.slice(index6, index6 + 2));
      }
      return result;
    }, []).filter(([name, value]) => {
      try {
        validateHeaderName(name);
        validateHeaderValue(name, String(value));
        return true;
      } catch {
        return false;
      }
    })
  );
}
var import_node_util2, import_node_http, validateHeaderName, validateHeaderValue, Headers2;
var init_headers = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() {
    import_node_util2 = require("node:util");
    import_node_http = __toESM(require("node:http"), 1);
    validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
        const error2 = new TypeError(`Header name must be a valid HTTP token [${name}]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error2;
      }
    };
    validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error2 = new TypeError(`Invalid character in header content ["${name}"]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
        throw error2;
      }
    };
    Headers2 = class _Headers extends URLSearchParams {
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init2) {
        let result = [];
        if (init2 instanceof _Headers) {
          const raw2 = init2.raw();
          for (const [name, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name, value]));
          }
        } else if (init2 == null) {
        } else if (typeof init2 === "object" && !import_node_util2.types.isBoxedPrimitive(init2)) {
          const method = init2[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init2));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init2].map((pair) => {
              if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) {
                throw new TypeError("Each header pair must be an iterable object");
              }
              return [...pair];
            }).map((pair) => {
              if (pair.length !== 2) {
                throw new TypeError("Each header pair must be a name/value tuple");
              }
              return [...pair];
            });
          }
        } else {
          throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
        }
        result = result.length > 0 ? result.map(([name, value]) => {
          validateHeaderName(name);
          validateHeaderValue(name, String(value));
          return [String(name).toLowerCase(), String(value)];
        }) : void 0;
        super(result);
        return new Proxy(this, {
          get(target, p3, receiver) {
            switch (p3) {
              case "append":
              case "set":
                return (name, value) => {
                  validateHeaderName(name);
                  validateHeaderValue(name, String(value));
                  return URLSearchParams.prototype[p3].call(
                    target,
                    String(name).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name) => {
                  validateHeaderName(name);
                  return URLSearchParams.prototype[p3].call(
                    target,
                    String(name).toLowerCase()
                  );
                };
              case "keys":
                return () => {
                  target.sort();
                  return new Set(URLSearchParams.prototype.keys.call(target)).keys();
                };
              default:
                return Reflect.get(target, p3, receiver);
            }
          }
        });
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
      toString() {
        return Object.prototype.toString.call(this);
      }
      get(name) {
        const values = this.getAll(name);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name), name, this]);
        }
      }
      *values() {
        for (const name of this.keys()) {
          yield this.get(name);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name of this.keys()) {
          yield [name, this.get(name)];
        }
      }
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * Node-fetch non-spec method
       * returning all headers and their values as array
       * @returns {Record<string, string[]>}
       */
      raw() {
        return [...this.keys()].reduce((result, key) => {
          result[key] = this.getAll(key);
          return result;
        }, {});
      }
      /**
       * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
       */
      [Symbol.for("nodejs.util.inspect.custom")]() {
        return [...this.keys()].reduce((result, key) => {
          const values = this.getAll(key);
          if (key === "host") {
            result[key] = values[0];
          } else {
            result[key] = values.length > 1 ? values : values[0];
          }
          return result;
        }, {});
      }
    };
    Object.defineProperties(
      Headers2.prototype,
      ["get", "entries", "forEach", "values"].reduce((result, property) => {
        result[property] = { enumerable: true };
        return result;
      }, {})
    );
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
var redirectStatus, isRedirect;
var init_is_redirect = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js"() {
    redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
    isRedirect = (code) => {
      return redirectStatus.has(code);
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
var INTERNALS2, Response2;
var init_response = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() {
    init_headers();
    init_body();
    init_is_redirect();
    INTERNALS2 = Symbol("Response internals");
    Response2 = class _Response2 extends Body {
      constructor(body = null, options = {}) {
        super(body, options);
        const status = options.status != null ? options.status : 200;
        const headers = new Headers2(options.headers);
        if (body !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType(body, this);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        this[INTERNALS2] = {
          type: "default",
          url: options.url,
          status,
          statusText: options.statusText || "",
          headers,
          counter: options.counter,
          highWaterMark: options.highWaterMark
        };
      }
      get type() {
        return this[INTERNALS2].type;
      }
      get url() {
        return this[INTERNALS2].url || "";
      }
      get status() {
        return this[INTERNALS2].status;
      }
      /**
       * Convenience property representing if the request ended normally
       */
      get ok() {
        return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
      }
      get redirected() {
        return this[INTERNALS2].counter > 0;
      }
      get statusText() {
        return this[INTERNALS2].statusText;
      }
      get headers() {
        return this[INTERNALS2].headers;
      }
      get highWaterMark() {
        return this[INTERNALS2].highWaterMark;
      }
      /**
       * Clone this response
       *
       * @return  Response
       */
      clone() {
        return new _Response2(clone(this, this.highWaterMark), {
          type: this.type,
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected,
          size: this.size,
          highWaterMark: this.highWaterMark
        });
      }
      /**
       * @param {string} url    The URL that the new response is to originate from.
       * @param {number} status An optional status code for the response (e.g., 302.)
       * @returns {Response}    A Response object.
       */
      static redirect(url, status = 302) {
        if (!isRedirect(status)) {
          throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
        }
        return new _Response2(null, {
          headers: {
            location: new URL(url).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response2(null, { status: 0, statusText: "" });
        response[INTERNALS2].type = "error";
        return response;
      }
      static json(data = void 0, init2 = {}) {
        const body = JSON.stringify(data);
        if (body === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers2(init2 && init2.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response2(body, {
          ...init2,
          headers
        });
      }
      get [Symbol.toStringTag]() {
        return "Response";
      }
    };
    Object.defineProperties(Response2.prototype, {
      type: { enumerable: true },
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
var getSearch;
var init_get_search = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js"() {
    getSearch = (parsedURL) => {
      if (parsedURL.search) {
        return parsedURL.search;
      }
      const lastOffset = parsedURL.href.length - 1;
      const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
      return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
function stripURLForUseAsAReferrer(url, originOnly = false) {
  if (url == null) {
    return "no-referrer";
  }
  url = new URL(url);
  if (/^(about|blob|data):$/.test(url.protocol)) {
    return "no-referrer";
  }
  url.username = "";
  url.password = "";
  url.hash = "";
  if (originOnly) {
    url.pathname = "";
    url.search = "";
  }
  return url;
}
function validateReferrerPolicy(referrerPolicy) {
  if (!ReferrerPolicy.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy(url) {
  if (/^(http|ws)s:$/.test(url.protocol)) {
    return true;
  }
  const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
  const hostIPVersion = (0, import_node_net.isIP)(hostIp);
  if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
    return true;
  }
  if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
    return true;
  }
  if (url.host === "localhost" || url.host.endsWith(".localhost")) {
    return false;
  }
  if (url.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy(url) {
  if (/^about:(blank|srcdoc)$/.test(url)) {
    return true;
  }
  if (url.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy(url);
}
function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) {
  if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
    return null;
  }
  const policy5 = request.referrerPolicy;
  if (request.referrer === "about:client") {
    return "no-referrer";
  }
  const referrerSource = request.referrer;
  let referrerURL = stripURLForUseAsAReferrer(referrerSource);
  let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
  if (referrerURL.toString().length > 4096) {
    referrerURL = referrerOrigin;
  }
  if (referrerURLCallback) {
    referrerURL = referrerURLCallback(referrerURL);
  }
  if (referrerOriginCallback) {
    referrerOrigin = referrerOriginCallback(referrerOrigin);
  }
  const currentURL = new URL(request.url);
  switch (policy5) {
    case "no-referrer":
      return "no-referrer";
    case "origin":
      return referrerOrigin;
    case "unsafe-url":
      return referrerURL;
    case "strict-origin":
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin.toString();
    case "strict-origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin;
    case "same-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return "no-referrer";
    case "origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return referrerOrigin;
    case "no-referrer-when-downgrade":
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerURL;
    default:
      throw new TypeError(`Invalid referrerPolicy: ${policy5}`);
  }
}
function parseReferrerPolicyFromHeader(headers) {
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  let policy5 = "";
  for (const token of policyTokens) {
    if (token && ReferrerPolicy.has(token)) {
      policy5 = token;
    }
  }
  return policy5;
}
var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
var init_referrer = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() {
    import_node_net = require("node:net");
    ReferrerPolicy = /* @__PURE__ */ new Set([
      "",
      "no-referrer",
      "no-referrer-when-downgrade",
      "same-origin",
      "origin",
      "strict-origin",
      "origin-when-cross-origin",
      "strict-origin-when-cross-origin",
      "unsafe-url"
    ]);
    DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
var import_node_url, import_node_util3, INTERNALS3, isRequest, doBadDataWarn, Request2, getNodeRequestOptions;
var init_request = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() {
    import_node_url = require("node:url");
    import_node_util3 = require("node:util");
    init_headers();
    init_body();
    init_is();
    init_get_search();
    init_referrer();
    INTERNALS3 = Symbol("Request internals");
    isRequest = (object) => {
      return typeof object === "object" && typeof object[INTERNALS3] === "object";
    };
    doBadDataWarn = (0, import_node_util3.deprecate)(
      () => {
      },
      ".data is not a valid RequestInit property, use .body instead",
      "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
    );
    Request2 = class _Request extends Body {
      constructor(input, init2 = {}) {
        let parsedURL;
        if (isRequest(input)) {
          parsedURL = new URL(input.url);
        } else {
          parsedURL = new URL(input);
          input = {};
        }
        if (parsedURL.username !== "" || parsedURL.password !== "") {
          throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
        }
        let method = init2.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest(init2) && "data" in init2) {
          doBadDataWarn();
        }
        if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
        super(inputBody, {
          size: init2.size || input.size || 0
        });
        const headers = new Headers2(init2.headers || input.headers || {});
        if (inputBody !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType(inputBody, this);
          if (contentType) {
            headers.set("Content-Type", contentType);
          }
        }
        let signal = isRequest(input) ? input.signal : null;
        if ("signal" in init2) {
          signal = init2.signal;
        }
        if (signal != null && !isAbortSignal(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
        }
        let referrer = init2.referrer == null ? input.referrer : init2.referrer;
        if (referrer === "") {
          referrer = "no-referrer";
        } else if (referrer) {
          const parsedReferrer = new URL(referrer);
          referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
        } else {
          referrer = void 0;
        }
        this[INTERNALS3] = {
          method,
          redirect: init2.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
        this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
        this.counter = init2.counter || input.counter || 0;
        this.agent = init2.agent || input.agent;
        this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init2.referrerPolicy || input.referrerPolicy || "";
      }
      /** @returns {string} */
      get method() {
        return this[INTERNALS3].method;
      }
      /** @returns {string} */
      get url() {
        return (0, import_node_url.format)(this[INTERNALS3].parsedURL);
      }
      /** @returns {Headers} */
      get headers() {
        return this[INTERNALS3].headers;
      }
      get redirect() {
        return this[INTERNALS3].redirect;
      }
      /** @returns {AbortSignal} */
      get signal() {
        return this[INTERNALS3].signal;
      }
      // https://fetch.spec.whatwg.org/#dom-request-referrer
      get referrer() {
        if (this[INTERNALS3].referrer === "no-referrer") {
          return "";
        }
        if (this[INTERNALS3].referrer === "client") {
          return "about:client";
        }
        if (this[INTERNALS3].referrer) {
          return this[INTERNALS3].referrer.toString();
        }
        return void 0;
      }
      get referrerPolicy() {
        return this[INTERNALS3].referrerPolicy;
      }
      set referrerPolicy(referrerPolicy) {
        this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
      }
      /**
       * Clone this request
       *
       * @return  Request
       */
      clone() {
        return new _Request(this);
      }
      get [Symbol.toStringTag]() {
        return "Request";
      }
    };
    Object.defineProperties(Request2.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true },
      referrer: { enumerable: true },
      referrerPolicy: { enumerable: true }
    });
    getNodeRequestOptions = (request) => {
      const { parsedURL } = request[INTERNALS3];
      const headers = new Headers2(request[INTERNALS3].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      let contentLengthValue = null;
      if (request.body === null && /^(post|put)$/i.test(request.method)) {
        contentLengthValue = "0";
      }
      if (request.body !== null) {
        const totalBytes = getTotalBytes(request);
        if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (request.referrerPolicy === "") {
        request.referrerPolicy = DEFAULT_REFERRER_POLICY;
      }
      if (request.referrer && request.referrer !== "no-referrer") {
        request[INTERNALS3].referrer = determineRequestsReferrer(request);
      } else {
        request[INTERNALS3].referrer = "no-referrer";
      }
      if (request[INTERNALS3].referrer instanceof URL) {
        headers.set("Referer", request.referrer);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch");
      }
      if (request.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip, deflate, br");
      }
      let { agent } = request;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      const search = getSearch(parsedURL);
      const options = {
        // Overwrite search to retain trailing ? (issue #776)
        path: parsedURL.pathname + search,
        // The following options are not expressed in the URL
        method: request.method,
        headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
        insecureHTTPParser: request.insecureHTTPParser,
        agent
      };
      return {
        /** @type {URL} */
        parsedURL,
        options
      };
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js
var AbortError;
var init_abort_error = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js"() {
    init_base();
    AbortError = class extends FetchBaseError {
      constructor(message, type = "aborted") {
        super(message, type);
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
async function fetch2(url, options_) {
  return new Promise((resolve2, reject) => {
    const request = new Request2(url, options_);
    const { parsedURL, options } = getNodeRequestOptions(request);
    if (!supportedSchemas.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
    }
    if (parsedURL.protocol === "data:") {
      const data = dist_default(request.url);
      const response2 = new Response2(data, { headers: { "Content-Type": data.typeFull } });
      resolve2(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request;
    const { signal } = request;
    let response = null;
    const abort = () => {
      const error2 = new AbortError("The operation was aborted.");
      reject(error2);
      if (request.body && request.body instanceof import_node_stream2.default.Readable) {
        request.body.destroy(error2);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error2);
    };
    if (signal && signal.aborted) {
      abort();
      return;
    }
    const abortAndFinalize = () => {
      abort();
      finalize();
    };
    const request_ = send(parsedURL.toString(), options);
    if (signal) {
      signal.addEventListener("abort", abortAndFinalize);
    }
    const finalize = () => {
      request_.abort();
      if (signal) {
        signal.removeEventListener("abort", abortAndFinalize);
      }
    };
    request_.on("error", (error2) => {
      reject(new FetchError(`request to ${request.url} failed, reason: ${error2.message}`, "system", error2));
      finalize();
    });
    fixResponseChunkedTransferBadEnding(request_, (error2) => {
      if (response && response.body) {
        response.body.destroy(error2);
      }
    });
    if (process.version < "v14") {
      request_.on("socket", (s4) => {
        let endedWithEventsCount;
        s4.prependListener("end", () => {
          endedWithEventsCount = s4._eventsCount;
        });
        s4.prependListener("close", (hadError) => {
          if (response && endedWithEventsCount < s4._eventsCount && !hadError) {
            const error2 = new Error("Premature close");
            error2.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error2);
          }
        });
      });
    }
    request_.on("response", (response_) => {
      request_.setTimeout(0);
      const headers = fromRawHeaders(response_.rawHeaders);
      if (isRedirect(response_.statusCode)) {
        const location = headers.get("Location");
        let locationURL = null;
        try {
          locationURL = location === null ? null : new URL(location, request.url);
        } catch {
          if (request.redirect !== "manual") {
            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
            finalize();
            return;
          }
        }
        switch (request.redirect) {
          case "error":
            reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
            finalize();
            return;
          case "manual":
            break;
          case "follow": {
            if (locationURL === null) {
              break;
            }
            if (request.counter >= request.follow) {
              reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
              finalize();
              return;
            }
            const requestOptions = {
              headers: new Headers2(request.headers),
              follow: request.follow,
              counter: request.counter + 1,
              agent: request.agent,
              compress: request.compress,
              method: request.method,
              body: clone(request),
              signal: request.signal,
              size: request.size,
              referrer: request.referrer,
              referrerPolicy: request.referrerPolicy
            };
            if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
              for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name);
              }
            }
            if (response_.statusCode !== 303 && request.body && options_.body instanceof import_node_stream2.default.Readable) {
              reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
              finalize();
              return;
            }
            if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
              requestOptions.method = "GET";
              requestOptions.body = void 0;
              requestOptions.headers.delete("content-length");
            }
            const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
            if (responseReferrerPolicy) {
              requestOptions.referrerPolicy = responseReferrerPolicy;
            }
            resolve2(fetch2(new Request2(locationURL, requestOptions)));
            finalize();
            return;
          }
          default:
            return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
        }
      }
      if (signal) {
        response_.once("end", () => {
          signal.removeEventListener("abort", abortAndFinalize);
        });
      }
      let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
        if (error2) {
          reject(error2);
        }
      });
      if (process.version < "v12.10") {
        response_.on("aborted", abortAndFinalize);
      }
      const responseOptions = {
        url: request.url,
        status: response_.statusCode,
        statusText: response_.statusMessage,
        headers,
        size: request.size,
        counter: request.counter,
        highWaterMark: request.highWaterMark
      };
      const codings = headers.get("Content-Encoding");
      if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
        response = new Response2(body, responseOptions);
        resolve2(response);
        return;
      }
      const zlibOptions = {
        flush: import_node_zlib.default.Z_SYNC_FLUSH,
        finishFlush: import_node_zlib.default.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve2(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          } else {
            body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          }
          response = new Response2(body, responseOptions);
          resolve2(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response2(body, responseOptions);
            resolve2(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve2(response);
        return;
      }
      response = new Response2(body, responseOptions);
      resolve2(response);
    });
    writeToStream(request_, request).catch(reject);
  });
}
function fixResponseChunkedTransferBadEnding(request, errorCallback) {
  const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n");
  let isChunkedTransfer = false;
  let properLastChunkReceived = false;
  let previousChunk;
  request.on("response", (response) => {
    const { headers } = response;
    isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  });
  request.on("socket", (socket) => {
    const onSocketClose = () => {
      if (isChunkedTransfer && !properLastChunkReceived) {
        const error2 = new Error("Premature close");
        error2.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error2);
      }
    };
    const onData = (buf) => {
      properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;
      if (!properLastChunkReceived && previousChunk) {
        properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
      }
      previousChunk = buf;
    };
    socket.prependListener("close", onSocketClose);
    socket.on("data", onData);
    request.on("close", () => {
      socket.removeListener("close", onSocketClose);
      socket.removeListener("data", onData);
    });
  });
}
var import_node_http2, import_node_https, import_node_zlib, import_node_stream2, import_node_buffer2, supportedSchemas;
var init_src = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() {
    import_node_http2 = __toESM(require("node:http"), 1);
    import_node_https = __toESM(require("node:https"), 1);
    import_node_zlib = __toESM(require("node:zlib"), 1);
    import_node_stream2 = __toESM(require("node:stream"), 1);
    import_node_buffer2 = require("node:buffer");
    init_dist();
    init_body();
    init_response();
    init_headers();
    init_request();
    init_fetch_error();
    init_abort_error();
    init_is_redirect();
    init_esm_min();
    init_is();
    init_referrer();
    init_from();
    supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
  }
});

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

// ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
var require_node_gyp_build = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
    var fs7 = require("fs");
    var path4 = require("path");
    var os3 = require("os");
    var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    var vars = process.config && process.config.variables || {};
    var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
    var abi = process.versions.modules;
    var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
    var arch = process.env.npm_config_arch || os3.arch();
    var platform = process.env.npm_config_platform || os3.platform();
    var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
    var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
    var uv = (process.versions.uv || "").split(".")[0];
    module2.exports = load;
    function load(dir) {
      return runtimeRequire(load.resolve(dir));
    }
    load.resolve = load.path = function(dir) {
      dir = path4.resolve(dir || ".");
      try {
        var name = runtimeRequire(path4.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
        if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
      } catch (err2) {
      }
      if (!prebuildsOnly) {
        var release = getFirst(path4.join(dir, "build/Release"), matchBuild);
        if (release) return release;
        var debug = getFirst(path4.join(dir, "build/Debug"), matchBuild);
        if (debug) return debug;
      }
      var prebuild = resolve2(dir);
      if (prebuild) return prebuild;
      var nearby = resolve2(path4.dirname(process.execPath));
      if (nearby) return nearby;
      var target = [
        "platform=" + platform,
        "arch=" + arch,
        "runtime=" + runtime,
        "abi=" + abi,
        "uv=" + uv,
        armv ? "armv=" + armv : "",
        "libc=" + libc,
        "node=" + process.versions.node,
        process.versions.electron ? "electron=" + process.versions.electron : "",
        typeof __webpack_require__ === "function" ? "webpack=true" : ""
        // eslint-disable-line
      ].filter(Boolean).join(" ");
      throw new Error("No native build was found for " + target + "\n    loaded from: " + dir + "\n");
      function resolve2(dir2) {
        var tuples = readdirSync2(path4.join(dir2, "prebuilds")).map(parseTuple);
        var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
        if (!tuple) return;
        var prebuilds = path4.join(dir2, "prebuilds", tuple.name);
        var parsed = readdirSync2(prebuilds).map(parseTags);
        var candidates = parsed.filter(matchTags(runtime, abi));
        var winner = candidates.sort(compareTags(runtime))[0];
        if (winner) return path4.join(prebuilds, winner.file);
      }
    };
    function readdirSync2(dir) {
      try {
        return fs7.readdirSync(dir);
      } catch (err2) {
        return [];
      }
    }
    function getFirst(dir, filter2) {
      var files = readdirSync2(dir).filter(filter2);
      return files[0] && path4.join(dir, files[0]);
    }
    function matchBuild(name) {
      return /\.node$/.test(name);
    }
    function parseTuple(name) {
      var arr = name.split("-");
      if (arr.length !== 2) return;
      var platform2 = arr[0];
      var architectures = arr[1].split("+");
      if (!platform2) return;
      if (!architectures.length) return;
      if (!architectures.every(Boolean)) return;
      return { name, platform: platform2, architectures };
    }
    function matchTuple(platform2, arch2) {
      return function(tuple) {
        if (tuple == null) return false;
        if (tuple.platform !== platform2) return false;
        return tuple.architectures.includes(arch2);
      };
    }
    function compareTuples(a3, b3) {
      return a3.architectures.length - b3.architectures.length;
    }
    function parseTags(file) {
      var arr = file.split(".");
      var extension = arr.pop();
      var tags = { file, specificity: 0 };
      if (extension !== "node") return;
      for (var i4 = 0; i4 < arr.length; i4++) {
        var tag = arr[i4];
        if (tag === "node" || tag === "electron" || tag === "node-webkit") {
          tags.runtime = tag;
        } else if (tag === "napi") {
          tags.napi = true;
        } else if (tag.slice(0, 3) === "abi") {
          tags.abi = tag.slice(3);
        } else if (tag.slice(0, 2) === "uv") {
          tags.uv = tag.slice(2);
        } else if (tag.slice(0, 4) === "armv") {
          tags.armv = tag.slice(4);
        } else if (tag === "glibc" || tag === "musl") {
          tags.libc = tag;
        } else {
          continue;
        }
        tags.specificity++;
      }
      return tags;
    }
    function matchTags(runtime2, abi2) {
      return function(tags) {
        if (tags == null) return false;
        if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
        if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
        if (tags.uv && tags.uv !== uv) return false;
        if (tags.armv && tags.armv !== armv) return false;
        if (tags.libc && tags.libc !== libc) return false;
        return true;
      };
    }
    function runtimeAgnostic(tags) {
      return tags.runtime === "node" && tags.napi;
    }
    function compareTags(runtime2) {
      return function(a3, b3) {
        if (a3.runtime !== b3.runtime) {
          return a3.runtime === runtime2 ? -1 : 1;
        } else if (a3.abi !== b3.abi) {
          return a3.abi ? -1 : 1;
        } else if (a3.specificity !== b3.specificity) {
          return a3.specificity > b3.specificity ? -1 : 1;
        } else {
          return 0;
        }
      };
    }
    function isNwjs() {
      return !!(process.versions && process.versions.nw);
    }
    function isElectron() {
      if (process.versions && process.versions.electron) return true;
      if (process.env.ELECTRON_RUN_AS_NODE) return true;
      return typeof window !== "undefined" && window.process && window.process.type === "renderer";
    }
    function isAlpine(platform2) {
      return platform2 === "linux" && fs7.existsSync("/etc/alpine-release");
    }
    load.parseTags = parseTags;
    load.matchTags = matchTags;
    load.compareTags = compareTags;
    load.parseTuple = parseTuple;
    load.matchTuple = matchTuple;
    load.compareTuples = compareTuples;
  }
});

// ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
var require_node_gyp_build2 = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports2, module2) {
    var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    if (typeof runtimeRequire.addon === "function") {
      module2.exports = runtimeRequire.addon.bind(runtimeRequire);
    } else {
      module2.exports = require_node_gyp_build();
    }
  }
});

// ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js
var require_fallback = __commonJS({
  "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js"(exports2, module2) {
    "use strict";
    var mask = (source, mask2, output, offset, length) => {
      for (var i4 = 0; i4 < length; i4++) {
        output[offset + i4] = source[i4] ^ mask2[i4 & 3];
      }
    };
    var unmask = (buffer, mask2) => {
      const length = buffer.length;
      for (var i4 = 0; i4 < length; i4++) {
        buffer[i4] ^= mask2[i4 & 3];
      }
    };
    module2.exports = { mask, unmask };
  }
});

// ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js
var require_bufferutil = __commonJS({
  "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js"(exports2, module2) {
    "use strict";
    try {
      module2.exports = require_node_gyp_build2()(__dirname);
    } catch (e4) {
      module2.exports = require_fallback();
    }
  }
});

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

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

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

// ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js
var require_fallback2 = __commonJS({
  "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports2, module2) {
    "use strict";
    function isValidUTF8(buf) {
      const len = buf.length;
      let i4 = 0;
      while (i4 < len) {
        if ((buf[i4] & 128) === 0) {
          i4++;
        } else if ((buf[i4] & 224) === 192) {
          if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) {
            return false;
          }
          i4 += 2;
        } else if ((buf[i4] & 240) === 224) {
          if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // overlong
          buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) {
            return false;
          }
          i4 += 3;
        } else if ((buf[i4] & 248) === 240) {
          if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // overlong
          buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) {
            return false;
          }
          i4 += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    module2.exports = isValidUTF8;
  }
});

// ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js
var require_utf_8_validate = __commonJS({
  "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js"(exports2, module2) {
    "use strict";
    try {
      module2.exports = require_node_gyp_build2()(__dirname);
    } catch (e4) {
      module2.exports = require_fallback2();
    }
  }
});

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

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

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

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

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

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

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

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

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

// ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs
var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
  "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs"() {
    import_stream = __toESM(require_stream(), 1);
    import_receiver = __toESM(require_receiver(), 1);
    import_sender = __toESM(require_sender(), 1);
    import_websocket = __toESM(require_websocket(), 1);
    import_websocket_server = __toESM(require_websocket_server(), 1);
    wrapper_default = import_websocket.default;
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-cjs/index.js
var require_dist_cjs = __commonJS({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AlgorithmId: () => AlgorithmId,
      EndpointURLScheme: () => EndpointURLScheme,
      FieldPosition: () => FieldPosition,
      HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation2,
      HttpAuthLocation: () => HttpAuthLocation,
      IniSectionType: () => IniSectionType,
      RequestHandlerProtocol: () => RequestHandlerProtocol,
      SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY4,
      getDefaultClientConfiguration: () => getDefaultClientConfiguration,
      resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3
    });
    module2.exports = __toCommonJS2(src_exports);
    var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => {
      HttpAuthLocation2["HEADER"] = "header";
      HttpAuthLocation2["QUERY"] = "query";
      return HttpAuthLocation2;
    })(HttpAuthLocation || {});
    var HttpApiKeyAuthLocation2 = /* @__PURE__ */ ((HttpApiKeyAuthLocation22) => {
      HttpApiKeyAuthLocation22["HEADER"] = "header";
      HttpApiKeyAuthLocation22["QUERY"] = "query";
      return HttpApiKeyAuthLocation22;
    })(HttpApiKeyAuthLocation2 || {});
    var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => {
      EndpointURLScheme2["HTTP"] = "http";
      EndpointURLScheme2["HTTPS"] = "https";
      return EndpointURLScheme2;
    })(EndpointURLScheme || {});
    var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => {
      AlgorithmId2["MD5"] = "md5";
      AlgorithmId2["CRC32"] = "crc32";
      AlgorithmId2["CRC32C"] = "crc32c";
      AlgorithmId2["SHA1"] = "sha1";
      AlgorithmId2["SHA256"] = "sha256";
      return AlgorithmId2;
    })(AlgorithmId || {});
    var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const checksumAlgorithms = [];
      if (runtimeConfig.sha256 !== void 0) {
        checksumAlgorithms.push({
          algorithmId: () => "sha256",
          checksumConstructor: () => runtimeConfig.sha256
        });
      }
      if (runtimeConfig.md5 != void 0) {
        checksumAlgorithms.push({
          algorithmId: () => "md5",
          checksumConstructor: () => runtimeConfig.md5
        });
      }
      return {
        addChecksumAlgorithm(algo) {
          checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return checksumAlgorithms;
        }
      };
    }, "getChecksumConfiguration");
    var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    }, "resolveChecksumRuntimeConfig");
    var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      return getChecksumConfiguration(runtimeConfig);
    }, "getDefaultClientConfiguration");
    var resolveDefaultRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
      return resolveChecksumRuntimeConfig(config);
    }, "resolveDefaultRuntimeConfig");
    var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => {
      FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
      FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
      return FieldPosition2;
    })(FieldPosition || {});
    var SMITHY_CONTEXT_KEY4 = "__smithy_context";
    var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => {
      IniSectionType2["PROFILE"] = "profile";
      IniSectionType2["SSO_SESSION"] = "sso-session";
      IniSectionType2["SERVICES"] = "services";
      return IniSectionType2;
    })(IniSectionType || {});
    var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => {
      RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
      RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
      RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
      return RequestHandlerProtocol2;
    })(RequestHandlerProtocol || {});
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-cjs/index.js
var require_dist_cjs2 = __commonJS({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Field: () => Field,
      Fields: () => Fields,
      HttpRequest: () => HttpRequest10,
      HttpResponse: () => HttpResponse4,
      IHttpRequest: () => import_types5.HttpRequest,
      getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration3,
      isValidHostname: () => isValidHostname,
      resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig3
    });
    module2.exports = __toCommonJS2(src_exports);
    var getHttpHandlerExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
      return {
        setHttpHandler(handler) {
          runtimeConfig.httpHandler = handler;
        },
        httpHandler() {
          return runtimeConfig.httpHandler;
        },
        updateHttpClientConfig(key, value) {
          var _a6;
          (_a6 = runtimeConfig.httpHandler) == null ? void 0 : _a6.updateHttpClientConfig(key, value);
        },
        httpHandlerConfigs() {
          return runtimeConfig.httpHandler.httpHandlerConfigs();
        }
      };
    }, "getHttpHandlerExtensionConfiguration");
    var resolveHttpHandlerRuntimeConfig3 = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => {
      return {
        httpHandler: httpHandlerExtensionConfiguration.httpHandler()
      };
    }, "resolveHttpHandlerRuntimeConfig");
    var import_types5 = require_dist_cjs();
    var _a2;
    var Field = (_a2 = class {
      constructor({ name, kind = import_types5.FieldPosition.HEADER, values = [] }) {
        this.name = name;
        this.kind = kind;
        this.values = values;
      }
      /**
       * Appends a value to the field.
       *
       * @param value The value to append.
       */
      add(value) {
        this.values.push(value);
      }
      /**
       * Overwrite existing field values.
       *
       * @param values The new field values.
       */
      set(values) {
        this.values = values;
      }
      /**
       * Remove all matching entries from list.
       *
       * @param value Value to remove.
       */
      remove(value) {
        this.values = this.values.filter((v6) => v6 !== value);
      }
      /**
       * Get comma-delimited string.
       *
       * @returns String representation of {@link Field}.
       */
      toString() {
        return this.values.map((v6) => v6.includes(",") || v6.includes(" ") ? `"${v6}"` : v6).join(", ");
      }
      /**
       * Get string values as a list
       *
       * @returns Values in {@link Field} as a list.
       */
      get() {
        return this.values;
      }
    }, __name(_a2, "Field"), _a2);
    var _a3;
    var Fields = (_a3 = class {
      constructor({ fields = [], encoding = "utf-8" }) {
        this.entries = {};
        fields.forEach(this.setField.bind(this));
        this.encoding = encoding;
      }
      /**
       * Set entry for a {@link Field} name. The `name`
       * attribute will be used to key the collection.
       *
       * @param field The {@link Field} to set.
       */
      setField(field) {
        this.entries[field.name.toLowerCase()] = field;
      }
      /**
       *  Retrieve {@link Field} entry by name.
       *
       * @param name The name of the {@link Field} entry
       *  to retrieve
       * @returns The {@link Field} if it exists.
       */
      getField(name) {
        return this.entries[name.toLowerCase()];
      }
      /**
       * Delete entry from collection.
       *
       * @param name Name of the entry to delete.
       */
      removeField(name) {
        delete this.entries[name.toLowerCase()];
      }
      /**
       * Helper function for retrieving specific types of fields.
       * Used to grab all headers or all trailers.
       *
       * @param kind {@link FieldPosition} of entries to retrieve.
       * @returns The {@link Field} entries with the specified
       *  {@link FieldPosition}.
       */
      getByType(kind) {
        return Object.values(this.entries).filter((field) => field.kind === kind);
      }
    }, __name(_a3, "Fields"), _a3);
    var _a4;
    var HttpRequest10 = (_a4 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      /**
       * Note: this does not deep-clone the body.
       */
      static clone(request) {
        const cloned = new _a4({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery(cloned.query);
        }
        return cloned;
      }
      /**
       * This method only actually asserts that request is the interface {@link IHttpRequest},
       * and not necessarily this concrete class. Left in place for API stability.
       *
       * Do not call instance methods on the input of this function, and
       * do not assume it has the HttpRequest prototype.
       */
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      /**
       * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call
       * this method because {@link HttpRequest.isInstance} incorrectly
       * asserts that IHttpRequest (interface) objects are of type HttpRequest (class).
       */
      clone() {
        return _a4.clone(this);
      }
    }, __name(_a4, "HttpRequest"), _a4);
    function cloneQuery(query) {
      return Object.keys(query).reduce((carry, paramName) => {
        const param = query[paramName];
        return {
          ...carry,
          [paramName]: Array.isArray(param) ? [...param] : param
        };
      }, {});
    }
    __name(cloneQuery, "cloneQuery");
    var _a5;
    var HttpResponse4 = (_a5 = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    }, __name(_a5, "HttpResponse"), _a5);
    function isValidHostname(hostname) {
      const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
      return hostPattern.test(hostname);
    }
    __name(isValidHostname, "isValidHostname");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js
var require_dist_cjs3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      getHostHeaderPlugin: () => getHostHeaderPlugin3,
      hostHeaderMiddleware: () => hostHeaderMiddleware,
      hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions,
      resolveHostHeaderConfig: () => resolveHostHeaderConfig3
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_protocol_http15 = require_dist_cjs2();
    function resolveHostHeaderConfig3(input) {
      return input;
    }
    __name(resolveHostHeaderConfig3, "resolveHostHeaderConfig");
    var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
      if (!import_protocol_http15.HttpRequest.isInstance(args.request)) return next(args);
      const { request } = args;
      const { handlerProtocol = "" } = options.requestHandler.metadata || {};
      if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) {
        delete request.headers["host"];
        request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : "");
      } else if (!request.headers["host"]) {
        let host = request.hostname;
        if (request.port != null) host += `:${request.port}`;
        request.headers["host"] = host;
      }
      return next(args);
    }, "hostHeaderMiddleware");
    var hostHeaderMiddlewareOptions = {
      name: "hostHeaderMiddleware",
      step: "build",
      priority: "low",
      tags: ["HOST"],
      override: true
    };
    var getHostHeaderPlugin3 = /* @__PURE__ */ __name((options) => ({
      applyToStack: /* @__PURE__ */ __name((clientStack) => {
        clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
      }, "applyToStack")
    }), "getHostHeaderPlugin");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js
var require_dist_cjs4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      getLoggerPlugin: () => getLoggerPlugin3,
      loggerMiddleware: () => loggerMiddleware,
      loggerMiddlewareOptions: () => loggerMiddlewareOptions
    });
    module2.exports = __toCommonJS2(index_exports);
    var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => {
      var _a2, _b;
      try {
        const response = await next(args);
        const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
        const { $metadata, ...outputWithoutMetadata } = response.output;
        (_a2 = logger3 == null ? void 0 : logger3.info) == null ? void 0 : _a2.call(logger3, {
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          output: outputFilterSensitiveLog(outputWithoutMetadata),
          metadata: $metadata
        });
        return response;
      } catch (error2) {
        const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        (_b = logger3 == null ? void 0 : logger3.error) == null ? void 0 : _b.call(logger3, {
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          error: error2,
          metadata: error2.$metadata
        });
        throw error2;
      }
    }, "loggerMiddleware");
    var loggerMiddlewareOptions = {
      name: "loggerMiddleware",
      tags: ["LOGGER"],
      step: "initialize",
      override: true
    };
    var getLoggerPlugin3 = /* @__PURE__ */ __name((options) => ({
      applyToStack: /* @__PURE__ */ __name((clientStack) => {
        clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
      }, "applyToStack")
    }), "getLoggerPlugin");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js
var require_dist_cjs5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions,
      getRecursionDetectionPlugin: () => getRecursionDetectionPlugin3,
      recursionDetectionMiddleware: () => recursionDetectionMiddleware
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
    var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
    var ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
    var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
      const { request } = args;
      if (!import_protocol_http15.HttpRequest.isInstance(request) || options.runtime !== "node") {
        return next(args);
      }
      const traceIdHeader = Object.keys(request.headers ?? {}).find((h4) => h4.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
      if (request.headers.hasOwnProperty(traceIdHeader)) {
        return next(args);
      }
      const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
      const traceId = process.env[ENV_TRACE_ID];
      const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString");
      if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
        request.headers[TRACE_ID_HEADER_NAME] = traceId;
      }
      return next({
        ...args,
        request
      });
    }, "recursionDetectionMiddleware");
    var addRecursionDetectionMiddlewareOptions = {
      step: "build",
      tags: ["RECURSION_DETECTION"],
      name: "recursionDetectionMiddleware",
      override: true,
      priority: "low"
    };
    var getRecursionDetectionPlugin3 = /* @__PURE__ */ __name((options) => ({
      applyToStack: /* @__PURE__ */ __name((clientStack) => {
        clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
      }, "applyToStack")
    }), "getRecursionDetectionPlugin");
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js
var import_types, getSmithyContext;
var init_getSmithyContext = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
    import_types = __toESM(require_dist_cjs());
    getSmithyContext = (context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {});
  }
});

// ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-cjs/index.js
var require_dist_cjs6 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      getSmithyContext: () => getSmithyContext8,
      normalizeProvider: () => normalizeProvider4
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_types5 = require_dist_cjs();
    var getSmithyContext8 = /* @__PURE__ */ __name((context) => context[import_types5.SMITHY_CONTEXT_KEY] || (context[import_types5.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext");
    var normalizeProvider4 = /* @__PURE__ */ __name((input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    }, "normalizeProvider");
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
var resolveAuthOptions;
var init_resolveAuthOptions = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() {
    resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
      if (!authSchemePreference || authSchemePreference.length === 0) {
        return candidateAuthOptions;
      }
      const preferredAuthOptions = [];
      for (const preferredSchemeName of authSchemePreference) {
        for (const candidateAuthOption of candidateAuthOptions) {
          const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
          if (candidateAuthSchemeName === preferredSchemeName) {
            preferredAuthOptions.push(candidateAuthOption);
          }
        }
      }
      for (const candidateAuthOption of candidateAuthOptions) {
        if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
          preferredAuthOptions.push(candidateAuthOption);
        }
      }
      return preferredAuthOptions;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap(httpAuthSchemes) {
  const map2 = /* @__PURE__ */ new Map();
  for (const scheme of httpAuthSchemes) {
    map2.set(scheme.schemeId, scheme);
  }
  return map2;
}
var import_types2, import_util_middleware, httpAuthSchemeMiddleware;
var init_httpAuthSchemeMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
    import_types2 = __toESM(require_dist_cjs());
    import_util_middleware = __toESM(require_dist_cjs6());
    init_resolveAuthOptions();
    httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
      var _a2;
      const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));
      const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];
      const resolvedOptions = resolveAuthOptions(options, authSchemePreference);
      const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
      const smithyContext = (0, import_util_middleware.getSmithyContext)(context);
      const failureReasons = [];
      for (const option of resolvedOptions) {
        const scheme = authSchemes.get(option.schemeId);
        if (!scheme) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
          continue;
        }
        const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
        if (!identityProvider) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
          continue;
        }
        const { identityProperties = {}, signingProperties = {} } = ((_a2 = option.propertiesExtractor) == null ? void 0 : _a2.call(option, config, context)) || {};
        option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
        option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
        smithyContext.selectedHttpAuthScheme = {
          httpAuthOption: option,
          identity: await identityProvider(option.identityProperties),
          signer: scheme.signer
        };
        break;
      }
      if (!smithyContext.selectedHttpAuthScheme) {
        throw new Error(failureReasons.join("\n"));
      }
      return next(args);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: "endpointV2Middleware"
    };
    getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
          httpAuthSchemeParametersProvider,
          identityProviderConfigProvider
        }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-cjs/index.js
var require_dist_cjs7 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      deserializerMiddleware: () => deserializerMiddleware,
      deserializerMiddlewareOption: () => deserializerMiddlewareOption,
      getSerdePlugin: () => getSerdePlugin4,
      serializerMiddleware: () => serializerMiddleware,
      serializerMiddlewareOption: () => serializerMiddlewareOption2
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => {
      var _a2, _b, _c, _d;
      const { response } = await next(args);
      try {
        const parsed = await deserializer(response, options);
        return {
          response,
          output: parsed
        };
      } catch (error2) {
        Object.defineProperty(error2, "$response", {
          value: response
        });
        if (!("$metadata" in error2)) {
          const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
          try {
            error2.message += "\n  " + hint;
          } catch (e4) {
            if (!context.logger || ((_b = (_a2 = context.logger) == null ? void 0 : _a2.constructor) == null ? void 0 : _b.name) === "NoOpLogger") {
              console.warn(hint);
            } else {
              (_d = (_c = context.logger) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(_c, hint);
            }
          }
          if (typeof error2.$responseBodyText !== "undefined") {
            if (error2.$response) {
              error2.$response.body = error2.$responseBodyText;
            }
          }
          try {
            if (import_protocol_http15.HttpResponse.isInstance(response)) {
              const { headers = {} } = response;
              const headerEntries = Object.entries(headers);
              error2.$metadata = {
                httpStatusCode: response.statusCode,
                requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
                extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
                cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
              };
            }
          } catch (e4) {
          }
        }
        throw error2;
      }
    }, "deserializerMiddleware");
    var findHeader = /* @__PURE__ */ __name((pattern, headers) => {
      return (headers.find(([k3]) => {
        return k3.match(pattern);
      }) || [void 0, void 0])[1];
    }, "findHeader");
    var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => {
      var _a2;
      const endpointConfig = options;
      const endpoint = ((_a2 = context.endpointV2) == null ? void 0 : _a2.url) && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint;
      if (!endpoint) {
        throw new Error("No valid endpoint provider available.");
      }
      const request = await serializer(args.input, { ...options, endpoint });
      return next({
        ...args,
        request
      });
    }, "serializerMiddleware");
    var deserializerMiddlewareOption = {
      name: "deserializerMiddleware",
      step: "deserialize",
      tags: ["DESERIALIZER"],
      override: true
    };
    var serializerMiddlewareOption2 = {
      name: "serializerMiddleware",
      step: "serialize",
      tags: ["SERIALIZER"],
      override: true
    };
    function getSerdePlugin4(config, serializer, deserializer) {
      return {
        applyToStack: (commandStack) => {
          commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
          commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption2);
        }
      };
    }
    __name(getSerdePlugin4, "getSerdePlugin");
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var import_middleware_serde, httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin;
var init_getHttpAuthSchemePlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
    import_middleware_serde = __toESM(require_dist_cjs7());
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: import_middleware_serde.serializerMiddlewareOption.name
    };
    getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
          httpAuthSchemeParametersProvider,
          identityProviderConfigProvider
        }), httpAuthSchemeMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
    init_httpAuthSchemeMiddleware();
    init_getHttpAuthSchemeEndpointRuleSetPlugin();
    init_getHttpAuthSchemePlugin();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var import_protocol_http, import_types3, import_util_middleware2, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
var init_httpSigningMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
    import_protocol_http = __toESM(require_dist_cjs2());
    import_types3 = __toESM(require_dist_cjs());
    import_util_middleware2 = __toESM(require_dist_cjs6());
    defaultErrorHandler = (signingProperties) => (error2) => {
      throw error2;
    };
    defaultSuccessHandler = (httpResponse, signingProperties) => {
    };
    httpSigningMiddleware = (config) => (next, context) => async (args) => {
      if (!import_protocol_http.HttpRequest.isInstance(args.request)) {
        return next(args);
      }
      const smithyContext = (0, import_util_middleware2.getSmithyContext)(context);
      const scheme = smithyContext.selectedHttpAuthScheme;
      if (!scheme) {
        throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
      }
      const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
      const output = await next({
        ...args,
        request: await signer.sign(args.request, identity, signingProperties)
      }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
      (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
      return output;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions, getHttpSigningPlugin;
var init_getHttpSigningMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
    init_httpSigningMiddleware();
    httpSigningMiddlewareOptions = {
      step: "finalizeRequest",
      tags: ["HTTP_SIGNING"],
      name: "httpSigningMiddleware",
      aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
      override: true,
      relation: "after",
      toMiddleware: "retryMiddleware"
    };
    getHttpSigningPlugin = (config) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
    init_httpSigningMiddleware();
    init_getHttpSigningMiddleware();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider;
var init_normalizeProvider = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
    normalizeProvider = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
  return async function* paginateOperation(config, input, ...additionalArguments) {
    const _input = input;
    let token = config.startingToken ?? _input[inputTokenName];
    let hasNext = true;
    let page;
    while (hasNext) {
      _input[inputTokenName] = token;
      if (pageSizeTokenName) {
        _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize;
      }
      if (config.client instanceof ClientCtor) {
        page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments);
      } else {
        throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
      }
      yield page;
      const prevToken = token;
      token = get(page, outputTokenName);
      hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
    }
    return void 0;
  };
}
var makePagedClientRequest, get;
var init_createPaginator = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
    makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => {
      let command = new CommandCtor(input);
      command = withCommand(command) ?? command;
      return await client.send(command, ...args);
    };
    get = (fromObject, path4) => {
      let cursor = fromObject;
      const pathComponents = path4.split(".");
      for (const step of pathComponents) {
        if (!cursor || typeof cursor !== "object") {
          return void 0;
        }
        cursor = cursor[step];
      }
      return cursor;
    };
  }
});

// ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
var require_dist_cjs8 = __commonJS({
  "../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      isArrayBuffer: () => isArrayBuffer
    });
    module2.exports = __toCommonJS2(src_exports);
    var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
  }
});

// ../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
var require_dist_cjs9 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromArrayBuffer: () => fromArrayBuffer,
      fromString: () => fromString
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_is_array_buffer = require_dist_cjs8();
    var import_buffer2 = require("buffer");
    var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
      if (!(0, import_is_array_buffer.isArrayBuffer)(input)) {
        throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
      }
      return import_buffer2.Buffer.from(input, offset, length);
    }, "fromArrayBuffer");
    var fromString = /* @__PURE__ */ __name((input, encoding) => {
      if (typeof input !== "string") {
        throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
      }
      return encoding ? import_buffer2.Buffer.from(input, encoding) : import_buffer2.Buffer.from(input);
    }, "fromString");
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
var require_fromBase64 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromBase64 = void 0;
    var util_buffer_from_1 = require_dist_cjs9();
    var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
    var fromBase645 = (input) => {
      if (input.length * 3 % 4 !== 0) {
        throw new TypeError(`Incorrect padding on base64 string.`);
      }
      if (!BASE64_REGEX.exec(input)) {
        throw new TypeError(`Invalid base64 string.`);
      }
      const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
      return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    };
    exports2.fromBase64 = fromBase645;
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js
var require_dist_cjs10 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromUtf8: () => fromUtf84,
      toUint8Array: () => toUint8Array,
      toUtf8: () => toUtf85
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_buffer_from = require_dist_cjs9();
    var fromUtf84 = /* @__PURE__ */ __name((input) => {
      const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
      return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    }, "fromUtf8");
    var toUint8Array = /* @__PURE__ */ __name((data) => {
      if (typeof data === "string") {
        return fromUtf84(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    }, "toUint8Array");
    var toUtf85 = /* @__PURE__ */ __name((input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
    }, "toUtf8");
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
var require_toBase64 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toBase64 = void 0;
    var util_buffer_from_1 = require_dist_cjs9();
    var util_utf8_1 = require_dist_cjs10();
    var toBase645 = (_input) => {
      let input;
      if (typeof _input === "string") {
        input = (0, util_utf8_1.fromUtf8)(_input);
      } else {
        input = _input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
      }
      return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
    };
    exports2.toBase64 = toBase645;
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js
var require_dist_cjs11 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_fromBase64(), module2.exports);
    __reExport(src_exports, require_toBase64(), module2.exports);
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js
var require_ChecksumStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChecksumStream = void 0;
    var util_base64_1 = require_dist_cjs11();
    var stream_1 = require("stream");
    var ChecksumStream2 = class extends stream_1.Duplex {
      constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) {
        var _a2, _b;
        super();
        if (typeof source.pipe === "function") {
          this.source = source;
        } else {
          throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`);
        }
        this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64;
        this.expectedChecksum = expectedChecksum;
        this.checksum = checksum;
        this.checksumSourceLocation = checksumSourceLocation;
        this.source.pipe(this);
      }
      _read(size) {
      }
      _write(chunk, encoding, callback) {
        try {
          this.checksum.update(chunk);
          this.push(chunk);
        } catch (e4) {
          return callback(e4);
        }
        return callback();
      }
      async _final(callback) {
        try {
          const digest = await this.checksum.digest();
          const received = this.base64Encoder(digest);
          if (this.expectedChecksum !== received) {
            return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`));
          }
        } catch (e4) {
          return callback(e4);
        }
        this.push(null);
        return callback();
      }
    };
    exports2.ChecksumStream = ChecksumStream2;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js
var require_stream_type_check = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isBlob = exports2.isReadableStream = void 0;
    var isReadableStream2 = (stream) => {
      var _a2;
      return typeof ReadableStream === "function" && (((_a2 = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === ReadableStream.name || stream instanceof ReadableStream);
    };
    exports2.isReadableStream = isReadableStream2;
    var isBlob3 = (blob) => {
      var _a2;
      return typeof Blob === "function" && (((_a2 = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === Blob.name || blob instanceof Blob);
    };
    exports2.isBlob = isBlob3;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js
var require_ChecksumStream_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChecksumStream = void 0;
    var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() {
    };
    var ChecksumStream2 = class extends ReadableStreamRef {
    };
    exports2.ChecksumStream = ChecksumStream2;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js
var require_createChecksumStream_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createChecksumStream = void 0;
    var util_base64_1 = require_dist_cjs11();
    var stream_type_check_1 = require_stream_type_check();
    var ChecksumStream_browser_1 = require_ChecksumStream_browser();
    var createChecksumStream2 = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => {
      var _a2, _b;
      if (!(0, stream_type_check_1.isReadableStream)(source)) {
        throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`);
      }
      const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64;
      if (typeof TransformStream !== "function") {
        throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");
      }
      const transform = new TransformStream({
        start() {
        },
        async transform(chunk, controller) {
          checksum.update(chunk);
          controller.enqueue(chunk);
        },
        async flush(controller) {
          const digest = await checksum.digest();
          const received = encoder(digest);
          if (expectedChecksum !== received) {
            const error2 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);
            controller.error(error2);
          } else {
            controller.terminate();
          }
        }
      });
      source.pipeThrough(transform);
      const readable = transform.readable;
      Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype);
      return readable;
    };
    exports2.createChecksumStream = createChecksumStream2;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js
var require_createChecksumStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createChecksumStream = createChecksumStream2;
    var stream_type_check_1 = require_stream_type_check();
    var ChecksumStream_1 = require_ChecksumStream();
    var createChecksumStream_browser_1 = require_createChecksumStream_browser();
    function createChecksumStream2(init2) {
      if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init2.source)) {
        return (0, createChecksumStream_browser_1.createChecksumStream)(init2);
      }
      return new ChecksumStream_1.ChecksumStream(init2);
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js
var require_ByteArrayCollector = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ByteArrayCollector = void 0;
    var ByteArrayCollector = class {
      constructor(allocByteArray) {
        this.allocByteArray = allocByteArray;
        this.byteLength = 0;
        this.byteArrays = [];
      }
      push(byteArray) {
        this.byteArrays.push(byteArray);
        this.byteLength += byteArray.byteLength;
      }
      flush() {
        if (this.byteArrays.length === 1) {
          const bytes = this.byteArrays[0];
          this.reset();
          return bytes;
        }
        const aggregation = this.allocByteArray(this.byteLength);
        let cursor = 0;
        for (let i4 = 0; i4 < this.byteArrays.length; ++i4) {
          const bytes = this.byteArrays[i4];
          aggregation.set(bytes, cursor);
          cursor += bytes.byteLength;
        }
        this.reset();
        return aggregation;
      }
      reset() {
        this.byteArrays = [];
        this.byteLength = 0;
      }
    };
    exports2.ByteArrayCollector = ByteArrayCollector;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js
var require_createBufferedReadableStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createBufferedReadable = void 0;
    exports2.createBufferedReadableStream = createBufferedReadableStream;
    exports2.merge = merge;
    exports2.flush = flush;
    exports2.sizeOf = sizeOf;
    exports2.modeOf = modeOf;
    var ByteArrayCollector_1 = require_ByteArrayCollector();
    function createBufferedReadableStream(upstream, size, logger3) {
      const reader = upstream.getReader();
      let streamBufferingLoggedWarning = false;
      let bytesSeen = 0;
      const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2))];
      let mode = -1;
      const pull2 = async (controller) => {
        const { value, done } = await reader.read();
        const chunk = value;
        if (done) {
          if (mode !== -1) {
            const remainder = flush(buffers, mode);
            if (sizeOf(remainder) > 0) {
              controller.enqueue(remainder);
            }
          }
          controller.close();
        } else {
          const chunkMode = modeOf(chunk, false);
          if (mode !== chunkMode) {
            if (mode >= 0) {
              controller.enqueue(flush(buffers, mode));
            }
            mode = chunkMode;
          }
          if (mode === -1) {
            controller.enqueue(chunk);
            return;
          }
          const chunkSize = sizeOf(chunk);
          bytesSeen += chunkSize;
          const bufferSize = sizeOf(buffers[mode]);
          if (chunkSize >= size && bufferSize === 0) {
            controller.enqueue(chunk);
          } else {
            const newSize = merge(buffers, mode, chunk);
            if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
              streamBufferingLoggedWarning = true;
              logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
            }
            if (newSize >= size) {
              controller.enqueue(flush(buffers, mode));
            } else {
              await pull2(controller);
            }
          }
        }
      };
      return new ReadableStream({
        pull: pull2
      });
    }
    exports2.createBufferedReadable = createBufferedReadableStream;
    function merge(buffers, mode, chunk) {
      switch (mode) {
        case 0:
          buffers[0] += chunk;
          return sizeOf(buffers[0]);
        case 1:
        case 2:
          buffers[mode].push(chunk);
          return sizeOf(buffers[mode]);
      }
    }
    function flush(buffers, mode) {
      switch (mode) {
        case 0:
          const s4 = buffers[0];
          buffers[0] = "";
          return s4;
        case 1:
        case 2:
          return buffers[mode].flush();
      }
      throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`);
    }
    function sizeOf(chunk) {
      var _a2, _b;
      return (_b = (_a2 = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0;
    }
    function modeOf(chunk, allowBuffer = true) {
      if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) {
        return 2;
      }
      if (chunk instanceof Uint8Array) {
        return 1;
      }
      if (typeof chunk === "string") {
        return 0;
      }
      return -1;
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js
var require_createBufferedReadable = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createBufferedReadable = createBufferedReadable2;
    var node_stream_1 = require("node:stream");
    var ByteArrayCollector_1 = require_ByteArrayCollector();
    var createBufferedReadableStream_1 = require_createBufferedReadableStream();
    var stream_type_check_1 = require_stream_type_check();
    function createBufferedReadable2(upstream, size, logger3) {
      if ((0, stream_type_check_1.isReadableStream)(upstream)) {
        return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger3);
      }
      const downstream = new node_stream_1.Readable({ read() {
      } });
      let streamBufferingLoggedWarning = false;
      let bytesSeen = 0;
      const buffers = [
        "",
        new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2)),
        new ByteArrayCollector_1.ByteArrayCollector((size2) => Buffer.from(new Uint8Array(size2)))
      ];
      let mode = -1;
      upstream.on("data", (chunk) => {
        const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true);
        if (mode !== chunkMode) {
          if (mode >= 0) {
            downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
          }
          mode = chunkMode;
        }
        if (mode === -1) {
          downstream.push(chunk);
          return;
        }
        const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk);
        bytesSeen += chunkSize;
        const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]);
        if (chunkSize >= size && bufferSize === 0) {
          downstream.push(chunk);
        } else {
          const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk);
          if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
            streamBufferingLoggedWarning = true;
            logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
          }
          if (newSize >= size) {
            downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
          }
        }
      });
      upstream.on("end", () => {
        if (mode !== -1) {
          const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode);
          if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) {
            downstream.push(remainder);
          }
        }
        downstream.push(null);
      });
      return downstream;
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js
var require_getAwsChunkedEncodingStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getAwsChunkedEncodingStream = void 0;
    var stream_1 = require("stream");
    var getAwsChunkedEncodingStream2 = (readableStream, options) => {
      const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;
      const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0;
      const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0;
      const awsChunkedEncodingStream = new stream_1.Readable({ read: () => {
      } });
      readableStream.on("data", (data) => {
        const length = bodyLengthChecker(data) || 0;
        awsChunkedEncodingStream.push(`${length.toString(16)}\r
`);
        awsChunkedEncodingStream.push(data);
        awsChunkedEncodingStream.push("\r\n");
      });
      readableStream.on("end", async () => {
        awsChunkedEncodingStream.push(`0\r
`);
        if (checksumRequired) {
          const checksum = base64Encoder(await digest);
          awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r
`);
          awsChunkedEncodingStream.push(`\r
`);
        }
        awsChunkedEncodingStream.push(null);
      });
      return awsChunkedEncodingStream;
    };
    exports2.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream2;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js
var require_headStream_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headStream = headStream2;
    async function headStream2(stream, bytes) {
      var _a2;
      let byteLengthCounter = 0;
      const chunks = [];
      const reader = stream.getReader();
      let isDone = false;
      while (!isDone) {
        const { done, value } = await reader.read();
        if (value) {
          chunks.push(value);
          byteLengthCounter += (_a2 = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a2 !== void 0 ? _a2 : 0;
        }
        if (byteLengthCounter >= bytes) {
          break;
        }
        isDone = done;
      }
      reader.releaseLock();
      const collected = new Uint8Array(Math.min(bytes, byteLengthCounter));
      let offset = 0;
      for (const chunk of chunks) {
        if (chunk.byteLength > collected.byteLength - offset) {
          collected.set(chunk.subarray(0, collected.byteLength - offset), offset);
          break;
        } else {
          collected.set(chunk, offset);
        }
        offset += chunk.length;
      }
      return collected;
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js
var require_headStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headStream = void 0;
    var stream_1 = require("stream");
    var headStream_browser_1 = require_headStream_browser();
    var stream_type_check_1 = require_stream_type_check();
    var headStream2 = (stream, bytes) => {
      if ((0, stream_type_check_1.isReadableStream)(stream)) {
        return (0, headStream_browser_1.headStream)(stream, bytes);
      }
      return new Promise((resolve2, reject) => {
        const collector = new Collector();
        collector.limit = bytes;
        stream.pipe(collector);
        stream.on("error", (err2) => {
          collector.end();
          reject(err2);
        });
        collector.on("error", reject);
        collector.on("finish", function() {
          const bytes2 = new Uint8Array(Buffer.concat(this.buffers));
          resolve2(bytes2);
        });
      });
    };
    exports2.headStream = headStream2;
    var Collector = class extends stream_1.Writable {
      constructor() {
        super(...arguments);
        this.buffers = [];
        this.limit = Infinity;
        this.bytesBuffered = 0;
      }
      _write(chunk, encoding, callback) {
        var _a2;
        this.buffers.push(chunk);
        this.bytesBuffered += (_a2 = chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : 0;
        if (this.bytesBuffered >= this.limit) {
          const excess = this.bytesBuffered - this.limit;
          const tailBuffer = this.buffers[this.buffers.length - 1];
          this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess);
          this.emit("finish");
        }
        callback();
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
var require_dist_cjs12 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      escapeUri: () => escapeUri,
      escapeUriPath: () => escapeUriPath
    });
    module2.exports = __toCommonJS2(src_exports);
    var escapeUri = /* @__PURE__ */ __name((uri) => (
      // AWS percent-encodes some extra non-standard characters in a URI
      encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode)
    ), "escapeUri");
    var hexEncode = /* @__PURE__ */ __name((c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode");
    var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath");
  }
});

// ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-cjs/index.js
var require_dist_cjs13 = __commonJS({
  "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      buildQueryString: () => buildQueryString
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_uri_escape = require_dist_cjs12();
    function buildQueryString(query) {
      const parts = [];
      for (let key of Object.keys(query).sort()) {
        const value = query[key];
        key = (0, import_util_uri_escape.escapeUri)(key);
        if (Array.isArray(value)) {
          for (let i4 = 0, iLen = value.length; i4 < iLen; i4++) {
            parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i4])}`);
          }
        } else {
          let qsEntry = key;
          if (value || typeof value === "string") {
            qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`;
          }
          parts.push(qsEntry);
        }
      }
      return parts.join("&");
    }
    __name(buildQueryString, "buildQueryString");
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-cjs/index.js
var require_dist_cjs14 = __commonJS({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-cjs/index.js"(exports2, module2) {
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
      NodeHttp2Handler: () => NodeHttp2Handler,
      NodeHttpHandler: () => NodeHttpHandler,
      streamCollector: () => streamCollector3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var import_querystring_builder = require_dist_cjs13();
    var import_http3 = require("http");
    var import_https = require("https");
    var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
    var getTransformedHeaders = /* @__PURE__ */ __name((headers) => {
      const transformedHeaders = {};
      for (const name of Object.keys(headers)) {
        const headerValues = headers[name];
        transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
      }
      return transformedHeaders;
    }, "getTransformedHeaders");
    var timing = {
      setTimeout: (cb, ms) => setTimeout(cb, ms),
      clearTimeout: (timeoutId) => clearTimeout(timeoutId)
    };
    var DEFER_EVENT_LISTENER_TIME = 1e3;
    var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => {
      if (!timeoutInMs) {
        return -1;
      }
      const registerTimeout = /* @__PURE__ */ __name((offset) => {
        const timeoutId = timing.setTimeout(() => {
          request.destroy();
          reject(
            Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
              name: "TimeoutError"
            })
          );
        }, timeoutInMs - offset);
        const doWithSocket = /* @__PURE__ */ __name((socket) => {
          if (socket == null ? void 0 : socket.connecting) {
            socket.on("connect", () => {
              timing.clearTimeout(timeoutId);
            });
          } else {
            timing.clearTimeout(timeoutId);
          }
        }, "doWithSocket");
        if (request.socket) {
          doWithSocket(request.socket);
        } else {
          request.on("socket", doWithSocket);
        }
      }, "registerTimeout");
      if (timeoutInMs < 2e3) {
        registerTimeout(0);
        return 0;
      }
      return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
    }, "setConnectionTimeout");
    var DEFER_EVENT_LISTENER_TIME2 = 3e3;
    var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => {
      if (keepAlive !== true) {
        return -1;
      }
      const registerListener = /* @__PURE__ */ __name(() => {
        if (request.socket) {
          request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
        } else {
          request.on("socket", (socket) => {
            socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
          });
        }
      }, "registerListener");
      if (deferTimeMs === 0) {
        registerListener();
        return 0;
      }
      return timing.setTimeout(registerListener, deferTimeMs);
    }, "setSocketKeepAlive");
    var DEFER_EVENT_LISTENER_TIME3 = 3e3;
    var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
      const registerTimeout = /* @__PURE__ */ __name((offset) => {
        const timeout = timeoutInMs - offset;
        const onTimeout = /* @__PURE__ */ __name(() => {
          request.destroy();
          reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
        }, "onTimeout");
        if (request.socket) {
          request.socket.setTimeout(timeout, onTimeout);
          request.on("close", () => {
            var _a7;
            return (_a7 = request.socket) == null ? void 0 : _a7.removeListener("timeout", onTimeout);
          });
        } else {
          request.setTimeout(timeout, onTimeout);
        }
      }, "registerTimeout");
      if (0 < timeoutInMs && timeoutInMs < 6e3) {
        registerTimeout(0);
        return 0;
      }
      return timing.setTimeout(
        registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3),
        DEFER_EVENT_LISTENER_TIME3
      );
    }, "setSocketTimeout");
    var import_stream3 = require("stream");
    var MIN_WAIT_TIME = 6e3;
    async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) {
      const headers = request.headers ?? {};
      const expect = headers["Expect"] || headers["expect"];
      let timeoutId = -1;
      let sendBody = true;
      if (expect === "100-continue") {
        sendBody = await Promise.race([
          new Promise((resolve2) => {
            timeoutId = Number(timing.setTimeout(() => resolve2(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
          }),
          new Promise((resolve2) => {
            httpRequest.on("continue", () => {
              timing.clearTimeout(timeoutId);
              resolve2(true);
            });
            httpRequest.on("response", () => {
              timing.clearTimeout(timeoutId);
              resolve2(false);
            });
            httpRequest.on("error", () => {
              timing.clearTimeout(timeoutId);
              resolve2(false);
            });
          })
        ]);
      }
      if (sendBody) {
        writeBody(httpRequest, request.body);
      }
    }
    __name(writeRequestBody, "writeRequestBody");
    function writeBody(httpRequest, body) {
      if (body instanceof import_stream3.Readable) {
        body.pipe(httpRequest);
        return;
      }
      if (body) {
        if (Buffer.isBuffer(body) || typeof body === "string") {
          httpRequest.end(body);
          return;
        }
        const uint8 = body;
        if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
          httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
          return;
        }
        httpRequest.end(Buffer.from(body));
        return;
      }
      httpRequest.end();
    }
    __name(writeBody, "writeBody");
    var DEFAULT_REQUEST_TIMEOUT = 0;
    var _a2;
    var NodeHttpHandler = (_a2 = class {
      constructor(options) {
        this.socketWarningTimestamp = 0;
        this.metadata = { handlerProtocol: "http/1.1" };
        this.configProvider = new Promise((resolve2, reject) => {
          if (typeof options === "function") {
            options().then((_options) => {
              resolve2(this.resolveDefaultConfig(_options));
            }).catch(reject);
          } else {
            resolve2(this.resolveDefaultConfig(options));
          }
        });
      }
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _a2(instanceOrOptions);
      }
      /**
       * @internal
       *
       * @param agent - http(s) agent in use by the NodeHttpHandler instance.
       * @param socketWarningTimestamp - last socket usage check timestamp.
       * @param logger - channel for the warning.
       * @returns timestamp of last emitted warning.
       */
      static checkSocketUsage(agent, socketWarningTimestamp, logger3 = console) {
        var _a7, _b, _c;
        const { sockets, requests, maxSockets } = agent;
        if (typeof maxSockets !== "number" || maxSockets === Infinity) {
          return socketWarningTimestamp;
        }
        const interval = 15e3;
        if (Date.now() - interval < socketWarningTimestamp) {
          return socketWarningTimestamp;
        }
        if (sockets && requests) {
          for (const origin in sockets) {
            const socketsInUse = ((_a7 = sockets[origin]) == null ? void 0 : _a7.length) ?? 0;
            const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0;
            if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
              (_c = logger3 == null ? void 0 : logger3.warn) == null ? void 0 : _c.call(
                logger3,
                `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`
              );
              return Date.now();
            }
          }
        }
        return socketWarningTimestamp;
      }
      resolveDefaultConfig(options) {
        const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
        const keepAlive = true;
        const maxSockets = 50;
        return {
          connectionTimeout,
          requestTimeout: requestTimeout ?? socketTimeout,
          socketAcquisitionWarningTimeout,
          httpAgent: (() => {
            if (httpAgent instanceof import_http3.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") {
              return httpAgent;
            }
            return new import_http3.Agent({ keepAlive, maxSockets, ...httpAgent });
          })(),
          httpsAgent: (() => {
            if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") {
              return httpsAgent;
            }
            return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
          })(),
          logger: console
        };
      }
      destroy() {
        var _a7, _b, _c, _d;
        (_b = (_a7 = this.config) == null ? void 0 : _a7.httpAgent) == null ? void 0 : _b.destroy();
        (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy();
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
        }
        return new Promise((_resolve, _reject) => {
          let writeRequestBodyPromise = void 0;
          const timeouts = [];
          const resolve2 = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            timeouts.forEach(timing.clearTimeout);
            _resolve(arg);
          }, "resolve");
          const reject = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            timeouts.forEach(timing.clearTimeout);
            _reject(arg);
          }, "reject");
          if (!this.config) {
            throw new Error("Node HTTP request handler config is not resolved");
          }
          if (abortSignal == null ? void 0 : abortSignal.aborted) {
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
            return;
          }
          const isSSL = request.protocol === "https:";
          const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
          timeouts.push(
            timing.setTimeout(
              () => {
                this.socketWarningTimestamp = _a2.checkSocketUsage(
                  agent,
                  this.socketWarningTimestamp,
                  this.config.logger
                );
              },
              this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)
            )
          );
          const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
          let auth = void 0;
          if (request.username != null || request.password != null) {
            const username = request.username ?? "";
            const password = request.password ?? "";
            auth = `${username}:${password}`;
          }
          let path4 = request.path;
          if (queryString) {
            path4 += `?${queryString}`;
          }
          if (request.fragment) {
            path4 += `#${request.fragment}`;
          }
          let hostname = request.hostname ?? "";
          if (hostname[0] === "[" && hostname.endsWith("]")) {
            hostname = request.hostname.slice(1, -1);
          } else {
            hostname = request.hostname;
          }
          const nodeHttpsOptions = {
            headers: request.headers,
            host: hostname,
            method: request.method,
            path: path4,
            port: request.port,
            agent,
            auth
          };
          const requestFunc = isSSL ? import_https.request : import_http3.request;
          const req = requestFunc(nodeHttpsOptions, (res) => {
            const httpResponse = new import_protocol_http15.HttpResponse({
              statusCode: res.statusCode || -1,
              reason: res.statusMessage,
              headers: getTransformedHeaders(res.headers),
              body: res
            });
            resolve2({ response: httpResponse });
          });
          req.on("error", (err2) => {
            if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) {
              reject(Object.assign(err2, { name: "TimeoutError" }));
            } else {
              reject(err2);
            }
          });
          if (abortSignal) {
            const onAbort = /* @__PURE__ */ __name(() => {
              req.destroy();
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              reject(abortError);
            }, "onAbort");
            if (typeof abortSignal.addEventListener === "function") {
              const signal = abortSignal;
              signal.addEventListener("abort", onAbort, { once: true });
              req.once("close", () => signal.removeEventListener("abort", onAbort));
            } else {
              abortSignal.onabort = onAbort;
            }
          }
          timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout));
          timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout));
          const httpAgent = nodeHttpsOptions.agent;
          if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
            timeouts.push(
              setSocketKeepAlive(req, {
                // @ts-expect-error keepAlive is not public on httpAgent.
                keepAlive: httpAgent.keepAlive,
                // @ts-expect-error keepAliveMsecs is not public on httpAgent.
                keepAliveMsecs: httpAgent.keepAliveMsecs
              })
            );
          }
          writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e4) => {
            timeouts.forEach(timing.clearTimeout);
            return _reject(e4);
          });
        });
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          return {
            ...config,
            [key]: value
          };
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    }, __name(_a2, "NodeHttpHandler"), _a2);
    var import_http22 = require("http2");
    var import_http23 = __toESM3(require("http2"));
    var _a3;
    var NodeHttp2ConnectionPool = (_a3 = class {
      constructor(sessions) {
        this.sessions = [];
        this.sessions = sessions ?? [];
      }
      poll() {
        if (this.sessions.length > 0) {
          return this.sessions.shift();
        }
      }
      offerLast(session) {
        this.sessions.push(session);
      }
      contains(session) {
        return this.sessions.includes(session);
      }
      remove(session) {
        this.sessions = this.sessions.filter((s4) => s4 !== session);
      }
      [Symbol.iterator]() {
        return this.sessions[Symbol.iterator]();
      }
      destroy(connection) {
        for (const session of this.sessions) {
          if (session === connection) {
            if (!session.destroyed) {
              session.destroy();
            }
          }
        }
      }
    }, __name(_a3, "NodeHttp2ConnectionPool"), _a3);
    var _a4;
    var NodeHttp2ConnectionManager = (_a4 = class {
      constructor(config) {
        this.sessionCache = /* @__PURE__ */ new Map();
        this.config = config;
        if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {
          throw new RangeError("maxConcurrency must be greater than zero.");
        }
      }
      lease(requestContext, connectionConfiguration) {
        const url = this.getUrlString(requestContext);
        const existingPool = this.sessionCache.get(url);
        if (existingPool) {
          const existingSession = existingPool.poll();
          if (existingSession && !this.config.disableConcurrency) {
            return existingSession;
          }
        }
        const session = import_http23.default.connect(url);
        if (this.config.maxConcurrency) {
          session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err2) => {
            if (err2) {
              throw new Error(
                "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()
              );
            }
          });
        }
        session.unref();
        const destroySessionCb = /* @__PURE__ */ __name(() => {
          session.destroy();
          this.deleteSession(url, session);
        }, "destroySessionCb");
        session.on("goaway", destroySessionCb);
        session.on("error", destroySessionCb);
        session.on("frameError", destroySessionCb);
        session.on("close", () => this.deleteSession(url, session));
        if (connectionConfiguration.requestTimeout) {
          session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb);
        }
        const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool();
        connectionPool.offerLast(session);
        this.sessionCache.set(url, connectionPool);
        return session;
      }
      /**
       * Delete a session from the connection pool.
       * @param authority The authority of the session to delete.
       * @param session The session to delete.
       */
      deleteSession(authority, session) {
        const existingConnectionPool = this.sessionCache.get(authority);
        if (!existingConnectionPool) {
          return;
        }
        if (!existingConnectionPool.contains(session)) {
          return;
        }
        existingConnectionPool.remove(session);
        this.sessionCache.set(authority, existingConnectionPool);
      }
      release(requestContext, session) {
        var _a7;
        const cacheKey2 = this.getUrlString(requestContext);
        (_a7 = this.sessionCache.get(cacheKey2)) == null ? void 0 : _a7.offerLast(session);
      }
      destroy() {
        for (const [key, connectionPool] of this.sessionCache) {
          for (const session of connectionPool) {
            if (!session.destroyed) {
              session.destroy();
            }
            connectionPool.remove(session);
          }
          this.sessionCache.delete(key);
        }
      }
      setMaxConcurrentStreams(maxConcurrentStreams) {
        if (maxConcurrentStreams && maxConcurrentStreams <= 0) {
          throw new RangeError("maxConcurrentStreams must be greater than zero.");
        }
        this.config.maxConcurrency = maxConcurrentStreams;
      }
      setDisableConcurrentStreams(disableConcurrentStreams) {
        this.config.disableConcurrency = disableConcurrentStreams;
      }
      getUrlString(request) {
        return request.destination.toString();
      }
    }, __name(_a4, "NodeHttp2ConnectionManager"), _a4);
    var _a5;
    var NodeHttp2Handler = (_a5 = class {
      constructor(options) {
        this.metadata = { handlerProtocol: "h2" };
        this.connectionManager = new NodeHttp2ConnectionManager({});
        this.configProvider = new Promise((resolve2, reject) => {
          if (typeof options === "function") {
            options().then((opts) => {
              resolve2(opts || {});
            }).catch(reject);
          } else {
            resolve2(options || {});
          }
        });
      }
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _a5(instanceOrOptions);
      }
      destroy() {
        this.connectionManager.destroy();
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
          this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false);
          if (this.config.maxConcurrentStreams) {
            this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams);
          }
        }
        const { requestTimeout, disableConcurrentStreams } = this.config;
        return new Promise((_resolve, _reject) => {
          var _a7;
          let fulfilled = false;
          let writeRequestBodyPromise = void 0;
          const resolve2 = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            _resolve(arg);
          }, "resolve");
          const reject = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            _reject(arg);
          }, "reject");
          if (abortSignal == null ? void 0 : abortSignal.aborted) {
            fulfilled = true;
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
            return;
          }
          const { hostname, method, port, protocol, query } = request;
          let auth = "";
          if (request.username != null || request.password != null) {
            const username = request.username ?? "";
            const password = request.password ?? "";
            auth = `${username}:${password}@`;
          }
          const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`;
          const requestContext = { destination: new URL(authority) };
          const session = this.connectionManager.lease(requestContext, {
            requestTimeout: (_a7 = this.config) == null ? void 0 : _a7.sessionTimeout,
            disableConcurrentStreams: disableConcurrentStreams || false
          });
          const rejectWithDestroy = /* @__PURE__ */ __name((err2) => {
            if (disableConcurrentStreams) {
              this.destroySession(session);
            }
            fulfilled = true;
            reject(err2);
          }, "rejectWithDestroy");
          const queryString = (0, import_querystring_builder.buildQueryString)(query || {});
          let path4 = request.path;
          if (queryString) {
            path4 += `?${queryString}`;
          }
          if (request.fragment) {
            path4 += `#${request.fragment}`;
          }
          const req = session.request({
            ...request.headers,
            [import_http22.constants.HTTP2_HEADER_PATH]: path4,
            [import_http22.constants.HTTP2_HEADER_METHOD]: method
          });
          session.ref();
          req.on("response", (headers) => {
            const httpResponse = new import_protocol_http15.HttpResponse({
              statusCode: headers[":status"] || -1,
              headers: getTransformedHeaders(headers),
              body: req
            });
            fulfilled = true;
            resolve2({ response: httpResponse });
            if (disableConcurrentStreams) {
              session.close();
              this.connectionManager.deleteSession(authority, session);
            }
          });
          if (requestTimeout) {
            req.setTimeout(requestTimeout, () => {
              req.close();
              const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`);
              timeoutError.name = "TimeoutError";
              rejectWithDestroy(timeoutError);
            });
          }
          if (abortSignal) {
            const onAbort = /* @__PURE__ */ __name(() => {
              req.close();
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              rejectWithDestroy(abortError);
            }, "onAbort");
            if (typeof abortSignal.addEventListener === "function") {
              const signal = abortSignal;
              signal.addEventListener("abort", onAbort, { once: true });
              req.once("close", () => signal.removeEventListener("abort", onAbort));
            } else {
              abortSignal.onabort = onAbort;
            }
          }
          req.on("frameError", (type, code, id) => {
            rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));
          });
          req.on("error", rejectWithDestroy);
          req.on("aborted", () => {
            rejectWithDestroy(
              new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)
            );
          });
          req.on("close", () => {
            session.unref();
            if (disableConcurrentStreams) {
              session.destroy();
            }
            if (!fulfilled) {
              rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response"));
            }
          });
          writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout);
        });
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          return {
            ...config,
            [key]: value
          };
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
      /**
       * Destroys a session.
       * @param session - the session to destroy.
       */
      destroySession(session) {
        if (!session.destroyed) {
          session.destroy();
        }
      }
    }, __name(_a5, "NodeHttp2Handler"), _a5);
    var _a6;
    var Collector = (_a6 = class extends import_stream3.Writable {
      constructor() {
        super(...arguments);
        this.bufferedBytes = [];
      }
      _write(chunk, encoding, callback) {
        this.bufferedBytes.push(chunk);
        callback();
      }
    }, __name(_a6, "Collector"), _a6);
    var streamCollector3 = /* @__PURE__ */ __name((stream) => {
      if (isReadableStreamInstance(stream)) {
        return collectReadableStream(stream);
      }
      return new Promise((resolve2, reject) => {
        const collector = new Collector();
        stream.pipe(collector);
        stream.on("error", (err2) => {
          collector.end();
          reject(err2);
        });
        collector.on("error", reject);
        collector.on("finish", function() {
          const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
          resolve2(bytes);
        });
      });
    }, "streamCollector");
    var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance");
    async function collectReadableStream(stream) {
      const chunks = [];
      const reader = stream.getReader();
      let isDone = false;
      let length = 0;
      while (!isDone) {
        const { done, value } = await reader.read();
        if (value) {
          chunks.push(value);
          length += value.length;
        }
        isDone = done;
      }
      const collected = new Uint8Array(length);
      let offset = 0;
      for (const chunk of chunks) {
        collected.set(chunk, offset);
        offset += chunk.length;
      }
      return collected;
    }
    __name(collectReadableStream, "collectReadableStream");
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js
var require_dist_cjs15 = __commonJS({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      FetchHttpHandler: () => FetchHttpHandler,
      keepAliveSupport: () => keepAliveSupport,
      streamCollector: () => streamCollector3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var import_querystring_builder = require_dist_cjs13();
    function createRequest(url, requestOptions) {
      return new Request(url, requestOptions);
    }
    __name(createRequest, "createRequest");
    function requestTimeout(timeoutInMs = 0) {
      return new Promise((resolve2, reject) => {
        if (timeoutInMs) {
          setTimeout(() => {
            const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
            timeoutError.name = "TimeoutError";
            reject(timeoutError);
          }, timeoutInMs);
        }
      });
    }
    __name(requestTimeout, "requestTimeout");
    var keepAliveSupport = {
      supported: void 0
    };
    var _a2;
    var FetchHttpHandler = (_a2 = class {
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _a2(instanceOrOptions);
      }
      constructor(options) {
        if (typeof options === "function") {
          this.configProvider = options().then((opts) => opts || {});
        } else {
          this.config = options ?? {};
          this.configProvider = Promise.resolve(this.config);
        }
        if (keepAliveSupport.supported === void 0) {
          keepAliveSupport.supported = Boolean(
            typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")
          );
        }
      }
      destroy() {
      }
      async handle(request, { abortSignal } = {}) {
        var _a3;
        if (!this.config) {
          this.config = await this.configProvider;
        }
        const requestTimeoutInMs = this.config.requestTimeout;
        const keepAlive = this.config.keepAlive === true;
        const credentials2 = this.config.credentials;
        if (abortSignal == null ? void 0 : abortSignal.aborted) {
          const abortError = new Error("Request aborted");
          abortError.name = "AbortError";
          return Promise.reject(abortError);
        }
        let path4 = request.path;
        const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
        if (queryString) {
          path4 += `?${queryString}`;
        }
        if (request.fragment) {
          path4 += `#${request.fragment}`;
        }
        let auth = "";
        if (request.username != null || request.password != null) {
          const username = request.username ?? "";
          const password = request.password ?? "";
          auth = `${username}:${password}@`;
        }
        const { port, method } = request;
        const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path4}`;
        const body = method === "GET" || method === "HEAD" ? void 0 : request.body;
        const requestOptions = {
          body,
          headers: new Headers(request.headers),
          method,
          credentials: credentials2
        };
        if ((_a3 = this.config) == null ? void 0 : _a3.cache) {
          requestOptions.cache = this.config.cache;
        }
        if (body) {
          requestOptions.duplex = "half";
        }
        if (typeof AbortController !== "undefined") {
          requestOptions.signal = abortSignal;
        }
        if (keepAliveSupport.supported) {
          requestOptions.keepalive = keepAlive;
        }
        if (typeof this.config.requestInit === "function") {
          Object.assign(requestOptions, this.config.requestInit(request));
        }
        let removeSignalEventListener = /* @__PURE__ */ __name(() => {
        }, "removeSignalEventListener");
        const fetchRequest = createRequest(url, requestOptions);
        const raceOfPromises = [
          fetch(fetchRequest).then((response) => {
            const fetchHeaders = response.headers;
            const transformedHeaders = {};
            for (const pair of fetchHeaders.entries()) {
              transformedHeaders[pair[0]] = pair[1];
            }
            const hasReadableStream = response.body != void 0;
            if (!hasReadableStream) {
              return response.blob().then((body2) => ({
                response: new import_protocol_http15.HttpResponse({
                  headers: transformedHeaders,
                  reason: response.statusText,
                  statusCode: response.status,
                  body: body2
                })
              }));
            }
            return {
              response: new import_protocol_http15.HttpResponse({
                headers: transformedHeaders,
                reason: response.statusText,
                statusCode: response.status,
                body: response.body
              })
            };
          }),
          requestTimeout(requestTimeoutInMs)
        ];
        if (abortSignal) {
          raceOfPromises.push(
            new Promise((resolve2, reject) => {
              const onAbort = /* @__PURE__ */ __name(() => {
                const abortError = new Error("Request aborted");
                abortError.name = "AbortError";
                reject(abortError);
              }, "onAbort");
              if (typeof abortSignal.addEventListener === "function") {
                const signal = abortSignal;
                signal.addEventListener("abort", onAbort, { once: true });
                removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener");
              } else {
                abortSignal.onabort = onAbort;
              }
            })
          );
        }
        return Promise.race(raceOfPromises).finally(removeSignalEventListener);
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          config[key] = value;
          return config;
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    }, __name(_a2, "FetchHttpHandler"), _a2);
    var import_util_base645 = require_dist_cjs11();
    var streamCollector3 = /* @__PURE__ */ __name(async (stream) => {
      var _a3;
      if (typeof Blob === "function" && stream instanceof Blob || ((_a3 = stream.constructor) == null ? void 0 : _a3.name) === "Blob") {
        if (Blob.prototype.arrayBuffer !== void 0) {
          return new Uint8Array(await stream.arrayBuffer());
        }
        return collectBlob(stream);
      }
      return collectStream(stream);
    }, "streamCollector");
    async function collectBlob(blob) {
      const base64 = await readToBase64(blob);
      const arrayBuffer = (0, import_util_base645.fromBase64)(base64);
      return new Uint8Array(arrayBuffer);
    }
    __name(collectBlob, "collectBlob");
    async function collectStream(stream) {
      const chunks = [];
      const reader = stream.getReader();
      let isDone = false;
      let length = 0;
      while (!isDone) {
        const { done, value } = await reader.read();
        if (value) {
          chunks.push(value);
          length += value.length;
        }
        isDone = done;
      }
      const collected = new Uint8Array(length);
      let offset = 0;
      for (const chunk of chunks) {
        collected.set(chunk, offset);
        offset += chunk.length;
      }
      return collected;
    }
    __name(collectStream, "collectStream");
    function readToBase64(blob) {
      return new Promise((resolve2, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          if (reader.readyState !== 2) {
            return reject(new Error("Reader aborted too early"));
          }
          const result = reader.result ?? "";
          const commaIndex = result.indexOf(",");
          const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
          resolve2(result.substring(dataOffset));
        };
        reader.onabort = () => reject(new Error("Read aborted"));
        reader.onerror = () => reject(reader.error);
        reader.readAsDataURL(blob);
      });
    }
    __name(readToBase64, "readToBase64");
  }
});

// ../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
var require_dist_cjs16 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromHex: () => fromHex,
      toHex: () => toHex
    });
    module2.exports = __toCommonJS2(src_exports);
    var SHORT_TO_HEX = {};
    var HEX_TO_SHORT = {};
    for (let i4 = 0; i4 < 256; i4++) {
      let encodedByte = i4.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX[i4] = encodedByte;
      HEX_TO_SHORT[encodedByte] = i4;
    }
    function fromHex(encoded) {
      if (encoded.length % 2 !== 0) {
        throw new Error("Hex encoded strings must have an even number length");
      }
      const out = new Uint8Array(encoded.length / 2);
      for (let i4 = 0; i4 < encoded.length; i4 += 2) {
        const encodedByte = encoded.slice(i4, i4 + 2).toLowerCase();
        if (encodedByte in HEX_TO_SHORT) {
          out[i4 / 2] = HEX_TO_SHORT[encodedByte];
        } else {
          throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
        }
      }
      return out;
    }
    __name(fromHex, "fromHex");
    function toHex(bytes) {
      let out = "";
      for (let i4 = 0; i4 < bytes.byteLength; i4++) {
        out += SHORT_TO_HEX[bytes[i4]];
      }
      return out;
    }
    __name(toHex, "toHex");
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js
var require_sdk_stream_mixin_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sdkStreamMixin = void 0;
    var fetch_http_handler_1 = require_dist_cjs15();
    var util_base64_1 = require_dist_cjs11();
    var util_hex_encoding_1 = require_dist_cjs16();
    var util_utf8_1 = require_dist_cjs10();
    var stream_type_check_1 = require_stream_type_check();
    var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    var sdkStreamMixin3 = (stream) => {
      var _a2, _b;
      if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) {
        const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream;
        throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
      }
      let transformed = false;
      const transformToByteArray = async () => {
        if (transformed) {
          throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
        }
        transformed = true;
        return await (0, fetch_http_handler_1.streamCollector)(stream);
      };
      const blobToWebStream = (blob) => {
        if (typeof blob.stream !== "function") {
          throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
        }
        return blob.stream();
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === "base64") {
            return (0, util_base64_1.toBase64)(buf);
          } else if (encoding === "hex") {
            return (0, util_hex_encoding_1.toHex)(buf);
          } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
            return (0, util_utf8_1.toUtf8)(buf);
          } else if (typeof TextDecoder === "function") {
            return new TextDecoder(encoding).decode(buf);
          } else {
            throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
          }
          transformed = true;
          if (isBlobInstance(stream)) {
            return blobToWebStream(stream);
          } else if ((0, stream_type_check_1.isReadableStream)(stream)) {
            return stream;
          } else {
            throw new Error(`Cannot transform payload to web stream, got ${stream}`);
          }
        }
      });
    };
    exports2.sdkStreamMixin = sdkStreamMixin3;
    var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js
var require_sdk_stream_mixin = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sdkStreamMixin = void 0;
    var node_http_handler_1 = require_dist_cjs14();
    var util_buffer_from_1 = require_dist_cjs9();
    var stream_1 = require("stream");
    var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser();
    var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    var sdkStreamMixin3 = (stream) => {
      var _a2, _b;
      if (!(stream instanceof stream_1.Readable)) {
        try {
          return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream);
        } catch (e4) {
          const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream;
          throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);
        }
      }
      let transformed = false;
      const transformToByteArray = async () => {
        if (transformed) {
          throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
        }
        transformed = true;
        return await (0, node_http_handler_1.streamCollector)(stream);
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === void 0 || Buffer.isEncoding(encoding)) {
            return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
          } else {
            const decoder = new TextDecoder(encoding);
            return decoder.decode(buf);
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
          }
          if (stream.readableFlowing !== null) {
            throw new Error("The stream has been consumed by other callbacks.");
          }
          if (typeof stream_1.Readable.toWeb !== "function") {
            throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");
          }
          transformed = true;
          return stream_1.Readable.toWeb(stream);
        }
      });
    };
    exports2.sdkStreamMixin = sdkStreamMixin3;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js
var require_splitStream_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.splitStream = splitStream2;
    async function splitStream2(stream) {
      if (typeof stream.stream === "function") {
        stream = stream.stream();
      }
      const readableStream = stream;
      return readableStream.tee();
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js
var require_splitStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.splitStream = splitStream2;
    var stream_1 = require("stream");
    var splitStream_browser_1 = require_splitStream_browser();
    var stream_type_check_1 = require_stream_type_check();
    async function splitStream2(stream) {
      if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) {
        return (0, splitStream_browser_1.splitStream)(stream);
      }
      const stream1 = new stream_1.PassThrough();
      const stream2 = new stream_1.PassThrough();
      stream.pipe(stream1);
      stream.pipe(stream2);
      return [stream1, stream2];
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/index.js
var require_dist_cjs17 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter2
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_base645 = require_dist_cjs11();
    var import_util_utf85 = require_dist_cjs10();
    function transformToString(payload, encoding = "utf-8") {
      if (encoding === "base64") {
        return (0, import_util_base645.toBase64)(payload);
      }
      return (0, import_util_utf85.toUtf8)(payload);
    }
    __name(transformToString, "transformToString");
    function transformFromString(str, encoding) {
      if (encoding === "base64") {
        return Uint8ArrayBlobAdapter2.mutate((0, import_util_base645.fromBase64)(str));
      }
      return Uint8ArrayBlobAdapter2.mutate((0, import_util_utf85.fromUtf8)(str));
    }
    __name(transformFromString, "transformFromString");
    var _a2;
    var Uint8ArrayBlobAdapter2 = (_a2 = class extends Uint8Array {
      /**
       * @param source - such as a string or Stream.
       * @returns a new Uint8ArrayBlobAdapter extending Uint8Array.
       */
      static fromString(source, encoding = "utf-8") {
        switch (typeof source) {
          case "string":
            return transformFromString(source, encoding);
          default:
            throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
        }
      }
      /**
       * @param source - Uint8Array to be mutated.
       * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter.
       */
      static mutate(source) {
        Object.setPrototypeOf(source, _a2.prototype);
        return source;
      }
      /**
       * @param encoding - default 'utf-8'.
       * @returns the blob as string.
       */
      transformToString(encoding = "utf-8") {
        return transformToString(this, encoding);
      }
    }, __name(_a2, "Uint8ArrayBlobAdapter"), _a2);
    __reExport(src_exports, require_ChecksumStream(), module2.exports);
    __reExport(src_exports, require_createChecksumStream(), module2.exports);
    __reExport(src_exports, require_createBufferedReadable(), module2.exports);
    __reExport(src_exports, require_getAwsChunkedEncodingStream(), module2.exports);
    __reExport(src_exports, require_headStream(), module2.exports);
    __reExport(src_exports, require_sdk_stream_mixin(), module2.exports);
    __reExport(src_exports, require_splitStream(), module2.exports);
    __reExport(src_exports, require_stream_type_check(), module2.exports);
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
var import_util_stream, collectBody2;
var init_collect_stream_body = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() {
    import_util_stream = __toESM(require_dist_cjs17());
    collectBody2 = async (streamBody = new Uint8Array(), context) => {
      if (streamBody instanceof Uint8Array) {
        return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody);
      }
      if (!streamBody) {
        return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array());
      }
      const fromContext = context.streamCollector(streamBody);
      return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
function extendedEncodeURIComponent2(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c3) {
    return "%" + c3.charCodeAt(0).toString(16).toUpperCase();
  });
}
var init_extended_encode_uri_component = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() {
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js
var deref;
var init_deref = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() {
    deref = (schemaRef) => {
      if (typeof schemaRef === "function") {
        return schemaRef();
      }
      return schemaRef;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
var import_protocol_http2, import_util_middleware3;
var init_schemaDeserializationMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
    import_protocol_http2 = __toESM(require_dist_cjs2());
    import_util_middleware3 = __toESM(require_dist_cjs6());
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
var import_util_middleware4;
var init_schemaSerializationMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
    import_util_middleware4 = __toESM(require_dist_cjs6());
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
var init_getSchemaSerdePlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
    init_schemaDeserializationMiddleware();
    init_schemaSerializationMiddleware();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
var TypeRegistry;
var init_TypeRegistry = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() {
    TypeRegistry = class _TypeRegistry {
      constructor(namespace, schemas = /* @__PURE__ */ new Map()) {
        this.namespace = namespace;
        this.schemas = schemas;
      }
      static for(namespace) {
        if (!_TypeRegistry.registries.has(namespace)) {
          _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace));
        }
        return _TypeRegistry.registries.get(namespace);
      }
      register(shapeId, schema6) {
        const qualifiedName = this.normalizeShapeId(shapeId);
        const registry = _TypeRegistry.for(this.getNamespace(shapeId));
        registry.schemas.set(qualifiedName, schema6);
      }
      getSchema(shapeId) {
        const id = this.normalizeShapeId(shapeId);
        if (!this.schemas.has(id)) {
          throw new Error(`@smithy/core/schema - schema not found for ${id}`);
        }
        return this.schemas.get(id);
      }
      getBaseException() {
        for (const [id, schema6] of this.schemas.entries()) {
          if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) {
            return schema6;
          }
        }
        return void 0;
      }
      find(predicate) {
        return [...this.schemas.values()].find(predicate);
      }
      destroy() {
        _TypeRegistry.registries.delete(this.namespace);
        this.schemas.clear();
      }
      normalizeShapeId(shapeId) {
        if (shapeId.includes("#")) {
          return shapeId;
        }
        return this.namespace + "#" + shapeId;
      }
      getNamespace(shapeId) {
        return this.normalizeShapeId(shapeId).split("#")[0];
      }
    };
    TypeRegistry.registries = /* @__PURE__ */ new Map();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js
var Schema;
var init_Schema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() {
    Schema = class {
      constructor(name, traits) {
        this.name = name;
        this.traits = traits;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
var ListSchema;
var init_ListSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() {
    init_TypeRegistry();
    init_Schema();
    ListSchema = class extends Schema {
      constructor(name, traits, valueSchema) {
        super(name, traits);
        this.name = name;
        this.traits = traits;
        this.valueSchema = valueSchema;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js
var MapSchema;
var init_MapSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() {
    init_TypeRegistry();
    init_Schema();
    MapSchema = class extends Schema {
      constructor(name, traits, keySchema, valueSchema) {
        super(name, traits);
        this.name = name;
        this.traits = traits;
        this.keySchema = keySchema;
        this.valueSchema = valueSchema;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js
var init_OperationSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() {
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
var StructureSchema;
var init_StructureSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
    init_TypeRegistry();
    init_Schema();
    StructureSchema = class extends Schema {
      constructor(name, traits, memberNames, memberList) {
        super(name, traits);
        this.name = name;
        this.traits = traits;
        this.memberNames = memberNames;
        this.memberList = memberList;
        this.members = {};
        for (let i4 = 0; i4 < memberNames.length; ++i4) {
          this.members[memberNames[i4]] = Array.isArray(memberList[i4]) ? memberList[i4] : [memberList[i4], 0];
        }
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
var init_ErrorSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
    init_TypeRegistry();
    init_StructureSchema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js
var SCHEMA;
var init_sentinels = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() {
    SCHEMA = {
      BLOB: 21,
      STREAMING_BLOB: 42,
      BOOLEAN: 2,
      STRING: 0,
      NUMERIC: 1,
      BIG_INTEGER: 17,
      BIG_DECIMAL: 19,
      DOCUMENT: 15,
      TIMESTAMP_DEFAULT: 4,
      TIMESTAMP_DATE_TIME: 5,
      TIMESTAMP_HTTP_DATE: 6,
      TIMESTAMP_EPOCH_SECONDS: 7,
      LIST_MODIFIER: 64,
      MAP_MODIFIER: 128
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
var SimpleSchema;
var init_SimpleSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
    init_TypeRegistry();
    init_Schema();
    SimpleSchema = class extends Schema {
      constructor(name, schemaRef, traits) {
        super(name, traits);
        this.name = name;
        this.schemaRef = schemaRef;
        this.traits = traits;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js
var NormalizedSchema;
var init_NormalizedSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
    init_deref();
    init_ListSchema();
    init_MapSchema();
    init_sentinels();
    init_SimpleSchema();
    init_StructureSchema();
    NormalizedSchema = class _NormalizedSchema {
      constructor(ref, memberName) {
        var _a2, _b;
        this.ref = ref;
        this.memberName = memberName;
        const traitStack = [];
        let _ref = ref;
        let schema6 = ref;
        this._isMemberSchema = false;
        while (Array.isArray(_ref)) {
          traitStack.push(_ref[1]);
          _ref = _ref[0];
          schema6 = deref(_ref);
          this._isMemberSchema = true;
        }
        if (traitStack.length > 0) {
          this.memberTraits = {};
          for (let i4 = traitStack.length - 1; i4 >= 0; --i4) {
            const traitSet = traitStack[i4];
            Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet));
          }
        } else {
          this.memberTraits = 0;
        }
        if (schema6 instanceof _NormalizedSchema) {
          this.name = schema6.name;
          this.traits = schema6.traits;
          this._isMemberSchema = schema6._isMemberSchema;
          this.schema = schema6.schema;
          this.memberTraits = Object.assign({}, schema6.getMemberTraits(), this.getMemberTraits());
          this.normalizedTraits = void 0;
          this.ref = schema6.ref;
          this.memberName = memberName ?? schema6.memberName;
          return;
        }
        this.schema = deref(schema6);
        if (this.schema && typeof this.schema === "object") {
          this.traits = ((_a2 = this.schema) == null ? void 0 : _a2.traits) ?? {};
        } else {
          this.traits = 0;
        }
        this.name = (typeof this.schema === "object" ? (_b = this.schema) == null ? void 0 : _b.name : void 0) ?? this.memberName ?? this.getSchemaName();
        if (this._isMemberSchema && !memberName) {
          throw new Error(`@smithy/core/schema - NormalizedSchema member schema ${this.getName(true)} must initialize with memberName argument.`);
        }
      }
      static of(ref, memberName) {
        if (ref instanceof _NormalizedSchema) {
          return ref;
        }
        return new _NormalizedSchema(ref, memberName);
      }
      static translateTraits(indicator) {
        if (typeof indicator === "object") {
          return indicator;
        }
        indicator = indicator | 0;
        const traits = {};
        if ((indicator & 1) === 1) {
          traits.httpLabel = 1;
        }
        if ((indicator >> 1 & 1) === 1) {
          traits.idempotent = 1;
        }
        if ((indicator >> 2 & 1) === 1) {
          traits.idempotencyToken = 1;
        }
        if ((indicator >> 3 & 1) === 1) {
          traits.sensitive = 1;
        }
        if ((indicator >> 4 & 1) === 1) {
          traits.httpPayload = 1;
        }
        if ((indicator >> 5 & 1) === 1) {
          traits.httpResponseCode = 1;
        }
        if ((indicator >> 6 & 1) === 1) {
          traits.httpQueryParams = 1;
        }
        return traits;
      }
      static memberFrom(memberSchema, memberName) {
        if (memberSchema instanceof _NormalizedSchema) {
          memberSchema.memberName = memberName;
          memberSchema._isMemberSchema = true;
          return memberSchema;
        }
        return new _NormalizedSchema(memberSchema, memberName);
      }
      getSchema() {
        if (this.schema instanceof _NormalizedSchema) {
          return this.schema = this.schema.getSchema();
        }
        if (this.schema instanceof SimpleSchema) {
          return deref(this.schema.schemaRef);
        }
        return deref(this.schema);
      }
      getName(withNamespace = false) {
        if (!withNamespace) {
          if (this.name && this.name.includes("#")) {
            return this.name.split("#")[1];
          }
        }
        return this.name || void 0;
      }
      getMemberName() {
        if (!this.isMemberSchema()) {
          throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`);
        }
        return this.memberName;
      }
      isMemberSchema() {
        return this._isMemberSchema;
      }
      isUnitSchema() {
        return this.getSchema() === "unit";
      }
      isListSchema() {
        const inner = this.getSchema();
        if (typeof inner === "number") {
          return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER;
        }
        return inner instanceof ListSchema;
      }
      isMapSchema() {
        const inner = this.getSchema();
        if (typeof inner === "number") {
          return inner >= SCHEMA.MAP_MODIFIER && inner <= 255;
        }
        return inner instanceof MapSchema;
      }
      isDocumentSchema() {
        return this.getSchema() === SCHEMA.DOCUMENT;
      }
      isStructSchema() {
        const inner = this.getSchema();
        return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema;
      }
      isBlobSchema() {
        return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB;
      }
      isTimestampSchema() {
        const schema6 = this.getSchema();
        return typeof schema6 === "number" && schema6 >= SCHEMA.TIMESTAMP_DEFAULT && schema6 <= SCHEMA.TIMESTAMP_EPOCH_SECONDS;
      }
      isStringSchema() {
        return this.getSchema() === SCHEMA.STRING;
      }
      isBooleanSchema() {
        return this.getSchema() === SCHEMA.BOOLEAN;
      }
      isNumericSchema() {
        return this.getSchema() === SCHEMA.NUMERIC;
      }
      isBigIntegerSchema() {
        return this.getSchema() === SCHEMA.BIG_INTEGER;
      }
      isBigDecimalSchema() {
        return this.getSchema() === SCHEMA.BIG_DECIMAL;
      }
      isStreaming() {
        const streaming = !!this.getMergedTraits().streaming;
        if (streaming) {
          return true;
        }
        return this.getSchema() === SCHEMA.STREAMING_BLOB;
      }
      getMergedTraits() {
        if (this.normalizedTraits) {
          return this.normalizedTraits;
        }
        this.normalizedTraits = {
          ...this.getOwnTraits(),
          ...this.getMemberTraits()
        };
        return this.normalizedTraits;
      }
      getMemberTraits() {
        return _NormalizedSchema.translateTraits(this.memberTraits);
      }
      getOwnTraits() {
        return _NormalizedSchema.translateTraits(this.traits);
      }
      getKeySchema() {
        if (this.isDocumentSchema()) {
          return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key");
        }
        if (!this.isMapSchema()) {
          throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`);
        }
        const schema6 = this.getSchema();
        if (typeof schema6 === "number") {
          return _NormalizedSchema.memberFrom([63 & schema6, 0], "key");
        }
        return _NormalizedSchema.memberFrom([schema6.keySchema, 0], "key");
      }
      getValueSchema() {
        const schema6 = this.getSchema();
        if (typeof schema6 === "number") {
          if (this.isMapSchema()) {
            return _NormalizedSchema.memberFrom([63 & schema6, 0], "value");
          } else if (this.isListSchema()) {
            return _NormalizedSchema.memberFrom([63 & schema6, 0], "member");
          }
        }
        if (schema6 && typeof schema6 === "object") {
          if (this.isStructSchema()) {
            throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`);
          }
          const collection = schema6;
          if ("valueSchema" in collection) {
            if (this.isMapSchema()) {
              return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value");
            } else if (this.isListSchema()) {
              return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member");
            }
          }
        }
        if (this.isDocumentSchema()) {
          return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value");
        }
        throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`);
      }
      getMemberSchema(member) {
        if (this.isStructSchema()) {
          const struct = this.getSchema();
          if (!(member in struct.members)) {
            throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.`);
          }
          return _NormalizedSchema.memberFrom(struct.members[member], member);
        }
        if (this.isDocumentSchema()) {
          return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member);
        }
        throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`);
      }
      getMemberSchemas() {
        const { schema: schema6 } = this;
        const struct = schema6;
        if (!struct || typeof struct !== "object") {
          return {};
        }
        if ("members" in struct) {
          const buffer = {};
          for (const member of struct.memberNames) {
            buffer[member] = this.getMemberSchema(member);
          }
          return buffer;
        }
        return {};
      }
      *structIterator() {
        if (!this.isStructSchema()) {
          throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema.");
        }
        const struct = this.getSchema();
        for (let i4 = 0; i4 < struct.memberNames.length; ++i4) {
          yield [struct.memberNames[i4], _NormalizedSchema.memberFrom([struct.memberList[i4], 0], struct.memberNames[i4])];
        }
      }
      getSchemaName() {
        var _a2;
        const schema6 = this.getSchema();
        if (typeof schema6 === "number") {
          const _schema = 63 & schema6;
          const container = 192 & schema6;
          const type = ((_a2 = Object.entries(SCHEMA).find(([, value]) => {
            return value === _schema;
          })) == null ? void 0 : _a2[0]) ?? "Unknown";
          switch (container) {
            case SCHEMA.MAP_MODIFIER:
              return `${type}Map`;
            case SCHEMA.LIST_MODIFIER:
              return `${type}List`;
            case 0:
              return type;
          }
        }
        return "Unknown";
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js
var init_schema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() {
    init_deref();
    init_getSchemaSerdePlugin();
    init_ListSchema();
    init_MapSchema();
    init_OperationSchema();
    init_ErrorSchema();
    init_NormalizedSchema();
    init_Schema();
    init_SimpleSchema();
    init_StructureSchema();
    init_sentinels();
    init_TypeRegistry();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js
var copyDocumentWithTransform2;
var init_copyDocumentWithTransform = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() {
    init_schema();
    copyDocumentWithTransform2 = (source, schemaRef, transform = (_3) => _3) => {
      const ns = NormalizedSchema.of(schemaRef);
      switch (typeof source) {
        case "undefined":
        case "boolean":
        case "number":
        case "string":
        case "bigint":
        case "symbol":
          return transform(source, ns);
        case "function":
        case "object":
          if (source === null) {
            return transform(null, ns);
          }
          if (Array.isArray(source)) {
            const newArray = new Array(source.length);
            let i4 = 0;
            for (const item of source) {
              newArray[i4++] = copyDocumentWithTransform2(item, ns.getValueSchema(), transform);
            }
            return transform(newArray, ns);
          }
          if ("byteLength" in source) {
            const newBytes = new Uint8Array(source.byteLength);
            newBytes.set(source, 0);
            return transform(newBytes, ns);
          }
          if (source instanceof Date) {
            return transform(source, ns);
          }
          const newObject = {};
          if (ns.isMapSchema()) {
            for (const key of Object.keys(source)) {
              newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform);
            }
          } else if (ns.isStructSchema()) {
            for (const [key, memberSchema] of ns.structIterator()) {
              newObject[key] = copyDocumentWithTransform2(source[key], memberSchema, transform);
            }
          } else if (ns.isDocumentSchema()) {
            for (const key of Object.keys(source)) {
              newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform);
            }
          }
          return transform(newObject, ns);
        default:
          return transform(source, ns);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
var parseBoolean2, expectBoolean2, expectNumber2, MAX_FLOAT, expectFloat322, expectLong2, expectInt2, expectInt322, expectShort2, expectByte2, expectSizedInt, castInt, expectNonNull2, expectObject2, expectString2, expectUnion2, strictParseDouble2, strictParseFloat2, strictParseFloat322, NUMBER_REGEX, parseNumber, limitedParseDouble2, handleFloat2, limitedParseFloat2, limitedParseFloat322, parseFloatString, strictParseLong2, strictParseInt2, strictParseInt322, strictParseShort2, strictParseByte2, stackTraceWarning, logger2;
var init_parse_utils = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() {
    parseBoolean2 = (value) => {
      switch (value) {
        case "true":
          return true;
        case "false":
          return false;
        default:
          throw new Error(`Unable to parse boolean value "${value}"`);
      }
    };
    expectBoolean2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "number") {
        if (value === 0 || value === 1) {
          logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
        }
        if (value === 0) {
          return false;
        }
        if (value === 1) {
          return true;
        }
      }
      if (typeof value === "string") {
        const lower2 = value.toLowerCase();
        if (lower2 === "false" || lower2 === "true") {
          logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
        }
        if (lower2 === "false") {
          return false;
        }
        if (lower2 === "true") {
          return true;
        }
      }
      if (typeof value === "boolean") {
        return value;
      }
      throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
    };
    expectNumber2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        const parsed = parseFloat(value);
        if (!Number.isNaN(parsed)) {
          if (String(parsed) !== String(value)) {
            logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
          }
          return parsed;
        }
      }
      if (typeof value === "number") {
        return value;
      }
      throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
    };
    MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
    expectFloat322 = (value) => {
      const expected = expectNumber2(value);
      if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
        if (Math.abs(expected) > MAX_FLOAT) {
          throw new TypeError(`Expected 32-bit float, got ${value}`);
        }
      }
      return expected;
    };
    expectLong2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (Number.isInteger(value) && !Number.isNaN(value)) {
        return value;
      }
      throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
    };
    expectInt2 = expectLong2;
    expectInt322 = (value) => expectSizedInt(value, 32);
    expectShort2 = (value) => expectSizedInt(value, 16);
    expectByte2 = (value) => expectSizedInt(value, 8);
    expectSizedInt = (value, size) => {
      const expected = expectLong2(value);
      if (expected !== void 0 && castInt(expected, size) !== expected) {
        throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
      }
      return expected;
    };
    castInt = (value, size) => {
      switch (size) {
        case 32:
          return Int32Array.of(value)[0];
        case 16:
          return Int16Array.of(value)[0];
        case 8:
          return Int8Array.of(value)[0];
      }
    };
    expectNonNull2 = (value, location) => {
      if (value === null || value === void 0) {
        if (location) {
          throw new TypeError(`Expected a non-null value for ${location}`);
        }
        throw new TypeError("Expected a non-null value");
      }
      return value;
    };
    expectObject2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "object" && !Array.isArray(value)) {
        return value;
      }
      const receivedType = Array.isArray(value) ? "array" : typeof value;
      throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
    };
    expectString2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        return value;
      }
      if (["boolean", "number", "bigint"].includes(typeof value)) {
        logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
        return String(value);
      }
      throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
    };
    expectUnion2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      const asObject = expectObject2(value);
      const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k3]) => k3);
      if (setKeys.length === 0) {
        throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
      }
      if (setKeys.length > 1) {
        throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
      }
      return asObject;
    };
    strictParseDouble2 = (value) => {
      if (typeof value == "string") {
        return expectNumber2(parseNumber(value));
      }
      return expectNumber2(value);
    };
    strictParseFloat2 = strictParseDouble2;
    strictParseFloat322 = (value) => {
      if (typeof value == "string") {
        return expectFloat322(parseNumber(value));
      }
      return expectFloat322(value);
    };
    NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
    parseNumber = (value) => {
      const matches = value.match(NUMBER_REGEX);
      if (matches === null || matches[0].length !== value.length) {
        throw new TypeError(`Expected real number, got implicit NaN`);
      }
      return parseFloat(value);
    };
    limitedParseDouble2 = (value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectNumber2(value);
    };
    handleFloat2 = limitedParseDouble2;
    limitedParseFloat2 = limitedParseDouble2;
    limitedParseFloat322 = (value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectFloat322(value);
    };
    parseFloatString = (value) => {
      switch (value) {
        case "NaN":
          return NaN;
        case "Infinity":
          return Infinity;
        case "-Infinity":
          return -Infinity;
        default:
          throw new Error(`Unable to parse float value: ${value}`);
      }
    };
    strictParseLong2 = (value) => {
      if (typeof value === "string") {
        return expectLong2(parseNumber(value));
      }
      return expectLong2(value);
    };
    strictParseInt2 = strictParseLong2;
    strictParseInt322 = (value) => {
      if (typeof value === "string") {
        return expectInt322(parseNumber(value));
      }
      return expectInt322(value);
    };
    strictParseShort2 = (value) => {
      if (typeof value === "string") {
        return expectShort2(parseNumber(value));
      }
      return expectShort2(value);
    };
    strictParseByte2 = (value) => {
      if (typeof value === "string") {
        return expectByte2(parseNumber(value));
      }
      return expectByte2(value);
    };
    stackTraceWarning = (message) => {
      return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s4) => !s4.includes("stackTraceWarning")).join("\n");
    };
    logger2 = {
      warn: console.warn
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js
function dateToUtcString2(date) {
  const year = date.getUTCFullYear();
  const month = date.getUTCMonth();
  const dayOfWeek = date.getUTCDay();
  const dayOfMonthInt = date.getUTCDate();
  const hoursInt = date.getUTCHours();
  const minutesInt = date.getUTCMinutes();
  const secondsInt = date.getUTCSeconds();
  const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
  const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
  const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
  const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
  return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;
}
var DAYS, MONTHS, RFC3339, parseRfc3339DateTime2, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset2, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime2, parseEpochTimestamp2, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
var init_date_utils = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() {
    init_parse_utils();
    DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
    parseRfc3339DateTime2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
      const year = strictParseShort2(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
    };
    RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
    parseRfc3339DateTimeWithOffset2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339_WITH_OFFSET.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
      const year = strictParseShort2(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
      if (offsetStr.toUpperCase() != "Z") {
        date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
      }
      return date;
    };
    IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
    parseRfc7231DateTime2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-7231 date-times must be expressed as strings");
      }
      let match2 = IMF_FIXDATE.exec(value);
      if (match2) {
        const [_3, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
        return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
      }
      match2 = RFC_850_DATE.exec(value);
      if (match2) {
        const [_3, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
        return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), {
          hours,
          minutes,
          seconds,
          fractionalMilliseconds
        }));
      }
      match2 = ASC_TIME.exec(value);
      if (match2) {
        const [_3, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2;
        return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
      }
      throw new TypeError("Invalid RFC-7231 date-time value");
    };
    parseEpochTimestamp2 = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      let valueAsDouble;
      if (typeof value === "number") {
        valueAsDouble = value;
      } else if (typeof value === "string") {
        valueAsDouble = strictParseDouble2(value);
      } else if (typeof value === "object" && value.tag === 1) {
        valueAsDouble = value.value;
      } else {
        throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
      }
      if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
        throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
      }
      return new Date(Math.round(valueAsDouble * 1e3));
    };
    buildDate = (year, month, day, time) => {
      const adjustedMonth = month - 1;
      validateDayOfMonth(year, adjustedMonth, day);
      return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
    };
    parseTwoDigitYear = (value) => {
      const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear();
      const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort2(stripLeadingZeroes(value));
      if (valueInThisCentury < thisYear) {
        return valueInThisCentury + 100;
      }
      return valueInThisCentury;
    };
    FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
    adjustRfc850Year = (input) => {
      if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) {
        return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));
      }
      return input;
    };
    parseMonthByShortName = (value) => {
      const monthIdx = MONTHS.indexOf(value);
      if (monthIdx < 0) {
        throw new TypeError(`Invalid month: ${value}`);
      }
      return monthIdx + 1;
    };
    DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    validateDayOfMonth = (year, month, day) => {
      let maxDays = DAYS_IN_MONTH[month];
      if (month === 1 && isLeapYear(year)) {
        maxDays = 29;
      }
      if (day > maxDays) {
        throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
      }
    };
    isLeapYear = (year) => {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    };
    parseDateValue = (value, type, lower2, upper) => {
      const dateVal = strictParseByte2(stripLeadingZeroes(value));
      if (dateVal < lower2 || dateVal > upper) {
        throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`);
      }
      return dateVal;
    };
    parseMilliseconds = (value) => {
      if (value === null || value === void 0) {
        return 0;
      }
      return strictParseFloat322("0." + value) * 1e3;
    };
    parseOffsetToMilliseconds = (value) => {
      const directionStr = value[0];
      let direction = 1;
      if (directionStr == "+") {
        direction = 1;
      } else if (directionStr == "-") {
        direction = -1;
      } else {
        throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
      }
      const hour = Number(value.substring(1, 3));
      const minute = Number(value.substring(4, 6));
      return direction * (hour * 60 + minute) * 60 * 1e3;
    };
    stripLeadingZeroes = (value) => {
      let idx = 0;
      while (idx < value.length - 1 && value.charAt(idx) === "0") {
        idx++;
      }
      if (idx === 0) {
        return value;
      }
      return value.slice(idx);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js
var LazyJsonString2;
var init_lazy_json = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() {
    LazyJsonString2 = function LazyJsonString3(val2) {
      const str = Object.assign(new String(val2), {
        deserializeJSON() {
          return JSON.parse(String(val2));
        },
        toString() {
          return String(val2);
        },
        toJSON() {
          return String(val2);
        }
      });
      return str;
    };
    LazyJsonString2.from = (object) => {
      if (object && typeof object === "object" && (object instanceof LazyJsonString2 || "deserializeJSON" in object)) {
        return object;
      } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) {
        return LazyJsonString2(String(object));
      }
      return LazyJsonString2(JSON.stringify(object));
    };
    LazyJsonString2.fromObject = LazyJsonString2.from;
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js
function quoteHeader2(part) {
  if (part.includes(",") || part.includes('"')) {
    part = `"${part.replace(/"/g, '\\"')}"`;
  }
  return part;
}
var init_quote_header = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() {
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js
function splitEvery2(value, delimiter, numDelimiters) {
  if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) {
    throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery.");
  }
  const segments = value.split(delimiter);
  if (numDelimiters === 1) {
    return segments;
  }
  const compoundSegments = [];
  let currentSegment = "";
  for (let i4 = 0; i4 < segments.length; i4++) {
    if (currentSegment === "") {
      currentSegment = segments[i4];
    } else {
      currentSegment += delimiter + segments[i4];
    }
    if ((i4 + 1) % numDelimiters === 0) {
      compoundSegments.push(currentSegment);
      currentSegment = "";
    }
  }
  if (currentSegment !== "") {
    compoundSegments.push(currentSegment);
  }
  return compoundSegments;
}
var init_split_every = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() {
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js
var splitHeader2;
var init_split_header = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() {
    splitHeader2 = (value) => {
      const z2 = value.length;
      const values = [];
      let withinQuotes = false;
      let prevChar = void 0;
      let anchor = 0;
      for (let i4 = 0; i4 < z2; ++i4) {
        const char = value[i4];
        switch (char) {
          case `"`:
            if (prevChar !== "\\") {
              withinQuotes = !withinQuotes;
            }
            break;
          case ",":
            if (!withinQuotes) {
              values.push(value.slice(anchor, i4));
              anchor = i4 + 1;
            }
            break;
          default:
        }
        prevChar = char;
      }
      values.push(value.slice(anchor));
      return values.map((v6) => {
        v6 = v6.trim();
        const z3 = v6.length;
        if (z3 < 2) {
          return v6;
        }
        if (v6[0] === `"` && v6[z3 - 1] === `"`) {
          v6 = v6.slice(1, z3 - 1);
        }
        return v6.replace(/\\"/g, '"');
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js
function nv2(string2) {
  return new NumericValue2(string2, "bigDecimal");
}
var NumericValue2;
var init_NumericValue = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() {
    NumericValue2 = class {
      constructor(string2, type) {
        this.string = string2;
        this.type = type;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js
var serde_exports = {};
__export(serde_exports, {
  LazyJsonString: () => LazyJsonString2,
  NumericValue: () => NumericValue2,
  copyDocumentWithTransform: () => copyDocumentWithTransform2,
  dateToUtcString: () => dateToUtcString2,
  expectBoolean: () => expectBoolean2,
  expectByte: () => expectByte2,
  expectFloat32: () => expectFloat322,
  expectInt: () => expectInt2,
  expectInt32: () => expectInt322,
  expectLong: () => expectLong2,
  expectNonNull: () => expectNonNull2,
  expectNumber: () => expectNumber2,
  expectObject: () => expectObject2,
  expectShort: () => expectShort2,
  expectString: () => expectString2,
  expectUnion: () => expectUnion2,
  handleFloat: () => handleFloat2,
  limitedParseDouble: () => limitedParseDouble2,
  limitedParseFloat: () => limitedParseFloat2,
  limitedParseFloat32: () => limitedParseFloat322,
  logger: () => logger2,
  nv: () => nv2,
  parseBoolean: () => parseBoolean2,
  parseEpochTimestamp: () => parseEpochTimestamp2,
  parseRfc3339DateTime: () => parseRfc3339DateTime2,
  parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset2,
  parseRfc7231DateTime: () => parseRfc7231DateTime2,
  quoteHeader: () => quoteHeader2,
  splitEvery: () => splitEvery2,
  splitHeader: () => splitHeader2,
  strictParseByte: () => strictParseByte2,
  strictParseDouble: () => strictParseDouble2,
  strictParseFloat: () => strictParseFloat2,
  strictParseFloat32: () => strictParseFloat322,
  strictParseInt: () => strictParseInt2,
  strictParseInt32: () => strictParseInt322,
  strictParseLong: () => strictParseLong2,
  strictParseShort: () => strictParseShort2
});
var init_serde = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() {
    init_copyDocumentWithTransform();
    init_date_utils();
    init_lazy_json();
    init_parse_utils();
    init_quote_header();
    init_split_every();
    init_split_header();
    init_NumericValue();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
var import_protocol_http3, import_util_stream2, HttpProtocol;
var init_HttpProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
    init_schema();
    init_serde();
    import_protocol_http3 = __toESM(require_dist_cjs2());
    import_util_stream2 = __toESM(require_dist_cjs17());
    init_collect_stream_body();
    HttpProtocol = class {
      constructor(options) {
        this.options = options;
      }
      getRequestType() {
        return import_protocol_http3.HttpRequest;
      }
      getResponseType() {
        return import_protocol_http3.HttpResponse;
      }
      setSerdeContext(serdeContext) {
        this.serdeContext = serdeContext;
        this.serializer.setSerdeContext(serdeContext);
        this.deserializer.setSerdeContext(serdeContext);
        if (this.getPayloadCodec()) {
          this.getPayloadCodec().setSerdeContext(serdeContext);
        }
      }
      updateServiceEndpoint(request, endpoint) {
        if ("url" in endpoint) {
          request.protocol = endpoint.url.protocol;
          request.hostname = endpoint.url.hostname;
          request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0;
          request.path = endpoint.url.pathname;
          request.fragment = endpoint.url.hash || void 0;
          request.username = endpoint.url.username || void 0;
          request.password = endpoint.url.password || void 0;
          for (const [k3, v6] of endpoint.url.searchParams.entries()) {
            if (!request.query) {
              request.query = {};
            }
            request.query[k3] = v6;
          }
          return request;
        } else {
          request.protocol = endpoint.protocol;
          request.hostname = endpoint.hostname;
          request.port = endpoint.port ? Number(endpoint.port) : void 0;
          request.path = endpoint.path;
          request.query = {
            ...endpoint.query
          };
          return request;
        }
      }
      setHostPrefix(request, operationSchema, input) {
        var _a2;
        const operationNs = NormalizedSchema.of(operationSchema);
        const inputNs = NormalizedSchema.of(operationSchema.input);
        if (operationNs.getMergedTraits().endpoint) {
          let hostPrefix = (_a2 = operationNs.getMergedTraits().endpoint) == null ? void 0 : _a2[0];
          if (typeof hostPrefix === "string") {
            const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel);
            for (const [name] of hostLabelInputs) {
              const replacement = input[name];
              if (typeof replacement !== "string") {
                throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);
              }
              hostPrefix = hostPrefix.replace(`{${name}}`, replacement);
            }
            request.hostname = hostPrefix + request.hostname;
          }
        }
      }
      deserializeMetadata(output) {
        return {
          httpStatusCode: output.statusCode,
          requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
          extendedRequestId: output.headers["x-amz-id-2"],
          cfId: output.headers["x-amz-cf-id"]
        };
      }
      async deserializeHttpMessage(schema6, context, response, headerBindings, dataObject) {
        const deserializer = this.deserializer;
        const ns = NormalizedSchema.of(schema6);
        const nonHttpBindingMembers = [];
        for (const [memberName, memberSchema] of ns.structIterator()) {
          const memberTraits = memberSchema.getMemberTraits();
          if (memberTraits.httpPayload) {
            const isStreaming = memberSchema.isStreaming();
            if (isStreaming) {
              const isEventStream = memberSchema.isStructSchema();
              if (isEventStream) {
                const context2 = this.serdeContext;
                if (!context2.eventStreamMarshaller) {
                  throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");
                }
                const memberSchemas = memberSchema.getMemberSchemas();
                dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => {
                  const unionMember = Object.keys(event).find((key) => {
                    return key !== "__type";
                  }) ?? "";
                  if (unionMember in memberSchemas) {
                    const eventStreamSchema = memberSchemas[unionMember];
                    return {
                      [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body)
                    };
                  } else {
                    return {
                      $unknown: event
                    };
                  }
                });
              } else {
                dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body);
              }
            } else if (response.body) {
              const bytes = await collectBody2(response.body, context);
              if (bytes.byteLength > 0) {
                dataObject[memberName] = await deserializer.read(memberSchema, bytes);
              }
            }
          } else if (memberTraits.httpHeader) {
            const key = String(memberTraits.httpHeader).toLowerCase();
            const value = response.headers[key];
            if (null != value) {
              if (memberSchema.isListSchema()) {
                const headerListValueSchema = memberSchema.getValueSchema();
                let sections;
                if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === SCHEMA.TIMESTAMP_DEFAULT) {
                  sections = splitEvery2(value, ",", 2);
                } else {
                  sections = splitHeader2(value);
                }
                const list = [];
                for (const section of sections) {
                  list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim()));
                }
                dataObject[memberName] = list;
              } else {
                dataObject[memberName] = await deserializer.read(memberSchema, value);
              }
            }
          } else if (memberTraits.httpPrefixHeaders !== void 0) {
            dataObject[memberName] = {};
            for (const [header, value] of Object.entries(response.headers)) {
              if (!headerBindings.has(header) && header.startsWith(memberTraits.httpPrefixHeaders)) {
                dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read([memberSchema.getValueSchema(), { httpHeader: header }], value);
              }
            }
          } else if (memberTraits.httpResponseCode) {
            dataObject[memberName] = response.statusCode;
          } else {
            nonHttpBindingMembers.push(memberName);
          }
        }
        return nonHttpBindingMembers;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
var import_protocol_http4, HttpBindingProtocol;
var init_HttpBindingProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() {
    init_schema();
    import_protocol_http4 = __toESM(require_dist_cjs2());
    init_collect_stream_body();
    init_extended_encode_uri_component();
    init_HttpProtocol();
    HttpBindingProtocol = class extends HttpProtocol {
      async serializeRequest(operationSchema, input, context) {
        const serializer = this.serializer;
        const query = {};
        const headers = {};
        const endpoint = await context.endpoint();
        const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input);
        const schema6 = ns.getSchema();
        let hasNonHttpBindingMember = false;
        let payload;
        const request = new import_protocol_http4.HttpRequest({
          protocol: "",
          hostname: "",
          port: void 0,
          path: "",
          fragment: void 0,
          query,
          headers,
          body: void 0
        });
        if (endpoint) {
          this.updateServiceEndpoint(request, endpoint);
          this.setHostPrefix(request, operationSchema, input);
          const opTraits = NormalizedSchema.translateTraits(operationSchema.traits);
          if (opTraits.http) {
            request.method = opTraits.http[0];
            const [path4, search] = opTraits.http[1].split("?");
            if (request.path == "/") {
              request.path = path4;
            } else {
              request.path += path4;
            }
            const traitSearchParams = new URLSearchParams(search ?? "");
            Object.assign(query, Object.fromEntries(traitSearchParams));
          }
        }
        const _input = {
          ...input
        };
        for (const memberName of Object.keys(_input)) {
          const memberNs = ns.getMemberSchema(memberName);
          if (memberNs === void 0) {
            continue;
          }
          const memberTraits = memberNs.getMergedTraits();
          const inputMember = _input[memberName];
          if (memberTraits.httpPayload) {
            const isStreaming = memberNs.isStreaming();
            if (isStreaming) {
              const isEventStream = memberNs.isStructSchema();
              if (isEventStream) {
                throw new Error("serialization of event streams is not yet implemented");
              } else {
                payload = inputMember;
              }
            } else {
              serializer.write(memberNs, inputMember);
              payload = serializer.flush();
            }
          } else if (memberTraits.httpLabel) {
            serializer.write(memberNs, inputMember);
            const replacement = serializer.flush();
            if (request.path.includes(`{${memberName}+}`)) {
              request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent2).join("/"));
            } else if (request.path.includes(`{${memberName}}`)) {
              request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent2(replacement));
            }
            delete _input[memberName];
          } else if (memberTraits.httpHeader) {
            serializer.write(memberNs, inputMember);
            headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush());
            delete _input[memberName];
          } else if (typeof memberTraits.httpPrefixHeaders === "string") {
            for (const [key, val2] of Object.entries(inputMember)) {
              const amalgam = memberTraits.httpPrefixHeaders + key;
              serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val2);
              headers[amalgam.toLowerCase()] = serializer.flush();
            }
            delete _input[memberName];
          } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) {
            this.serializeQuery(memberNs, inputMember, query);
            delete _input[memberName];
          } else {
            hasNonHttpBindingMember = true;
          }
        }
        if (hasNonHttpBindingMember && input) {
          serializer.write(schema6, _input);
          payload = serializer.flush();
        }
        request.headers = headers;
        request.query = query;
        request.body = payload;
        return request;
      }
      serializeQuery(ns, data, query) {
        const serializer = this.serializer;
        const traits = ns.getMergedTraits();
        if (traits.httpQueryParams) {
          for (const [key, val2] of Object.entries(data)) {
            if (!(key in query)) {
              this.serializeQuery(NormalizedSchema.of([
                ns.getValueSchema(),
                {
                  ...traits,
                  httpQuery: key,
                  httpQueryParams: void 0
                }
              ]), val2, query);
            }
          }
          return;
        }
        if (ns.isListSchema()) {
          const sparse = !!ns.getMergedTraits().sparse;
          const buffer = [];
          for (const item of data) {
            serializer.write([ns.getValueSchema(), traits], item);
            const serializable = serializer.flush();
            if (sparse || serializable !== void 0) {
              buffer.push(serializable);
            }
          }
          query[traits.httpQuery] = buffer;
        } else {
          serializer.write([ns, traits], data);
          query[traits.httpQuery] = serializer.flush();
        }
      }
      async deserializeResponse(operationSchema, context, response) {
        const deserializer = this.deserializer;
        const ns = NormalizedSchema.of(operationSchema.output);
        const dataObject = {};
        if (response.statusCode >= 300) {
          const bytes = await collectBody2(response.body, context);
          if (bytes.byteLength > 0) {
            Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes));
          }
          await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));
          throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.");
        }
        for (const header in response.headers) {
          const value = response.headers[header];
          delete response.headers[header];
          response.headers[header.toLowerCase()] = value;
        }
        const headerBindings = new Set(Object.values(ns.getMemberSchemas()).map((schema6) => {
          return schema6.getMergedTraits().httpHeader;
        }).filter(Boolean));
        const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, headerBindings, dataObject);
        if (nonHttpBindingMembers.length) {
          const bytes = await collectBody2(response.body, context);
          if (bytes.byteLength > 0) {
            const dataFromBody = await deserializer.read(ns, bytes);
            for (const member of nonHttpBindingMembers) {
              dataObject[member] = dataFromBody[member];
            }
          }
        }
        const output = {
          $metadata: this.deserializeMetadata(response),
          ...dataObject
        };
        return output;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
var import_protocol_http5, RpcProtocol;
var init_RpcProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() {
    init_schema();
    import_protocol_http5 = __toESM(require_dist_cjs2());
    init_collect_stream_body();
    init_HttpProtocol();
    RpcProtocol = class extends HttpProtocol {
      async serializeRequest(operationSchema, input, context) {
        const serializer = this.serializer;
        const query = {};
        const headers = {};
        const endpoint = await context.endpoint();
        const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input);
        const schema6 = ns.getSchema();
        let payload;
        const request = new import_protocol_http5.HttpRequest({
          protocol: "",
          hostname: "",
          port: void 0,
          path: "/",
          fragment: void 0,
          query,
          headers,
          body: void 0
        });
        if (endpoint) {
          this.updateServiceEndpoint(request, endpoint);
          this.setHostPrefix(request, operationSchema, input);
        }
        const _input = {
          ...input
        };
        if (input) {
          serializer.write(schema6, _input);
          payload = serializer.flush();
        }
        request.headers = headers;
        request.query = query;
        request.body = payload;
        request.method = "POST";
        return request;
      }
      async deserializeResponse(operationSchema, context, response) {
        const deserializer = this.deserializer;
        const ns = NormalizedSchema.of(operationSchema.output);
        const dataObject = {};
        if (response.statusCode >= 300) {
          const bytes2 = await collectBody2(response.body, context);
          if (bytes2.byteLength > 0) {
            Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes2));
          }
          await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));
          throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.");
        }
        for (const header in response.headers) {
          const value = response.headers[header];
          delete response.headers[header];
          response.headers[header.toLowerCase()] = value;
        }
        const bytes = await collectBody2(response.body, context);
        if (bytes.byteLength > 0) {
          Object.assign(dataObject, await deserializer.read(ns, bytes));
        }
        const output = {
          $metadata: this.deserializeMetadata(response),
          ...dataObject
        };
        return output;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
var resolvedPath2;
var init_resolve_path = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() {
    init_extended_encode_uri_component();
    resolvedPath2 = (resolvedPath3, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
      if (input != null && input[memberName] !== void 0) {
        const labelValue = labelValueProvider();
        if (labelValue.length <= 0) {
          throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
        }
        resolvedPath3 = resolvedPath3.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent2(segment)).join("/") : extendedEncodeURIComponent2(labelValue));
      } else {
        throw new Error("No value provided for input HTTP label: " + memberName + ".");
      }
      return resolvedPath3;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
function requestBuilder(input, context) {
  return new RequestBuilder(input, context);
}
var import_protocol_http6, RequestBuilder;
var init_requestBuilder = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() {
    import_protocol_http6 = __toESM(require_dist_cjs2());
    init_resolve_path();
    RequestBuilder = class {
      constructor(input, context) {
        this.input = input;
        this.context = context;
        this.query = {};
        this.method = "";
        this.headers = {};
        this.path = "";
        this.body = null;
        this.hostname = "";
        this.resolvePathStack = [];
      }
      async build() {
        const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint();
        this.path = basePath;
        for (const resolvePath of this.resolvePathStack) {
          resolvePath(this.path);
        }
        return new import_protocol_http6.HttpRequest({
          protocol,
          hostname: this.hostname || hostname,
          port,
          method: this.method,
          path: this.path,
          query: this.query,
          body: this.body,
          headers: this.headers
        });
      }
      hn(hostname) {
        this.hostname = hostname;
        return this;
      }
      bp(uriLabel) {
        this.resolvePathStack.push((basePath) => {
          this.path = `${(basePath == null ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
        });
        return this;
      }
      p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
        this.resolvePathStack.push((path4) => {
          this.path = resolvedPath2(path4, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
        });
        return this;
      }
      h(headers) {
        this.headers = headers;
        return this;
      }
      q(query) {
        this.query = query;
        return this;
      }
      b(body) {
        this.body = body;
        return this;
      }
      m(method) {
        this.method = method;
        return this;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
function determineTimestampFormat(ns, settings) {
  if (settings.timestampFormat.useTrait) {
    if (ns.isTimestampSchema() && (ns.getSchema() === SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === SCHEMA.TIMESTAMP_EPOCH_SECONDS)) {
      return ns.getSchema();
    }
  }
  const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits();
  const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0;
  return bindingFormat ?? settings.timestampFormat.default;
}
var init_determineTimestampFormat = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() {
    init_schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
var import_util_base64, import_util_utf8, FromStringShapeDeserializer;
var init_FromStringShapeDeserializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() {
    init_schema();
    init_serde();
    import_util_base64 = __toESM(require_dist_cjs11());
    import_util_utf8 = __toESM(require_dist_cjs10());
    init_determineTimestampFormat();
    FromStringShapeDeserializer = class {
      constructor(settings) {
        this.settings = settings;
      }
      setSerdeContext(serdeContext) {
        this.serdeContext = serdeContext;
      }
      read(_schema, data) {
        var _a2;
        const ns = NormalizedSchema.of(_schema);
        if (ns.isListSchema()) {
          return splitHeader2(data).map((item) => this.read(ns.getValueSchema(), item));
        }
        if (ns.isBlobSchema()) {
          return (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Decoder) ?? import_util_base64.fromBase64)(data);
        }
        if (ns.isTimestampSchema()) {
          const format = determineTimestampFormat(ns, this.settings);
          switch (format) {
            case SCHEMA.TIMESTAMP_DATE_TIME:
              return parseRfc3339DateTimeWithOffset2(data);
            case SCHEMA.TIMESTAMP_HTTP_DATE:
              return parseRfc7231DateTime2(data);
            case SCHEMA.TIMESTAMP_EPOCH_SECONDS:
              return parseEpochTimestamp2(data);
            default:
              console.warn("Missing timestamp format, parsing value with Date constructor:", data);
              return new Date(data);
          }
        }
        if (ns.isStringSchema()) {
          const mediaType = ns.getMergedTraits().mediaType;
          let intermediateValue = data;
          if (mediaType) {
            if (ns.getMergedTraits().httpHeader) {
              intermediateValue = this.base64ToUtf8(intermediateValue);
            }
            const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
            if (isJson) {
              intermediateValue = LazyJsonString2.from(intermediateValue);
            }
            return intermediateValue;
          }
        }
        switch (true) {
          case ns.isNumericSchema():
            return Number(data);
          case ns.isBigIntegerSchema():
            return BigInt(data);
          case ns.isBigDecimalSchema():
            return new NumericValue2(data, "bigDecimal");
          case ns.isBooleanSchema():
            return String(data).toLowerCase() === "true";
        }
        return data;
      }
      base64ToUtf8(base64String) {
        var _a2, _b;
        return (((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf8.toUtf8)((((_b = this.serdeContext) == null ? void 0 : _b.base64Decoder) ?? import_util_base64.fromBase64)(base64String));
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
var import_util_utf82, HttpInterceptingShapeDeserializer;
var init_HttpInterceptingShapeDeserializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
    init_schema();
    import_util_utf82 = __toESM(require_dist_cjs10());
    init_FromStringShapeDeserializer();
    HttpInterceptingShapeDeserializer = class {
      constructor(codecDeserializer, codecSettings) {
        this.codecDeserializer = codecDeserializer;
        this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);
      }
      setSerdeContext(serdeContext) {
        this.stringDeserializer.setSerdeContext(serdeContext);
        this.codecDeserializer.setSerdeContext(serdeContext);
        this.serdeContext = serdeContext;
      }
      read(schema6, data) {
        var _a2, _b;
        const ns = NormalizedSchema.of(schema6);
        const traits = ns.getMergedTraits();
        const toString = ((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf82.toUtf8;
        if (traits.httpHeader || traits.httpResponseCode) {
          return this.stringDeserializer.read(ns, toString(data));
        }
        if (traits.httpPayload) {
          if (ns.isBlobSchema()) {
            const toBytes = ((_b = this.serdeContext) == null ? void 0 : _b.utf8Decoder) ?? import_util_utf82.fromUtf8;
            if (typeof data === "string") {
              return toBytes(data);
            }
            return data;
          } else if (ns.isStringSchema()) {
            if ("byteLength" in data) {
              return toString(data);
            }
            return data;
          }
        }
        return this.codecDeserializer.read(ns, data);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
var import_util_base642, ToStringShapeSerializer;
var init_ToStringShapeSerializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() {
    init_schema();
    init_serde();
    import_util_base642 = __toESM(require_dist_cjs11());
    init_determineTimestampFormat();
    ToStringShapeSerializer = class {
      constructor(settings) {
        this.settings = settings;
        this.stringBuffer = "";
        this.serdeContext = void 0;
      }
      setSerdeContext(serdeContext) {
        this.serdeContext = serdeContext;
      }
      write(schema6, value) {
        var _a2, _b;
        const ns = NormalizedSchema.of(schema6);
        switch (typeof value) {
          case "object":
            if (value === null) {
              this.stringBuffer = "null";
              return;
            }
            if (ns.isTimestampSchema()) {
              if (!(value instanceof Date)) {
                throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`);
              }
              const format = determineTimestampFormat(ns, this.settings);
              switch (format) {
                case SCHEMA.TIMESTAMP_DATE_TIME:
                  this.stringBuffer = value.toISOString().replace(".000Z", "Z");
                  break;
                case SCHEMA.TIMESTAMP_HTTP_DATE:
                  this.stringBuffer = dateToUtcString2(value);
                  break;
                case SCHEMA.TIMESTAMP_EPOCH_SECONDS:
                  this.stringBuffer = String(value.getTime() / 1e3);
                  break;
                default:
                  console.warn("Missing timestamp format, using epoch seconds", value);
                  this.stringBuffer = String(value.getTime() / 1e3);
              }
              return;
            }
            if (ns.isBlobSchema() && "byteLength" in value) {
              this.stringBuffer = (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Encoder) ?? import_util_base642.toBase64)(value);
              return;
            }
            if (ns.isListSchema() && Array.isArray(value)) {
              let buffer = "";
              for (const item of value) {
                this.write([ns.getValueSchema(), ns.getMergedTraits()], item);
                const headerItem = this.flush();
                const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader2(headerItem);
                if (buffer !== "") {
                  buffer += ", ";
                }
                buffer += serialized;
              }
              this.stringBuffer = buffer;
              return;
            }
            this.stringBuffer = JSON.stringify(value, null, 2);
            break;
          case "string":
            const mediaType = ns.getMergedTraits().mediaType;
            let intermediateValue = value;
            if (mediaType) {
              const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
              if (isJson) {
                intermediateValue = LazyJsonString2.from(intermediateValue);
              }
              if (ns.getMergedTraits().httpHeader) {
                this.stringBuffer = (((_b = this.serdeContext) == null ? void 0 : _b.base64Encoder) ?? import_util_base642.toBase64)(intermediateValue.toString());
                return;
              }
            }
            this.stringBuffer = value;
            break;
          default:
            this.stringBuffer = String(value);
        }
      }
      flush() {
        const buffer = this.stringBuffer;
        this.stringBuffer = "";
        return buffer;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
var HttpInterceptingShapeSerializer;
var init_HttpInterceptingShapeSerializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() {
    init_schema();
    init_ToStringShapeSerializer();
    HttpInterceptingShapeSerializer = class {
      constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) {
        this.codecSerializer = codecSerializer;
        this.stringSerializer = stringSerializer;
      }
      setSerdeContext(serdeContext) {
        this.codecSerializer.setSerdeContext(serdeContext);
        this.stringSerializer.setSerdeContext(serdeContext);
      }
      write(schema6, value) {
        const ns = NormalizedSchema.of(schema6);
        const traits = ns.getMergedTraits();
        if (traits.httpHeader || traits.httpLabel || traits.httpQuery) {
          this.stringSerializer.write(ns, value);
          this.buffer = this.stringSerializer.flush();
          return;
        }
        return this.codecSerializer.write(ns, value);
      }
      flush() {
        if (this.buffer !== void 0) {
          const buffer = this.buffer;
          this.buffer = void 0;
          return buffer;
        }
        return this.codecSerializer.flush();
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
var protocols_exports = {};
__export(protocols_exports, {
  FromStringShapeDeserializer: () => FromStringShapeDeserializer,
  HttpBindingProtocol: () => HttpBindingProtocol,
  HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer,
  HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer,
  RequestBuilder: () => RequestBuilder,
  RpcProtocol: () => RpcProtocol,
  ToStringShapeSerializer: () => ToStringShapeSerializer,
  collectBody: () => collectBody2,
  determineTimestampFormat: () => determineTimestampFormat,
  extendedEncodeURIComponent: () => extendedEncodeURIComponent2,
  requestBuilder: () => requestBuilder,
  resolvedPath: () => resolvedPath2
});
var init_protocols = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() {
    init_collect_stream_body();
    init_extended_encode_uri_component();
    init_HttpBindingProtocol();
    init_RpcProtocol();
    init_requestBuilder();
    init_resolve_path();
    init_FromStringShapeDeserializer();
    init_HttpInterceptingShapeDeserializer();
    init_HttpInterceptingShapeSerializer();
    init_ToStringShapeSerializer();
    init_determineTimestampFormat();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
var init_requestBuilder2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
    init_protocols();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js
function setFeature(context, feature, value) {
  if (!context.__smithy_context) {
    context.__smithy_context = {
      features: {}
    };
  } else if (!context.__smithy_context.features) {
    context.__smithy_context.features = {};
  }
  context.__smithy_context.features[feature] = value;
}
var init_setFeature = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() {
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig;
var init_DefaultIdentityProviderConfig = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
    DefaultIdentityProviderConfig = class {
      constructor(config) {
        this.authSchemes = /* @__PURE__ */ new Map();
        for (const [key, value] of Object.entries(config)) {
          if (value !== void 0) {
            this.authSchemes.set(key, value);
          }
        }
      }
      getIdentityProvider(schemeId) {
        return this.authSchemes.get(schemeId);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var import_protocol_http7, import_types4, HttpApiKeyAuthSigner;
var init_httpApiKeyAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
    import_protocol_http7 = __toESM(require_dist_cjs2());
    import_types4 = __toESM(require_dist_cjs());
    HttpApiKeyAuthSigner = class {
      async sign(httpRequest, identity, signingProperties) {
        if (!signingProperties) {
          throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");
        }
        if (!signingProperties.name) {
          throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing");
        }
        if (!signingProperties.in) {
          throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing");
        }
        if (!identity.apiKey) {
          throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");
        }
        const clonedRequest = import_protocol_http7.HttpRequest.clone(httpRequest);
        if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.QUERY) {
          clonedRequest.query[signingProperties.name] = identity.apiKey;
        } else if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.HEADER) {
          clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey;
        } else {
          throw new Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`");
        }
        return clonedRequest;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var import_protocol_http8, HttpBearerAuthSigner;
var init_httpBearerAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
    import_protocol_http8 = __toESM(require_dist_cjs2());
    HttpBearerAuthSigner = class {
      async sign(httpRequest, identity, signingProperties) {
        const clonedRequest = import_protocol_http8.HttpRequest.clone(httpRequest);
        if (!identity.token) {
          throw new Error("request could not be signed with `token` since the `token` is not defined");
        }
        clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`;
        return clonedRequest;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner;
var init_noAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
    NoAuthSigner = class {
      async sign(httpRequest, identity, signingProperties) {
        return httpRequest;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
    init_httpApiKeyAuth();
    init_httpBearerAuth();
    init_noAuth();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
var init_memoizeIdentityProvider = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
    createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
    EXPIRATION_MS = 3e5;
    isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
    doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
    memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
      if (provider === void 0) {
        return void 0;
      }
      const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = async (options) => {
        if (!pending) {
          pending = normalizedProvider(options);
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      };
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
            resolved = await coalesceProvider(options);
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
          resolved = await coalesceProvider(options);
        }
        if (isConstant) {
          return resolved;
        }
        if (!requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider(options);
          return resolved;
        }
        return resolved;
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
    init_DefaultIdentityProviderConfig();
    init_httpAuthSchemes();
    init_memoizeIdentityProvider();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js
var dist_es_exports = {};
__export(dist_es_exports, {
  DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig,
  EXPIRATION_MS: () => EXPIRATION_MS,
  HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner,
  HttpBearerAuthSigner: () => HttpBearerAuthSigner,
  NoAuthSigner: () => NoAuthSigner,
  createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction,
  createPaginator: () => createPaginator,
  doesIdentityRequireRefresh: () => doesIdentityRequireRefresh,
  getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin,
  getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin,
  getHttpSigningPlugin: () => getHttpSigningPlugin,
  getSmithyContext: () => getSmithyContext,
  httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions,
  httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware,
  httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions,
  httpSigningMiddleware: () => httpSigningMiddleware,
  httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions,
  isIdentityExpired: () => isIdentityExpired,
  memoizeIdentityProvider: () => memoizeIdentityProvider,
  normalizeProvider: () => normalizeProvider,
  requestBuilder: () => requestBuilder,
  setFeature: () => setFeature
});
var init_dist_es = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() {
    init_getSmithyContext();
    init_middleware_http_auth_scheme();
    init_middleware_http_signing();
    init_normalizeProvider();
    init_createPaginator();
    init_requestBuilder2();
    init_setFeature();
    init_util_identity_and_auth();
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-cjs/index.js
var require_dist_cjs18 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      EndpointCache: () => EndpointCache3,
      EndpointError: () => EndpointError2,
      customEndpointFunctions: () => customEndpointFunctions3,
      isIpAddress: () => isIpAddress2,
      isValidHostLabel: () => isValidHostLabel,
      resolveEndpoint: () => resolveEndpoint4
    });
    module2.exports = __toCommonJS2(src_exports);
    var _a2;
    var EndpointCache3 = (_a2 = class {
      /**
       * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed
       *                 before keys are dropped.
       * @param [params] - list of params to consider as part of the cache key.
       *
       * If the params list is not populated, no caching will happen.
       * This may be out of order depending on how the object is created and arrives to this class.
       */
      constructor({ size, params }) {
        this.data = /* @__PURE__ */ new Map();
        this.parameters = [];
        this.capacity = size ?? 50;
        if (params) {
          this.parameters = params;
        }
      }
      /**
       * @param endpointParams - query for endpoint.
       * @param resolver - provider of the value if not present.
       * @returns endpoint corresponding to the query.
       */
      get(endpointParams, resolver) {
        const key = this.hash(endpointParams);
        if (key === false) {
          return resolver();
        }
        if (!this.data.has(key)) {
          if (this.data.size > this.capacity + 10) {
            const keys = this.data.keys();
            let i4 = 0;
            while (true) {
              const { value, done } = keys.next();
              this.data.delete(value);
              if (done || ++i4 > 10) {
                break;
              }
            }
          }
          this.data.set(key, resolver());
        }
        return this.data.get(key);
      }
      size() {
        return this.data.size;
      }
      /**
       * @returns cache key or false if not cachable.
       */
      hash(endpointParams) {
        let buffer = "";
        const { parameters } = this;
        if (parameters.length === 0) {
          return false;
        }
        for (const param of parameters) {
          const val2 = String(endpointParams[param] ?? "");
          if (val2.includes("|;")) {
            return false;
          }
          buffer += val2 + "|;";
        }
        return buffer;
      }
    }, __name(_a2, "EndpointCache"), _a2);
    var IP_V4_REGEX = new RegExp(
      `^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`
    );
    var isIpAddress2 = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress");
    var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
    var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
      if (!allowSubDomains) {
        return VALID_HOST_LABEL_REGEX.test(value);
      }
      const labels = value.split(".");
      for (const label of labels) {
        if (!isValidHostLabel(label)) {
          return false;
        }
      }
      return true;
    }, "isValidHostLabel");
    var customEndpointFunctions3 = {};
    var debugId = "endpoints";
    function toDebugString(input) {
      if (typeof input !== "object" || input == null) {
        return input;
      }
      if ("ref" in input) {
        return `$${toDebugString(input.ref)}`;
      }
      if ("fn" in input) {
        return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
      }
      return JSON.stringify(input, null, 2);
    }
    __name(toDebugString, "toDebugString");
    var _a3;
    var EndpointError2 = (_a3 = class extends Error {
      constructor(message) {
        super(message);
        this.name = "EndpointError";
      }
    }, __name(_a3, "EndpointError"), _a3);
    var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals");
    var getAttrPathList = /* @__PURE__ */ __name((path4) => {
      const parts = path4.split(".");
      const pathList = [];
      for (const part of parts) {
        const squareBracketIndex = part.indexOf("[");
        if (squareBracketIndex !== -1) {
          if (part.indexOf("]") !== part.length - 1) {
            throw new EndpointError2(`Path: '${path4}' does not end with ']'`);
          }
          const arrayIndex = part.slice(squareBracketIndex + 1, -1);
          if (Number.isNaN(parseInt(arrayIndex))) {
            throw new EndpointError2(`Invalid array index: '${arrayIndex}' in path: '${path4}'`);
          }
          if (squareBracketIndex !== 0) {
            pathList.push(part.slice(0, squareBracketIndex));
          }
          pathList.push(arrayIndex);
        } else {
          pathList.push(part);
        }
      }
      return pathList;
    }, "getAttrPathList");
    var getAttr = /* @__PURE__ */ __name((value, path4) => getAttrPathList(path4).reduce((acc, index6) => {
      if (typeof acc !== "object") {
        throw new EndpointError2(`Index '${index6}' in '${path4}' not found in '${JSON.stringify(value)}'`);
      } else if (Array.isArray(acc)) {
        return acc[parseInt(index6)];
      }
      return acc[index6];
    }, value), "getAttr");
    var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet");
    var not = /* @__PURE__ */ __name((value) => !value, "not");
    var import_types32 = require_dist_cjs();
    var DEFAULT_PORTS = {
      [import_types32.EndpointURLScheme.HTTP]: 80,
      [import_types32.EndpointURLScheme.HTTPS]: 443
    };
    var parseURL = /* @__PURE__ */ __name((value) => {
      const whatwgURL = (() => {
        try {
          if (value instanceof URL) {
            return value;
          }
          if (typeof value === "object" && "hostname" in value) {
            const { hostname: hostname2, port, protocol: protocol2 = "", path: path4 = "", query = {} } = value;
            const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path4}`);
            url.search = Object.entries(query).map(([k3, v6]) => `${k3}=${v6}`).join("&");
            return url;
          }
          return new URL(value);
        } catch (error2) {
          return null;
        }
      })();
      if (!whatwgURL) {
        console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
        return null;
      }
      const urlString = whatwgURL.href;
      const { host, hostname, pathname, protocol, search } = whatwgURL;
      if (search) {
        return null;
      }
      const scheme = protocol.slice(0, -1);
      if (!Object.values(import_types32.EndpointURLScheme).includes(scheme)) {
        return null;
      }
      const isIp = isIpAddress2(hostname);
      const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
      const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
      return {
        scheme,
        authority,
        path: pathname,
        normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
        isIp
      };
    }, "parseURL");
    var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals");
    var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => {
      if (start >= stop || input.length < stop) {
        return null;
      }
      if (!reverse) {
        return input.substring(start, stop);
      }
      return input.substring(input.length - stop, input.length - start);
    }, "substring");
    var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode");
    var endpointFunctions = {
      booleanEquals,
      getAttr,
      isSet,
      isValidHostLabel,
      not,
      parseURL,
      stringEquals,
      substring,
      uriEncode
    };
    var evaluateTemplate = /* @__PURE__ */ __name((template, options) => {
      const evaluatedTemplateArr = [];
      const templateContext = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      let currentIndex = 0;
      while (currentIndex < template.length) {
        const openingBraceIndex = template.indexOf("{", currentIndex);
        if (openingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(currentIndex));
          break;
        }
        evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
        const closingBraceIndex = template.indexOf("}", openingBraceIndex);
        if (closingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex));
          break;
        }
        if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
          currentIndex = closingBraceIndex + 2;
        }
        const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
        if (parameterName.includes("#")) {
          const [refName, attrName] = parameterName.split("#");
          evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
        } else {
          evaluatedTemplateArr.push(templateContext[parameterName]);
        }
        currentIndex = closingBraceIndex + 1;
      }
      return evaluatedTemplateArr.join("");
    }, "evaluateTemplate");
    var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => {
      const referenceRecord = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      return referenceRecord[ref];
    }, "getReferenceValue");
    var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => {
      if (typeof obj === "string") {
        return evaluateTemplate(obj, options);
      } else if (obj["fn"]) {
        return callFunction(obj, options);
      } else if (obj["ref"]) {
        return getReferenceValue(obj, options);
      }
      throw new EndpointError2(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
    }, "evaluateExpression");
    var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => {
      const evaluatedArgs = argv.map(
        (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options)
      );
      const fnSegments = fn.split(".");
      if (fnSegments[0] in customEndpointFunctions3 && fnSegments[1] != null) {
        return customEndpointFunctions3[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
      }
      return endpointFunctions[fn](...evaluatedArgs);
    }, "callFunction");
    var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => {
      var _a4, _b;
      if (assign && assign in options.referenceRecord) {
        throw new EndpointError2(`'${assign}' is already defined in Reference Record.`);
      }
      const value = callFunction(fnArgs, options);
      (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
      return {
        result: value === "" ? true : !!value,
        ...assign != null && { toAssign: { name: assign, value } }
      };
    }, "evaluateCondition");
    var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => {
      var _a4, _b;
      const conditionsReferenceRecord = {};
      for (const condition of conditions) {
        const { result, toAssign } = evaluateCondition(condition, {
          ...options,
          referenceRecord: {
            ...options.referenceRecord,
            ...conditionsReferenceRecord
          }
        });
        if (!result) {
          return { result };
        }
        if (toAssign) {
          conditionsReferenceRecord[toAssign.name] = toAssign.value;
          (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
        }
      }
      return { result: true, referenceRecord: conditionsReferenceRecord };
    }, "evaluateConditions");
    var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce(
      (acc, [headerKey, headerVal]) => ({
        ...acc,
        [headerKey]: headerVal.map((headerValEntry) => {
          const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
          if (typeof processedExpr !== "string") {
            throw new EndpointError2(`Header '${headerKey}' value '${processedExpr}' is not a string`);
          }
          return processedExpr;
        })
      }),
      {}
    ), "getEndpointHeaders");
    var getEndpointProperty = /* @__PURE__ */ __name((property, options) => {
      if (Array.isArray(property)) {
        return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
      }
      switch (typeof property) {
        case "string":
          return evaluateTemplate(property, options);
        case "object":
          if (property === null) {
            throw new EndpointError2(`Unexpected endpoint property: ${property}`);
          }
          return getEndpointProperties(property, options);
        case "boolean":
          return property;
        default:
          throw new EndpointError2(`Unexpected endpoint property type: ${typeof property}`);
      }
    }, "getEndpointProperty");
    var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce(
      (acc, [propertyKey, propertyVal]) => ({
        ...acc,
        [propertyKey]: getEndpointProperty(propertyVal, options)
      }),
      {}
    ), "getEndpointProperties");
    var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => {
      const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
      if (typeof expression === "string") {
        try {
          return new URL(expression);
        } catch (error2) {
          console.error(`Failed to construct URL with ${expression}`, error2);
          throw error2;
        }
      }
      throw new EndpointError2(`Endpoint URL must be a string, got ${typeof expression}`);
    }, "getEndpointUrl");
    var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => {
      var _a4, _b;
      const { conditions, endpoint } = endpointRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      const endpointRuleOptions = {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      };
      const { url, properties, headers } = endpoint;
      (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
      return {
        ...headers != void 0 && {
          headers: getEndpointHeaders(headers, endpointRuleOptions)
        },
        ...properties != void 0 && {
          properties: getEndpointProperties(properties, endpointRuleOptions)
        },
        url: getEndpointUrl(url, endpointRuleOptions)
      };
    }, "evaluateEndpointRule");
    var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => {
      const { conditions, error: error2 } = errorRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      throw new EndpointError2(
        evaluateExpression(error2, "Error", {
          ...options,
          referenceRecord: { ...options.referenceRecord, ...referenceRecord }
        })
      );
    }, "evaluateErrorRule");
    var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => {
      const { conditions, rules } = treeRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      return evaluateRules(rules, {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      });
    }, "evaluateTreeRule");
    var evaluateRules = /* @__PURE__ */ __name((rules, options) => {
      for (const rule of rules) {
        if (rule.type === "endpoint") {
          const endpointOrUndefined = evaluateEndpointRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else if (rule.type === "error") {
          evaluateErrorRule(rule, options);
        } else if (rule.type === "tree") {
          const endpointOrUndefined = evaluateTreeRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else {
          throw new EndpointError2(`Unknown endpoint rule: ${rule}`);
        }
      }
      throw new EndpointError2(`Rules evaluation failed`);
    }, "evaluateRules");
    var resolveEndpoint4 = /* @__PURE__ */ __name((ruleSetObject, options) => {
      var _a4, _b, _c, _d;
      const { endpointParams, logger: logger3 } = options;
      const { parameters, rules } = ruleSetObject;
      (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
      const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k3, v6]) => [k3, v6.default]);
      if (paramsWithDefault.length > 0) {
        for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
          endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
        }
      }
      const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k3]) => k3);
      for (const requiredParam of requiredParams) {
        if (endpointParams[requiredParam] == null) {
          throw new EndpointError2(`Missing required parameter: '${requiredParam}'`);
        }
      }
      const endpoint = evaluateRules(rules, { endpointParams, logger: logger3, referenceRecord: {} });
      (_d = (_c = options.logger) == null ? void 0 : _c.debug) == null ? void 0 : _d.call(_c, `${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
      return endpoint;
    }, "resolveEndpoint");
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js
var require_dist_cjs19 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      ConditionObject: () => import_util_endpoints5.ConditionObject,
      DeprecatedObject: () => import_util_endpoints5.DeprecatedObject,
      EndpointError: () => import_util_endpoints5.EndpointError,
      EndpointObject: () => import_util_endpoints5.EndpointObject,
      EndpointObjectHeaders: () => import_util_endpoints5.EndpointObjectHeaders,
      EndpointObjectProperties: () => import_util_endpoints5.EndpointObjectProperties,
      EndpointParams: () => import_util_endpoints5.EndpointParams,
      EndpointResolverOptions: () => import_util_endpoints5.EndpointResolverOptions,
      EndpointRuleObject: () => import_util_endpoints5.EndpointRuleObject,
      ErrorRuleObject: () => import_util_endpoints5.ErrorRuleObject,
      EvaluateOptions: () => import_util_endpoints5.EvaluateOptions,
      Expression: () => import_util_endpoints5.Expression,
      FunctionArgv: () => import_util_endpoints5.FunctionArgv,
      FunctionObject: () => import_util_endpoints5.FunctionObject,
      FunctionReturn: () => import_util_endpoints5.FunctionReturn,
      ParameterObject: () => import_util_endpoints5.ParameterObject,
      ReferenceObject: () => import_util_endpoints5.ReferenceObject,
      ReferenceRecord: () => import_util_endpoints5.ReferenceRecord,
      RuleSetObject: () => import_util_endpoints5.RuleSetObject,
      RuleSetRules: () => import_util_endpoints5.RuleSetRules,
      TreeRuleObject: () => import_util_endpoints5.TreeRuleObject,
      awsEndpointFunctions: () => awsEndpointFunctions3,
      getUserAgentPrefix: () => getUserAgentPrefix,
      isIpAddress: () => import_util_endpoints5.isIpAddress,
      partition: () => partition,
      resolveEndpoint: () => import_util_endpoints5.resolveEndpoint,
      setPartitionInfo: () => setPartitionInfo,
      useDefaultPartitionInfo: () => useDefaultPartitionInfo
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_util_endpoints5 = require_dist_cjs18();
    var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
      if (allowSubDomains) {
        for (const label of value.split(".")) {
          if (!isVirtualHostableS3Bucket(label)) {
            return false;
          }
        }
        return true;
      }
      if (!(0, import_util_endpoints5.isValidHostLabel)(value)) {
        return false;
      }
      if (value.length < 3 || value.length > 63) {
        return false;
      }
      if (value !== value.toLowerCase()) {
        return false;
      }
      if ((0, import_util_endpoints5.isIpAddress)(value)) {
        return false;
      }
      return true;
    }, "isVirtualHostableS3Bucket");
    var ARN_DELIMITER = ":";
    var RESOURCE_DELIMITER = "/";
    var parseArn = /* @__PURE__ */ __name((value) => {
      const segments = value.split(ARN_DELIMITER);
      if (segments.length < 6) return null;
      const [arn, partition2, service, region, accountId, ...resourcePath] = segments;
      if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null;
      const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
      return {
        partition: partition2,
        service,
        region,
        accountId,
        resourceId
      };
    }, "parseArn");
    var partitions_default = {
      partitions: [{
        id: "aws",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-east-1",
          name: "aws",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
        regions: {
          "af-south-1": {
            description: "Africa (Cape Town)"
          },
          "ap-east-1": {
            description: "Asia Pacific (Hong Kong)"
          },
          "ap-northeast-1": {
            description: "Asia Pacific (Tokyo)"
          },
          "ap-northeast-2": {
            description: "Asia Pacific (Seoul)"
          },
          "ap-northeast-3": {
            description: "Asia Pacific (Osaka)"
          },
          "ap-south-1": {
            description: "Asia Pacific (Mumbai)"
          },
          "ap-south-2": {
            description: "Asia Pacific (Hyderabad)"
          },
          "ap-southeast-1": {
            description: "Asia Pacific (Singapore)"
          },
          "ap-southeast-2": {
            description: "Asia Pacific (Sydney)"
          },
          "ap-southeast-3": {
            description: "Asia Pacific (Jakarta)"
          },
          "ap-southeast-4": {
            description: "Asia Pacific (Melbourne)"
          },
          "ap-southeast-5": {
            description: "Asia Pacific (Malaysia)"
          },
          "ap-southeast-7": {
            description: "Asia Pacific (Thailand)"
          },
          "aws-global": {
            description: "AWS Standard global region"
          },
          "ca-central-1": {
            description: "Canada (Central)"
          },
          "ca-west-1": {
            description: "Canada West (Calgary)"
          },
          "eu-central-1": {
            description: "Europe (Frankfurt)"
          },
          "eu-central-2": {
            description: "Europe (Zurich)"
          },
          "eu-north-1": {
            description: "Europe (Stockholm)"
          },
          "eu-south-1": {
            description: "Europe (Milan)"
          },
          "eu-south-2": {
            description: "Europe (Spain)"
          },
          "eu-west-1": {
            description: "Europe (Ireland)"
          },
          "eu-west-2": {
            description: "Europe (London)"
          },
          "eu-west-3": {
            description: "Europe (Paris)"
          },
          "il-central-1": {
            description: "Israel (Tel Aviv)"
          },
          "me-central-1": {
            description: "Middle East (UAE)"
          },
          "me-south-1": {
            description: "Middle East (Bahrain)"
          },
          "mx-central-1": {
            description: "Mexico (Central)"
          },
          "sa-east-1": {
            description: "South America (Sao Paulo)"
          },
          "us-east-1": {
            description: "US East (N. Virginia)"
          },
          "us-east-2": {
            description: "US East (Ohio)"
          },
          "us-west-1": {
            description: "US West (N. California)"
          },
          "us-west-2": {
            description: "US West (Oregon)"
          }
        }
      }, {
        id: "aws-cn",
        outputs: {
          dnsSuffix: "amazonaws.com.cn",
          dualStackDnsSuffix: "api.amazonwebservices.com.cn",
          implicitGlobalRegion: "cn-northwest-1",
          name: "aws-cn",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^cn\\-\\w+\\-\\d+$",
        regions: {
          "aws-cn-global": {
            description: "AWS China global region"
          },
          "cn-north-1": {
            description: "China (Beijing)"
          },
          "cn-northwest-1": {
            description: "China (Ningxia)"
          }
        }
      }, {
        id: "aws-us-gov",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-gov-west-1",
          name: "aws-us-gov",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
        regions: {
          "aws-us-gov-global": {
            description: "AWS GovCloud (US) global region"
          },
          "us-gov-east-1": {
            description: "AWS GovCloud (US-East)"
          },
          "us-gov-west-1": {
            description: "AWS GovCloud (US-West)"
          }
        }
      }, {
        id: "aws-iso",
        outputs: {
          dnsSuffix: "c2s.ic.gov",
          dualStackDnsSuffix: "c2s.ic.gov",
          implicitGlobalRegion: "us-iso-east-1",
          name: "aws-iso",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-global": {
            description: "AWS ISO (US) global region"
          },
          "us-iso-east-1": {
            description: "US ISO East"
          },
          "us-iso-west-1": {
            description: "US ISO WEST"
          }
        }
      }, {
        id: "aws-iso-b",
        outputs: {
          dnsSuffix: "sc2s.sgov.gov",
          dualStackDnsSuffix: "sc2s.sgov.gov",
          implicitGlobalRegion: "us-isob-east-1",
          name: "aws-iso-b",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-b-global": {
            description: "AWS ISOB (US) global region"
          },
          "us-isob-east-1": {
            description: "US ISOB East (Ohio)"
          }
        }
      }, {
        id: "aws-iso-e",
        outputs: {
          dnsSuffix: "cloud.adc-e.uk",
          dualStackDnsSuffix: "cloud.adc-e.uk",
          implicitGlobalRegion: "eu-isoe-west-1",
          name: "aws-iso-e",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-e-global": {
            description: "AWS ISOE (Europe) global region"
          },
          "eu-isoe-west-1": {
            description: "EU ISOE West"
          }
        }
      }, {
        id: "aws-iso-f",
        outputs: {
          dnsSuffix: "csp.hci.ic.gov",
          dualStackDnsSuffix: "csp.hci.ic.gov",
          implicitGlobalRegion: "us-isof-south-1",
          name: "aws-iso-f",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-f-global": {
            description: "AWS ISOF global region"
          },
          "us-isof-east-1": {
            description: "US ISOF EAST"
          },
          "us-isof-south-1": {
            description: "US ISOF SOUTH"
          }
        }
      }, {
        id: "aws-eusc",
        outputs: {
          dnsSuffix: "amazonaws.eu",
          dualStackDnsSuffix: "amazonaws.eu",
          implicitGlobalRegion: "eusc-de-east-1",
          name: "aws-eusc",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
        regions: {
          "eusc-de-east-1": {
            description: "EU (Germany)"
          }
        }
      }],
      version: "1.1"
    };
    var selectedPartitionsInfo = partitions_default;
    var selectedUserAgentPrefix = "";
    var partition = /* @__PURE__ */ __name((value) => {
      const { partitions } = selectedPartitionsInfo;
      for (const partition2 of partitions) {
        const { regions, outputs: outputs2 } = partition2;
        for (const [region, regionData] of Object.entries(regions)) {
          if (region === value) {
            return {
              ...outputs2,
              ...regionData
            };
          }
        }
      }
      for (const partition2 of partitions) {
        const { regionRegex, outputs: outputs2 } = partition2;
        if (new RegExp(regionRegex).test(value)) {
          return {
            ...outputs2
          };
        }
      }
      const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws");
      if (!DEFAULT_PARTITION) {
        throw new Error(
          "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."
        );
      }
      return {
        ...DEFAULT_PARTITION.outputs
      };
    }, "partition");
    var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => {
      selectedPartitionsInfo = partitionsInfo;
      selectedUserAgentPrefix = userAgentPrefix;
    }, "setPartitionInfo");
    var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => {
      setPartitionInfo(partitions_default, "");
    }, "useDefaultPartitionInfo");
    var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix");
    var awsEndpointFunctions3 = {
      isVirtualHostableS3Bucket,
      parseArn,
      partition
    };
    import_util_endpoints5.customEndpointFunctions.aws = awsEndpointFunctions3;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
var state, emitWarningIfUnsupportedVersion;
var init_emitWarningIfUnsupportedVersion = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
    state = {
      warningEmitted: false
    };
    emitWarningIfUnsupportedVersion = (version3) => {
      if (version3 && !state.warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 18) {
        state.warningEmitted = true;
        process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
no longer support Node.js 16.x on January 6, 2025.

To continue receiving updates to AWS services, bug fixes, and security
updates please upgrade to a supported Node.js LTS version.

More information can be found at: https://a.co/74kJMmI`);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
function setCredentialFeature(credentials2, feature, value) {
  if (!credentials2.$source) {
    credentials2.$source = {};
  }
  credentials2.$source[feature] = value;
  return credentials2;
}
var init_setCredentialFeature = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() {
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
function setFeature2(context, feature, value) {
  if (!context.__aws_sdk_context) {
    context.__aws_sdk_context = {
      features: {}
    };
  } else if (!context.__aws_sdk_context.features) {
    context.__aws_sdk_context.features = {};
  }
  context.__aws_sdk_context.features[feature] = value;
}
var init_setFeature2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() {
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
var client_exports = {};
__export(client_exports, {
  emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
  setCredentialFeature: () => setCredentialFeature,
  setFeature: () => setFeature2,
  state: () => state
});
var init_client = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
    init_emitWarningIfUnsupportedVersion();
    init_setCredentialFeature();
    init_setFeature2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
var import_protocol_http9, getDateHeader;
var init_getDateHeader = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
    import_protocol_http9 = __toESM(require_dist_cjs2());
    getDateHeader = (response) => {
      var _a2, _b;
      return import_protocol_http9.HttpResponse.isInstance(response) ? ((_a2 = response.headers) == null ? void 0 : _a2.date) ?? ((_b = response.headers) == null ? void 0 : _b.Date) : void 0;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
var getSkewCorrectedDate;
var init_getSkewCorrectedDate = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
    getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
var isClockSkewed;
var init_isClockSkewed = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
    init_getSkewCorrectedDate();
    isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
var getUpdatedSystemClockOffset;
var init_getUpdatedSystemClockOffset = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
    init_isClockSkewed();
    getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
      const clockTimeInMs = Date.parse(clockTime);
      if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
        return clockTimeInMs - Date.now();
      }
      return currentSystemClockOffset;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
var init_utils6 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
    init_getDateHeader();
    init_getSkewCorrectedDate();
    init_getUpdatedSystemClockOffset();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
var import_protocol_http10, throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer, AWSSDKSigV4Signer;
var init_AwsSdkSigV4Signer = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
    import_protocol_http10 = __toESM(require_dist_cjs2());
    init_utils6();
    throwSigningPropertyError = (name, property) => {
      if (!property) {
        throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
      }
      return property;
    };
    validateSigningProperties = async (signingProperties) => {
      var _a2, _b, _c;
      const context = throwSigningPropertyError("context", signingProperties.context);
      const config = throwSigningPropertyError("config", signingProperties.config);
      const authScheme = (_c = (_b = (_a2 = context.endpointV2) == null ? void 0 : _a2.properties) == null ? void 0 : _b.authSchemes) == null ? void 0 : _c[0];
      const signerFunction = throwSigningPropertyError("signer", config.signer);
      const signer = await signerFunction(authScheme);
      const signingRegion = signingProperties == null ? void 0 : signingProperties.signingRegion;
      const signingRegionSet = signingProperties == null ? void 0 : signingProperties.signingRegionSet;
      const signingName = signingProperties == null ? void 0 : signingProperties.signingName;
      return {
        config,
        signer,
        signingRegion,
        signingRegionSet,
        signingName
      };
    };
    AwsSdkSigV4Signer = class {
      async sign(httpRequest, identity, signingProperties) {
        var _a2;
        if (!import_protocol_http10.HttpRequest.isInstance(httpRequest)) {
          throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
        }
        const validatedProps = await validateSigningProperties(signingProperties);
        const { config, signer } = validatedProps;
        let { signingRegion, signingName } = validatedProps;
        const handlerExecutionContext = signingProperties.context;
        if (((_a2 = handlerExecutionContext == null ? void 0 : handlerExecutionContext.authSchemes) == null ? void 0 : _a2.length) ?? 0 > 1) {
          const [first, second] = handlerExecutionContext.authSchemes;
          if ((first == null ? void 0 : first.name) === "sigv4a" && (second == null ? void 0 : second.name) === "sigv4") {
            signingRegion = (second == null ? void 0 : second.signingRegion) ?? signingRegion;
            signingName = (second == null ? void 0 : second.signingName) ?? signingName;
          }
        }
        const signedRequest = await signer.sign(httpRequest, {
          signingDate: getSkewCorrectedDate(config.systemClockOffset),
          signingRegion,
          signingService: signingName
        });
        return signedRequest;
      }
      errorHandler(signingProperties) {
        return (error2) => {
          const serverTime = error2.ServerTime ?? getDateHeader(error2.$response);
          if (serverTime) {
            const config = throwSigningPropertyError("config", signingProperties.config);
            const initialSystemClockOffset = config.systemClockOffset;
            config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
            const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
            if (clockSkewCorrected && error2.$metadata) {
              error2.$metadata.clockSkewCorrected = true;
            }
          }
          throw error2;
        };
      }
      successHandler(httpResponse, signingProperties) {
        const dateHeader = getDateHeader(httpResponse);
        if (dateHeader) {
          const config = throwSigningPropertyError("config", signingProperties.config);
          config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
        }
      }
    };
    AWSSDKSigV4Signer = AwsSdkSigV4Signer;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js
var import_protocol_http11, AwsSdkSigV4ASigner;
var init_AwsSdkSigV4ASigner = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js"() {
    import_protocol_http11 = __toESM(require_dist_cjs2());
    init_utils6();
    init_AwsSdkSigV4Signer();
    AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer {
      async sign(httpRequest, identity, signingProperties) {
        var _a2;
        if (!import_protocol_http11.HttpRequest.isInstance(httpRequest)) {
          throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
        }
        const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
        const configResolvedSigningRegionSet = await ((_a2 = config.sigv4aSigningRegionSet) == null ? void 0 : _a2.call(config));
        const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(",");
        const signedRequest = await signer.sign(httpRequest, {
          signingDate: getSkewCorrectedDate(config.systemClockOffset),
          signingRegion: multiRegionOverride,
          signingService: signingName
        });
        return signedRequest;
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js
var getArrayForCommaSeparatedString;
var init_getArrayForCommaSeparatedString = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() {
    getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js
var getBearerTokenEnvKey;
var init_getBearerTokenEnvKey = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() {
    getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js
var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() {
    init_getArrayForCommaSeparatedString();
    init_getBearerTokenEnvKey();
    NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
    NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
    NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
      environmentVariableSelector: (env3, options) => {
        if (options == null ? void 0 : options.signingName) {
          const bearerTokenKey = getBearerTokenEnvKey(options.signingName);
          if (bearerTokenKey in env3)
            return ["httpBearerAuth"];
        }
        if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env3))
          return void 0;
        return getArrayForCommaSeparatedString(env3[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
      },
      configFileSelector: (profile) => {
        if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))
          return void 0;
        return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
      },
      default: []
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-cjs/index.js
var require_dist_cjs20 = __commonJS({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CredentialsProviderError: () => CredentialsProviderError,
      ProviderError: () => ProviderError2,
      TokenProviderError: () => TokenProviderError,
      chain: () => chain,
      fromStatic: () => fromStatic,
      memoize: () => memoize
    });
    module2.exports = __toCommonJS2(src_exports);
    var _a2;
    var ProviderError2 = (_a2 = class extends Error {
      constructor(message, options = true) {
        var _a5;
        let logger3;
        let tryNextLink = true;
        if (typeof options === "boolean") {
          logger3 = void 0;
          tryNextLink = options;
        } else if (options != null && typeof options === "object") {
          logger3 = options.logger;
          tryNextLink = options.tryNextLink ?? true;
        }
        super(message);
        this.name = "ProviderError";
        this.tryNextLink = tryNextLink;
        Object.setPrototypeOf(this, _a2.prototype);
        (_a5 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a5.call(logger3, `@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
      }
      /**
       * @deprecated use new operator.
       */
      static from(error2, options = true) {
        return Object.assign(new this(error2.message, options), error2);
      }
    }, __name(_a2, "ProviderError"), _a2);
    var _a3;
    var CredentialsProviderError = (_a3 = class extends ProviderError2 {
      /**
       * @override
       */
      constructor(message, options = true) {
        super(message, options);
        this.name = "CredentialsProviderError";
        Object.setPrototypeOf(this, _a3.prototype);
      }
    }, __name(_a3, "CredentialsProviderError"), _a3);
    var _a4;
    var TokenProviderError = (_a4 = class extends ProviderError2 {
      /**
       * @override
       */
      constructor(message, options = true) {
        super(message, options);
        this.name = "TokenProviderError";
        Object.setPrototypeOf(this, _a4.prototype);
      }
    }, __name(_a4, "TokenProviderError"), _a4);
    var chain = /* @__PURE__ */ __name((...providers) => async () => {
      if (providers.length === 0) {
        throw new ProviderError2("No providers in chain");
      }
      let lastProviderError;
      for (const provider of providers) {
        try {
          const credentials2 = await provider();
          return credentials2;
        } catch (err2) {
          lastProviderError = err2;
          if (err2 == null ? void 0 : err2.tryNextLink) {
            continue;
          }
          throw err2;
        }
      }
      throw lastProviderError;
    }, "chain");
    var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic");
    var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => {
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = /* @__PURE__ */ __name(async () => {
        if (!pending) {
          pending = provider();
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      }, "coalesceProvider");
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
            resolved = await coalesceProvider();
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
          resolved = await coalesceProvider();
        }
        if (isConstant) {
          return resolved;
        }
        if (requiresRefresh && !requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider();
          return resolved;
        }
        return resolved;
      };
    }, "memoize");
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
var import_property_provider, resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS;
var init_resolveAwsSdkSigV4AConfig = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
    init_dist_es();
    import_property_provider = __toESM(require_dist_cjs20());
    resolveAwsSdkSigV4AConfig = (config) => {
      config.sigv4aSigningRegionSet = normalizeProvider(config.sigv4aSigningRegionSet);
      return config;
    };
    NODE_SIGV4A_CONFIG_OPTIONS = {
      environmentVariableSelector(env3) {
        if (env3.AWS_SIGV4A_SIGNING_REGION_SET) {
          return env3.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_3) => _3.trim());
        }
        throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", {
          tryNextLink: true
        });
      },
      configFileSelector(profile) {
        if (profile.sigv4a_signing_region_set) {
          return (profile.sigv4a_signing_region_set ?? "").split(",").map((_3) => _3.trim());
        }
        throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", {
          tryNextLink: true
        });
      },
      default: void 0
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-cjs/index.js
var require_dist_cjs21 = __commonJS({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER,
      ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A,
      ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM,
      ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS,
      AMZ_DATE_HEADER: () => AMZ_DATE_HEADER,
      AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM,
      AUTH_HEADER: () => AUTH_HEADER,
      CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM,
      DATE_HEADER: () => DATE_HEADER,
      EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER,
      EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM,
      GENERATED_HEADERS: () => GENERATED_HEADERS,
      HOST_HEADER: () => HOST_HEADER,
      KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER,
      MAX_CACHE_SIZE: () => MAX_CACHE_SIZE,
      MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL,
      PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN,
      REGION_SET_PARAM: () => REGION_SET_PARAM,
      SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN,
      SHA256_HEADER: () => SHA256_HEADER,
      SIGNATURE_HEADER: () => SIGNATURE_HEADER,
      SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM,
      SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM,
      SignatureV4: () => SignatureV42,
      SignatureV4Base: () => SignatureV4Base,
      TOKEN_HEADER: () => TOKEN_HEADER,
      TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM,
      UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS,
      UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD,
      clearCredentialCache: () => clearCredentialCache,
      createScope: () => createScope,
      getCanonicalHeaders: () => getCanonicalHeaders,
      getCanonicalQuery: () => getCanonicalQuery,
      getPayloadHash: () => getPayloadHash,
      getSigningKey: () => getSigningKey,
      hasHeader: () => hasHeader,
      moveHeadersToQuery: () => moveHeadersToQuery,
      prepareRequest: () => prepareRequest,
      signatureV4aContainer: () => signatureV4aContainer
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_utf85 = require_dist_cjs10();
    var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
    var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
    var AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
    var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
    var EXPIRES_QUERY_PARAM = "X-Amz-Expires";
    var SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
    var TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
    var REGION_SET_PARAM = "X-Amz-Region-Set";
    var AUTH_HEADER = "authorization";
    var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
    var DATE_HEADER = "date";
    var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
    var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
    var SHA256_HEADER = "x-amz-content-sha256";
    var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
    var HOST_HEADER = "host";
    var ALWAYS_UNSIGNABLE_HEADERS = {
      authorization: true,
      "cache-control": true,
      connection: true,
      expect: true,
      from: true,
      "keep-alive": true,
      "max-forwards": true,
      pragma: true,
      referer: true,
      te: true,
      trailer: true,
      "transfer-encoding": true,
      upgrade: true,
      "user-agent": true,
      "x-amzn-trace-id": true
    };
    var PROXY_HEADER_PATTERN = /^proxy-/;
    var SEC_HEADER_PATTERN = /^sec-/;
    var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];
    var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
    var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256";
    var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
    var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
    var MAX_CACHE_SIZE = 50;
    var KEY_TYPE_IDENTIFIER = "aws4_request";
    var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
    var import_util_hex_encoding = require_dist_cjs16();
    var import_util_utf86 = require_dist_cjs10();
    var signingKeyCache = {};
    var cacheQueue = [];
    var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope");
    var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials2, shortDate, region, service) => {
      const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId);
      const cacheKey2 = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials2.sessionToken}`;
      if (cacheKey2 in signingKeyCache) {
        return signingKeyCache[cacheKey2];
      }
      cacheQueue.push(cacheKey2);
      while (cacheQueue.length > MAX_CACHE_SIZE) {
        delete signingKeyCache[cacheQueue.shift()];
      }
      let key = `AWS4${credentials2.secretAccessKey}`;
      for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
        key = await hmac(sha256Constructor, key, signable);
      }
      return signingKeyCache[cacheKey2] = key;
    }, "getSigningKey");
    var clearCredentialCache = /* @__PURE__ */ __name(() => {
      cacheQueue.length = 0;
      Object.keys(signingKeyCache).forEach((cacheKey2) => {
        delete signingKeyCache[cacheKey2];
      });
    }, "clearCredentialCache");
    var hmac = /* @__PURE__ */ __name((ctor, secret, data) => {
      const hash = new ctor(secret);
      hash.update((0, import_util_utf86.toUint8Array)(data));
      return hash.digest();
    }, "hmac");
    var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => {
      const canonical = {};
      for (const headerName of Object.keys(headers).sort()) {
        if (headers[headerName] == void 0) {
          continue;
        }
        const canonicalHeaderName = headerName.toLowerCase();
        if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders == null ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
          if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
            continue;
          }
        }
        canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
      }
      return canonical;
    }, "getCanonicalHeaders");
    var import_is_array_buffer = require_dist_cjs8();
    var import_util_utf822 = require_dist_cjs10();
    var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => {
      for (const headerName of Object.keys(headers)) {
        if (headerName.toLowerCase() === SHA256_HEADER) {
          return headers[headerName];
        }
      }
      if (body == void 0) {
        return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
      } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) {
        const hashCtor = new hashConstructor();
        hashCtor.update((0, import_util_utf822.toUint8Array)(body));
        return (0, import_util_hex_encoding.toHex)(await hashCtor.digest());
      }
      return UNSIGNED_PAYLOAD;
    }, "getPayloadHash");
    var import_util_utf832 = require_dist_cjs10();
    var _a2;
    var HeaderFormatter = (_a2 = class {
      format(headers) {
        const chunks = [];
        for (const headerName of Object.keys(headers)) {
          const bytes = (0, import_util_utf832.fromUtf8)(headerName);
          chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
        }
        const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
        let position = 0;
        for (const chunk of chunks) {
          out.set(chunk, position);
          position += chunk.byteLength;
        }
        return out;
      }
      formatHeaderValue(header) {
        switch (header.type) {
          case "boolean":
            return Uint8Array.from([
              header.value ? 0 : 1
              /* boolFalse */
            ]);
          case "byte":
            return Uint8Array.from([2, header.value]);
          case "short":
            const shortView = new DataView(new ArrayBuffer(3));
            shortView.setUint8(
              0,
              3
              /* short */
            );
            shortView.setInt16(1, header.value, false);
            return new Uint8Array(shortView.buffer);
          case "integer":
            const intView = new DataView(new ArrayBuffer(5));
            intView.setUint8(
              0,
              4
              /* integer */
            );
            intView.setInt32(1, header.value, false);
            return new Uint8Array(intView.buffer);
          case "long":
            const longBytes = new Uint8Array(9);
            longBytes[0] = 5;
            longBytes.set(header.value.bytes, 1);
            return longBytes;
          case "binary":
            const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
            binView.setUint8(
              0,
              6
              /* byteArray */
            );
            binView.setUint16(1, header.value.byteLength, false);
            const binBytes = new Uint8Array(binView.buffer);
            binBytes.set(header.value, 3);
            return binBytes;
          case "string":
            const utf8Bytes = (0, import_util_utf832.fromUtf8)(header.value);
            const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
            strView.setUint8(
              0,
              7
              /* string */
            );
            strView.setUint16(1, utf8Bytes.byteLength, false);
            const strBytes = new Uint8Array(strView.buffer);
            strBytes.set(utf8Bytes, 3);
            return strBytes;
          case "timestamp":
            const tsBytes = new Uint8Array(9);
            tsBytes[0] = 8;
            tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
            return tsBytes;
          case "uuid":
            if (!UUID_PATTERN.test(header.value)) {
              throw new Error(`Invalid UUID received: ${header.value}`);
            }
            const uuidBytes = new Uint8Array(17);
            uuidBytes[0] = 9;
            uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1);
            return uuidBytes;
        }
      }
    }, __name(_a2, "HeaderFormatter"), _a2);
    var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
    var _a3;
    var Int64 = (_a3 = class {
      constructor(bytes) {
        this.bytes = bytes;
        if (bytes.byteLength !== 8) {
          throw new Error("Int64 buffers must be exactly 8 bytes");
        }
      }
      static fromNumber(number2) {
        if (number2 > 9223372036854776e3 || number2 < -9223372036854776e3) {
          throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`);
        }
        const bytes = new Uint8Array(8);
        for (let i4 = 7, remaining = Math.abs(Math.round(number2)); i4 > -1 && remaining > 0; i4--, remaining /= 256) {
          bytes[i4] = remaining;
        }
        if (number2 < 0) {
          negate(bytes);
        }
        return new _a3(bytes);
      }
      /**
       * Called implicitly by infix arithmetic operators.
       */
      valueOf() {
        const bytes = this.bytes.slice(0);
        const negative = bytes[0] & 128;
        if (negative) {
          negate(bytes);
        }
        return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1);
      }
      toString() {
        return String(this.valueOf());
      }
    }, __name(_a3, "Int64"), _a3);
    function negate(bytes) {
      for (let i4 = 0; i4 < 8; i4++) {
        bytes[i4] ^= 255;
      }
      for (let i4 = 7; i4 > -1; i4--) {
        bytes[i4]++;
        if (bytes[i4] !== 0)
          break;
      }
    }
    __name(negate, "negate");
    var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return true;
        }
      }
      return false;
    }, "hasHeader");
    var import_protocol_http15 = require_dist_cjs2();
    var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => {
      var _a6, _b;
      const { headers, query = {} } = import_protocol_http15.HttpRequest.clone(request);
      for (const name of Object.keys(headers)) {
        const lname = name.toLowerCase();
        if (lname.slice(0, 6) === "x-amz-" && !((_a6 = options.unhoistableHeaders) == null ? void 0 : _a6.has(lname)) || ((_b = options.hoistableHeaders) == null ? void 0 : _b.has(lname))) {
          query[name] = headers[name];
          delete headers[name];
        }
      }
      return {
        ...request,
        headers,
        query
      };
    }, "moveHeadersToQuery");
    var prepareRequest = /* @__PURE__ */ __name((request) => {
      request = import_protocol_http15.HttpRequest.clone(request);
      for (const headerName of Object.keys(request.headers)) {
        if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
          delete request.headers[headerName];
        }
      }
      return request;
    }, "prepareRequest");
    var import_util_middleware7 = require_dist_cjs6();
    var import_util_utf842 = require_dist_cjs10();
    var import_util_uri_escape = require_dist_cjs12();
    var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => {
      const keys = [];
      const serialized = {};
      for (const key of Object.keys(query)) {
        if (key.toLowerCase() === SIGNATURE_HEADER) {
          continue;
        }
        const encodedKey = (0, import_util_uri_escape.escapeUri)(key);
        keys.push(encodedKey);
        const value = query[key];
        if (typeof value === "string") {
          serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`;
        } else if (Array.isArray(value)) {
          serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&");
        }
      }
      return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
    }, "getCanonicalQuery");
    var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601");
    var toDate = /* @__PURE__ */ __name((time) => {
      if (typeof time === "number") {
        return new Date(time * 1e3);
      }
      if (typeof time === "string") {
        if (Number(time)) {
          return new Date(Number(time) * 1e3);
        }
        return new Date(time);
      }
      return time;
    }, "toDate");
    var _a4;
    var SignatureV4Base = (_a4 = class {
      constructor({
        applyChecksum,
        credentials: credentials2,
        region,
        service,
        sha256: sha2562,
        uriEscapePath = true
      }) {
        this.service = service;
        this.sha256 = sha2562;
        this.uriEscapePath = uriEscapePath;
        this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
        this.regionProvider = (0, import_util_middleware7.normalizeProvider)(region);
        this.credentialProvider = (0, import_util_middleware7.normalizeProvider)(credentials2);
      }
      createCanonicalRequest(request, canonicalHeaders, payloadHash) {
        const sortedHeaders = Object.keys(canonicalHeaders).sort();
        return `${request.method}
${this.getCanonicalPath(request)}
${getCanonicalQuery(request)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
      }
      async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
        const hash = new this.sha256();
        hash.update((0, import_util_utf842.toUint8Array)(canonicalRequest));
        const hashedRequest = await hash.digest();
        return `${algorithmIdentifier}
${longDate}
${credentialScope}
${(0, import_util_hex_encoding.toHex)(hashedRequest)}`;
      }
      getCanonicalPath({ path: path4 }) {
        if (this.uriEscapePath) {
          const normalizedPathSegments = [];
          for (const pathSegment of path4.split("/")) {
            if ((pathSegment == null ? void 0 : pathSegment.length) === 0)
              continue;
            if (pathSegment === ".")
              continue;
            if (pathSegment === "..") {
              normalizedPathSegments.pop();
            } else {
              normalizedPathSegments.push(pathSegment);
            }
          }
          const normalizedPath = `${(path4 == null ? void 0 : path4.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path4 == null ? void 0 : path4.endsWith("/")) ? "/" : ""}`;
          const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath);
          return doubleEncoded.replace(/%2F/g, "/");
        }
        return path4;
      }
      validateResolvedCredentials(credentials2) {
        if (typeof credentials2 !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339)
        typeof credentials2.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339)
        typeof credentials2.secretAccessKey !== "string") {
          throw new Error("Resolved credential object is not valid");
        }
      }
      formatDate(now) {
        const longDate = iso8601(now).replace(/[\-:]/g, "");
        return {
          longDate,
          shortDate: longDate.slice(0, 8)
        };
      }
      getCanonicalHeaderList(headers) {
        return Object.keys(headers).sort().join(";");
      }
    }, __name(_a4, "SignatureV4Base"), _a4);
    var _a5;
    var SignatureV42 = (_a5 = class extends SignatureV4Base {
      constructor({
        applyChecksum,
        credentials: credentials2,
        region,
        service,
        sha256: sha2562,
        uriEscapePath = true
      }) {
        super({
          applyChecksum,
          credentials: credentials2,
          region,
          service,
          sha256: sha2562,
          uriEscapePath
        });
        this.headerFormatter = new HeaderFormatter();
      }
      async presign(originalRequest, options = {}) {
        const {
          signingDate = /* @__PURE__ */ new Date(),
          expiresIn = 3600,
          unsignableHeaders,
          unhoistableHeaders,
          signableHeaders,
          hoistableHeaders,
          signingRegion,
          signingService
        } = options;
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const { longDate, shortDate } = this.formatDate(signingDate);
        if (expiresIn > MAX_PRESIGNED_TTL) {
          return Promise.reject(
            "Signature version 4 presigned URLs must have an expiration date less than one week in the future"
          );
        }
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
        if (credentials2.sessionToken) {
          request.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken;
        }
        request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
        request.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`;
        request.query[AMZ_DATE_QUERY_PARAM] = longDate;
        request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
        request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(
          longDate,
          scope,
          this.getSigningKey(credentials2, region, shortDate, signingService),
          this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))
        );
        return request;
      }
      async sign(toSign, options) {
        if (typeof toSign === "string") {
          return this.signString(toSign, options);
        } else if (toSign.headers && toSign.payload) {
          return this.signEvent(toSign, options);
        } else if (toSign.message) {
          return this.signMessage(toSign, options);
        } else {
          return this.signRequest(toSign, options);
        }
      }
      async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate, longDate } = this.formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
        const hash = new this.sha256();
        hash.update(headers);
        const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest());
        const stringToSign = [
          EVENT_ALGORITHM_IDENTIFIER,
          longDate,
          scope,
          priorSignature,
          hashedHeaders,
          hashedPayload
        ].join("\n");
        return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
      }
      async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
        const promise = this.signEvent(
          {
            headers: this.headerFormatter.format(signableMessage.message.headers),
            payload: signableMessage.message.body
          },
          {
            signingDate,
            signingRegion,
            signingService,
            priorSignature: signableMessage.priorSignature
          }
        );
        return promise.then((signature) => {
          return { message: signableMessage.message, signature };
        });
      }
      async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate } = this.formatDate(signingDate);
        const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService));
        hash.update((0, import_util_utf85.toUint8Array)(stringToSign));
        return (0, import_util_hex_encoding.toHex)(await hash.digest());
      }
      async signRequest(requestToSign, {
        signingDate = /* @__PURE__ */ new Date(),
        signableHeaders,
        unsignableHeaders,
        signingRegion,
        signingService
      } = {}) {
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const request = prepareRequest(requestToSign);
        const { longDate, shortDate } = this.formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        request.headers[AMZ_DATE_HEADER] = longDate;
        if (credentials2.sessionToken) {
          request.headers[TOKEN_HEADER] = credentials2.sessionToken;
        }
        const payloadHash = await getPayloadHash(request, this.sha256);
        if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {
          request.headers[SHA256_HEADER] = payloadHash;
        }
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        const signature = await this.getSignature(
          longDate,
          scope,
          this.getSigningKey(credentials2, region, shortDate, signingService),
          this.createCanonicalRequest(request, canonicalHeaders, payloadHash)
        );
        request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
        return request;
      }
      async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
        const stringToSign = await this.createStringToSign(
          longDate,
          credentialScope,
          canonicalRequest,
          ALGORITHM_IDENTIFIER
        );
        const hash = new this.sha256(await keyPromise);
        hash.update((0, import_util_utf85.toUint8Array)(stringToSign));
        return (0, import_util_hex_encoding.toHex)(await hash.digest());
      }
      getSigningKey(credentials2, region, shortDate, service) {
        return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service);
      }
    }, __name(_a5, "SignatureV4"), _a5);
    var signatureV4aContainer = {
      SignatureV4a: null
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
function normalizeCredentialProvider(config, { credentials: credentials2, credentialDefaultProvider }) {
  let credentialsProvider;
  if (credentials2) {
    if (!(credentials2 == null ? void 0 : credentials2.memoized)) {
      credentialsProvider = memoizeIdentityProvider(credentials2, isIdentityExpired, doesIdentityRequireRefresh);
    } else {
      credentialsProvider = credentials2;
    }
  } else {
    if (credentialDefaultProvider) {
      credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config, {
        parentClientConfig: config
      })));
    } else {
      credentialsProvider = async () => {
        throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
      };
    }
  }
  credentialsProvider.memoized = true;
  return credentialsProvider;
}
function bindCallerConfig(config, credentialsProvider) {
  if (credentialsProvider.configBound) {
    return credentialsProvider;
  }
  const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });
  fn.memoized = credentialsProvider.memoized;
  fn.configBound = true;
  return fn;
}
var import_signature_v4, resolveAwsSdkSigV4Config, resolveAWSSDKSigV4Config;
var init_resolveAwsSdkSigV4Config = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
    init_client();
    init_dist_es();
    import_signature_v4 = __toESM(require_dist_cjs21());
    resolveAwsSdkSigV4Config = (config) => {
      let inputCredentials = config.credentials;
      let isUserSupplied = !!config.credentials;
      let resolvedCredentials = void 0;
      Object.defineProperty(config, "credentials", {
        set(credentials2) {
          if (credentials2 && credentials2 !== inputCredentials && credentials2 !== resolvedCredentials) {
            isUserSupplied = true;
          }
          inputCredentials = credentials2;
          const memoizedProvider = normalizeCredentialProvider(config, {
            credentials: inputCredentials,
            credentialDefaultProvider: config.credentialDefaultProvider
          });
          const boundProvider = bindCallerConfig(config, memoizedProvider);
          if (isUserSupplied && !boundProvider.attributed) {
            resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
            resolvedCredentials.memoized = boundProvider.memoized;
            resolvedCredentials.configBound = boundProvider.configBound;
            resolvedCredentials.attributed = true;
          } else {
            resolvedCredentials = boundProvider;
          }
        },
        get() {
          return resolvedCredentials;
        },
        enumerable: true,
        configurable: true
      });
      config.credentials = inputCredentials;
      const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256: sha2562 } = config;
      let signer;
      if (config.signer) {
        signer = normalizeProvider(config.signer);
      } else if (config.regionInfoProvider) {
        signer = () => normalizeProvider(config.region)().then(async (region) => [
          await config.regionInfoProvider(region, {
            useFipsEndpoint: await config.useFipsEndpoint(),
            useDualstackEndpoint: await config.useDualstackEndpoint()
          }) || {},
          region
        ]).then(([regionInfo, region]) => {
          const { signingRegion, signingService } = regionInfo;
          config.signingRegion = config.signingRegion || signingRegion || region;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: config.credentials,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
          return new SignerCtor(params);
        });
      } else {
        signer = async (authScheme) => {
          authScheme = Object.assign({}, {
            name: "sigv4",
            signingName: config.signingName || config.defaultSigningName,
            signingRegion: await normalizeProvider(config.region)(),
            properties: {}
          }, authScheme);
          const signingRegion = authScheme.signingRegion;
          const signingService = authScheme.signingName;
          config.signingRegion = config.signingRegion || signingRegion;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: config.credentials,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
          return new SignerCtor(params);
        };
      }
      const resolvedConfig = Object.assign(config, {
        systemClockOffset,
        signingEscapePath,
        signer
      });
      return resolvedConfig;
    };
    resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
var init_aws_sdk = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
    init_AwsSdkSigV4Signer();
    init_AwsSdkSigV4ASigner();
    init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS();
    init_resolveAwsSdkSigV4AConfig();
    init_resolveAwsSdkSigV4Config();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
var init_httpAuthSchemes2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
    init_aws_sdk();
    init_getBearerTokenEnvKey();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
var _toStr, _toBool, _toNum;
var init_coercing_serializers = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
    _toStr = (val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "number" || typeof val2 === "bigint") {
        const warning3 = new Error(`Received number ${val2} where a string was expected.`);
        warning3.name = "Warning";
        console.warn(warning3);
        return String(val2);
      }
      if (typeof val2 === "boolean") {
        const warning3 = new Error(`Received boolean ${val2} where a string was expected.`);
        warning3.name = "Warning";
        console.warn(warning3);
        return String(val2);
      }
      return val2;
    };
    _toBool = (val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "number") {
      }
      if (typeof val2 === "string") {
        const lowercase = val2.toLowerCase();
        if (val2 !== "" && lowercase !== "false" && lowercase !== "true") {
          const warning3 = new Error(`Received string "${val2}" where a boolean was expected.`);
          warning3.name = "Warning";
          console.warn(warning3);
        }
        return val2 !== "" && lowercase !== "false";
      }
      return val2;
    };
    _toNum = (val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "boolean") {
      }
      if (typeof val2 === "string") {
        const num = Number(val2);
        if (num.toString() !== val2) {
          const warning3 = new Error(`Received string "${val2}" where a number was expected.`);
          warning3.name = "Warning";
          console.warn(warning3);
          return val2;
        }
        return num;
      }
      return val2;
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-cjs/index.js
var require_dist_cjs22 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      constructStack: () => constructStack
    });
    module2.exports = __toCommonJS2(src_exports);
    var getAllAliases = /* @__PURE__ */ __name((name, aliases) => {
      const _aliases = [];
      if (name) {
        _aliases.push(name);
      }
      if (aliases) {
        for (const alias of aliases) {
          _aliases.push(alias);
        }
      }
      return _aliases;
    }, "getAllAliases");
    var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => {
      return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
    }, "getMiddlewareNameWithAliases");
    var constructStack = /* @__PURE__ */ __name(() => {
      let absoluteEntries = [];
      let relativeEntries = [];
      let identifyOnResolve = false;
      const entriesNameSet = /* @__PURE__ */ new Set();
      const sort = /* @__PURE__ */ __name((entries) => entries.sort(
        (a3, b3) => stepWeights[b3.step] - stepWeights[a3.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a3.priority || "normal"]
      ), "sort");
      const removeByName = /* @__PURE__ */ __name((toRemove) => {
        let isRemoved = false;
        const filterCb = /* @__PURE__ */ __name((entry) => {
          const aliases = getAllAliases(entry.name, entry.aliases);
          if (aliases.includes(toRemove)) {
            isRemoved = true;
            for (const alias of aliases) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        }, "filterCb");
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      }, "removeByName");
      const removeByReference = /* @__PURE__ */ __name((toRemove) => {
        let isRemoved = false;
        const filterCb = /* @__PURE__ */ __name((entry) => {
          if (entry.middleware === toRemove) {
            isRemoved = true;
            for (const alias of getAllAliases(entry.name, entry.aliases)) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        }, "filterCb");
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      }, "removeByReference");
      const cloneTo = /* @__PURE__ */ __name((toStack) => {
        var _a2;
        absoluteEntries.forEach((entry) => {
          toStack.add(entry.middleware, { ...entry });
        });
        relativeEntries.forEach((entry) => {
          toStack.addRelativeTo(entry.middleware, { ...entry });
        });
        (_a2 = toStack.identifyOnResolve) == null ? void 0 : _a2.call(toStack, stack.identifyOnResolve());
        return toStack;
      }, "cloneTo");
      const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => {
        const expandedMiddlewareList = [];
        from.before.forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        expandedMiddlewareList.push(from);
        from.after.reverse().forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        return expandedMiddlewareList;
      }, "expandRelativeMiddlewareList");
      const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => {
        const normalizedAbsoluteEntries = [];
        const normalizedRelativeEntries = [];
        const normalizedEntriesNameMap = {};
        absoluteEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedAbsoluteEntries.push(normalizedEntry);
        });
        relativeEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedRelativeEntries.push(normalizedEntry);
        });
        normalizedRelativeEntries.forEach((entry) => {
          if (entry.toMiddleware) {
            const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
            if (toMiddleware === void 0) {
              if (debug) {
                return;
              }
              throw new Error(
                `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`
              );
            }
            if (entry.relation === "after") {
              toMiddleware.after.push(entry);
            }
            if (entry.relation === "before") {
              toMiddleware.before.push(entry);
            }
          }
        });
        const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce(
          (wholeList, expandedMiddlewareList) => {
            wholeList.push(...expandedMiddlewareList);
            return wholeList;
          },
          []
        );
        return mainChain;
      }, "getMiddlewareList");
      const stack = {
        add: (middleware, options = {}) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            step: "initialize",
            priority: "normal",
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = absoluteEntries.findIndex(
                  (entry2) => {
                    var _a2;
                    return entry2.name === alias || ((_a2 = entry2.aliases) == null ? void 0 : _a2.some((a3) => a3 === alias));
                  }
                );
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = absoluteEntries[toOverrideIndex];
                if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
                  throw new Error(
                    `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`
                  );
                }
                absoluteEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          absoluteEntries.push(entry);
        },
        addRelativeTo: (middleware, options) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = relativeEntries.findIndex(
                  (entry2) => {
                    var _a2;
                    return entry2.name === alias || ((_a2 = entry2.aliases) == null ? void 0 : _a2.some((a3) => a3 === alias));
                  }
                );
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = relativeEntries[toOverrideIndex];
                if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
                  throw new Error(
                    `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`
                  );
                }
                relativeEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          relativeEntries.push(entry);
        },
        clone: () => cloneTo(constructStack()),
        use: (plugin) => {
          plugin.applyToStack(stack);
        },
        remove: (toRemove) => {
          if (typeof toRemove === "string")
            return removeByName(toRemove);
          else
            return removeByReference(toRemove);
        },
        removeByTag: (toRemove) => {
          let isRemoved = false;
          const filterCb = /* @__PURE__ */ __name((entry) => {
            const { tags, name, aliases: _aliases } = entry;
            if (tags && tags.includes(toRemove)) {
              const aliases = getAllAliases(name, _aliases);
              for (const alias of aliases) {
                entriesNameSet.delete(alias);
              }
              isRemoved = true;
              return false;
            }
            return true;
          }, "filterCb");
          absoluteEntries = absoluteEntries.filter(filterCb);
          relativeEntries = relativeEntries.filter(filterCb);
          return isRemoved;
        },
        concat: (from) => {
          var _a2;
          const cloned = cloneTo(constructStack());
          cloned.use(from);
          cloned.identifyOnResolve(
            identifyOnResolve || cloned.identifyOnResolve() || (((_a2 = from.identifyOnResolve) == null ? void 0 : _a2.call(from)) ?? false)
          );
          return cloned;
        },
        applyToStack: cloneTo,
        identify: () => {
          return getMiddlewareList(true).map((mw) => {
            const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
            return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
          });
        },
        identifyOnResolve(toggle) {
          if (typeof toggle === "boolean")
            identifyOnResolve = toggle;
          return identifyOnResolve;
        },
        resolve: (handler, context) => {
          for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
            handler = middleware(handler, context);
          }
          if (identifyOnResolve) {
            console.log(stack.identify());
          }
          return handler;
        }
      };
      return stack;
    }, "constructStack");
    var stepWeights = {
      initialize: 5,
      serialize: 4,
      build: 3,
      finalizeRequest: 2,
      deserialize: 1
    };
    var priorityWeights = {
      high: 3,
      normal: 2,
      low: 1
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-cjs/index.js
var require_dist_cjs23 = __commonJS({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Client: () => Client,
      Command: () => Command,
      NoOpLogger: () => NoOpLogger3,
      SENSITIVE_STRING: () => SENSITIVE_STRING3,
      ServiceException: () => ServiceException,
      _json: () => _json2,
      collectBody: () => import_protocols2.collectBody,
      convertMap: () => convertMap,
      createAggregatedClient: () => createAggregatedClient3,
      decorateServiceException: () => decorateServiceException,
      emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion4,
      extendedEncodeURIComponent: () => import_protocols2.extendedEncodeURIComponent,
      getArrayIfSingleItem: () => getArrayIfSingleItem,
      getDefaultClientConfiguration: () => getDefaultClientConfiguration,
      getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration3,
      getValueFromTextNode: () => getValueFromTextNode2,
      isSerializableHeaderValue: () => isSerializableHeaderValue,
      loadConfigsForDefaultMode: () => loadConfigsForDefaultMode3,
      map: () => map2,
      resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3,
      resolvedPath: () => import_protocols2.resolvedPath,
      serializeDateTime: () => serializeDateTime,
      serializeFloat: () => serializeFloat,
      take: () => take2,
      throwDefaultError: () => throwDefaultError3,
      withBaseException: () => withBaseException3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_middleware_stack = require_dist_cjs22();
    var _a2;
    var Client = (_a2 = class {
      constructor(config) {
        this.config = config;
        this.middlewareStack = (0, import_middleware_stack.constructStack)();
      }
      send(command, optionsOrCb, cb) {
        const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
        const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
        const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
        let handler;
        if (useHandlerCache) {
          if (!this.handlers) {
            this.handlers = /* @__PURE__ */ new WeakMap();
          }
          const handlers = this.handlers;
          if (handlers.has(command.constructor)) {
            handler = handlers.get(command.constructor);
          } else {
            handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
            handlers.set(command.constructor, handler);
          }
        } else {
          delete this.handlers;
          handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
        }
        if (callback) {
          handler(command).then(
            (result) => callback(null, result.output),
            (err2) => callback(err2)
          ).catch(
            // prevent any errors thrown in the callback from triggering an
            // unhandled promise rejection
            () => {
            }
          );
        } else {
          return handler(command).then((result) => result.output);
        }
      }
      destroy() {
        var _a7, _b, _c;
        (_c = (_b = (_a7 = this.config) == null ? void 0 : _a7.requestHandler) == null ? void 0 : _b.destroy) == null ? void 0 : _c.call(_b);
        delete this.handlers;
      }
    }, __name(_a2, "Client"), _a2);
    var import_protocols2 = (init_protocols(), __toCommonJS(protocols_exports));
    var import_types5 = require_dist_cjs();
    var _a3;
    var Command = (_a3 = class {
      constructor() {
        this.middlewareStack = (0, import_middleware_stack.constructStack)();
      }
      /**
       * Factory for Command ClassBuilder.
       * @internal
       */
      static classBuilder() {
        return new ClassBuilder();
      }
      /**
       * @internal
       */
      resolveMiddlewareWithContext(clientStack, configuration, options, {
        middlewareFn,
        clientName,
        commandName,
        inputFilterSensitiveLog,
        outputFilterSensitiveLog,
        smithyContext,
        additionalContext,
        CommandCtor
      }) {
        for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
          this.middlewareStack.use(mw);
        }
        const stack = clientStack.concat(this.middlewareStack);
        const { logger: logger3 } = configuration;
        const handlerExecutionContext = {
          logger: logger3,
          clientName,
          commandName,
          inputFilterSensitiveLog,
          outputFilterSensitiveLog,
          [import_types5.SMITHY_CONTEXT_KEY]: {
            commandInstance: this,
            ...smithyContext
          },
          ...additionalContext
        };
        const { requestHandler } = configuration;
        return stack.resolve(
          (request) => requestHandler.handle(request.request, options || {}),
          handlerExecutionContext
        );
      }
    }, __name(_a3, "Command"), _a3);
    var _a4;
    var ClassBuilder = (_a4 = class {
      constructor() {
        this._init = () => {
        };
        this._ep = {};
        this._middlewareFn = () => [];
        this._commandName = "";
        this._clientName = "";
        this._additionalContext = {};
        this._smithyContext = {};
        this._inputFilterSensitiveLog = (_3) => _3;
        this._outputFilterSensitiveLog = (_3) => _3;
        this._serializer = null;
        this._deserializer = null;
      }
      /**
       * Optional init callback.
       */
      init(cb) {
        this._init = cb;
      }
      /**
       * Set the endpoint parameter instructions.
       */
      ep(endpointParameterInstructions) {
        this._ep = endpointParameterInstructions;
        return this;
      }
      /**
       * Add any number of middleware.
       */
      m(middlewareSupplier) {
        this._middlewareFn = middlewareSupplier;
        return this;
      }
      /**
       * Set the initial handler execution context Smithy field.
       */
      s(service, operation, smithyContext = {}) {
        this._smithyContext = {
          service,
          operation,
          ...smithyContext
        };
        return this;
      }
      /**
       * Set the initial handler execution context.
       */
      c(additionalContext = {}) {
        this._additionalContext = additionalContext;
        return this;
      }
      /**
       * Set constant string identifiers for the operation.
       */
      n(clientName, commandName) {
        this._clientName = clientName;
        this._commandName = commandName;
        return this;
      }
      /**
       * Set the input and output sensistive log filters.
       */
      f(inputFilter = (_3) => _3, outputFilter = (_3) => _3) {
        this._inputFilterSensitiveLog = inputFilter;
        this._outputFilterSensitiveLog = outputFilter;
        return this;
      }
      /**
       * Sets the serializer.
       */
      ser(serializer) {
        this._serializer = serializer;
        return this;
      }
      /**
       * Sets the deserializer.
       */
      de(deserializer) {
        this._deserializer = deserializer;
        return this;
      }
      /**
       * Sets input/output schema for the operation.
       */
      sc(operation) {
        this._operationSchema = operation;
        this._smithyContext.operationSchema = operation;
        return this;
      }
      /**
       * @returns a Command class with the classBuilder properties.
       */
      build() {
        var _a7;
        const closure = this;
        let CommandRef;
        return CommandRef = (_a7 = class extends Command {
          /**
           * @public
           */
          constructor(...[input]) {
            super();
            this.serialize = closure._serializer;
            this.deserialize = closure._deserializer;
            this.input = input ?? {};
            closure._init(this);
            this.schema = closure._operationSchema;
          }
          /**
           * @public
           */
          static getEndpointParameterInstructions() {
            return closure._ep;
          }
          /**
           * @internal
           */
          resolveMiddleware(stack, configuration, options) {
            return this.resolveMiddlewareWithContext(stack, configuration, options, {
              CommandCtor: CommandRef,
              middlewareFn: closure._middlewareFn,
              clientName: closure._clientName,
              commandName: closure._commandName,
              inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
              outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
              smithyContext: closure._smithyContext,
              additionalContext: closure._additionalContext
            });
          }
        }, __name(_a7, "CommandRef"), _a7);
      }
    }, __name(_a4, "ClassBuilder"), _a4);
    var SENSITIVE_STRING3 = "***SensitiveInformation***";
    var createAggregatedClient3 = /* @__PURE__ */ __name((commands3, Client2) => {
      for (const command of Object.keys(commands3)) {
        const CommandCtor = commands3[command];
        const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) {
          const command22 = new CommandCtor(args);
          if (typeof optionsOrCb === "function") {
            this.send(command22, optionsOrCb);
          } else if (typeof cb === "function") {
            if (typeof optionsOrCb !== "object")
              throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
            this.send(command22, optionsOrCb || {}, cb);
          } else {
            return this.send(command22, optionsOrCb);
          }
        }, "methodImpl");
        const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
        Client2.prototype[methodName] = methodImpl;
      }
    }, "createAggregatedClient");
    var _a5;
    var ServiceException = (_a5 = class extends Error {
      constructor(options) {
        super(options.message);
        Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
        this.name = options.name;
        this.$fault = options.$fault;
        this.$metadata = options.$metadata;
      }
      /**
       * Checks if a value is an instance of ServiceException (duck typed)
       */
      static isInstance(value) {
        if (!value)
          return false;
        const candidate = value;
        return _a5.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
      }
      /**
       * Custom instanceof check to support the operator for ServiceException base class
       */
      static [Symbol.hasInstance](instance) {
        if (!instance)
          return false;
        const candidate = instance;
        if (this === _a5) {
          return _a5.isInstance(instance);
        }
        if (_a5.isInstance(instance)) {
          if (candidate.name && this.name) {
            return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
          }
          return this.prototype.isPrototypeOf(instance);
        }
        return false;
      }
    }, __name(_a5, "ServiceException"), _a5);
    var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => {
      Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k3, v6]) => {
        if (exception[k3] == void 0 || exception[k3] === "") {
          exception[k3] = v6;
        }
      });
      const message = exception.message || exception.Message || "UnknownError";
      exception.message = message;
      delete exception.Message;
      return exception;
    }, "decorateServiceException");
    var throwDefaultError3 = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => {
      const $metadata = deserializeMetadata3(output);
      const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
      const response = new exceptionCtor({
        name: (parsedBody == null ? void 0 : parsedBody.code) || (parsedBody == null ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError",
        $fault: "client",
        $metadata
      });
      throw decorateServiceException(response, parsedBody);
    }, "throwDefaultError");
    var withBaseException3 = /* @__PURE__ */ __name((ExceptionCtor) => {
      return ({ output, parsedBody, errorCode }) => {
        throwDefaultError3({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
      };
    }, "withBaseException");
    var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    }), "deserializeMetadata");
    var loadConfigsForDefaultMode3 = /* @__PURE__ */ __name((mode) => {
      switch (mode) {
        case "standard":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "in-region":
          return {
            retryMode: "standard",
            connectionTimeout: 1100
          };
        case "cross-region":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "mobile":
          return {
            retryMode: "standard",
            connectionTimeout: 3e4
          };
        default:
          return {};
      }
    }, "loadConfigsForDefaultMode");
    var warningEmitted = false;
    var emitWarningIfUnsupportedVersion4 = /* @__PURE__ */ __name((version3) => {
      if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) {
        warningEmitted = true;
      }
    }, "emitWarningIfUnsupportedVersion");
    var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const checksumAlgorithms = [];
      for (const id in import_types5.AlgorithmId) {
        const algorithmId = import_types5.AlgorithmId[id];
        if (runtimeConfig[algorithmId] === void 0) {
          continue;
        }
        checksumAlgorithms.push({
          algorithmId: () => algorithmId,
          checksumConstructor: () => runtimeConfig[algorithmId]
        });
      }
      return {
        addChecksumAlgorithm(algo) {
          checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return checksumAlgorithms;
        }
      };
    }, "getChecksumConfiguration");
    var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    }, "resolveChecksumRuntimeConfig");
    var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      return {
        setRetryStrategy(retryStrategy) {
          runtimeConfig.retryStrategy = retryStrategy;
        },
        retryStrategy() {
          return runtimeConfig.retryStrategy;
        }
      };
    }, "getRetryConfiguration");
    var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => {
      const runtimeConfig = {};
      runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
      return runtimeConfig;
    }, "resolveRetryRuntimeConfig");
    var getDefaultExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
      return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));
    }, "getDefaultExtensionConfiguration");
    var getDefaultClientConfiguration = getDefaultExtensionConfiguration3;
    var resolveDefaultRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
      return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config));
    }, "resolveDefaultRuntimeConfig");
    var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem");
    var getValueFromTextNode2 = /* @__PURE__ */ __name((obj) => {
      const textNodeName = "#text";
      for (const key in obj) {
        if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
          obj[key] = obj[key][textNodeName];
        } else if (typeof obj[key] === "object" && obj[key] !== null) {
          obj[key] = getValueFromTextNode2(obj[key]);
        }
      }
      return obj;
    }, "getValueFromTextNode");
    var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => {
      return value != null;
    }, "isSerializableHeaderValue");
    var _a6;
    var NoOpLogger3 = (_a6 = class {
      trace() {
      }
      debug() {
      }
      info() {
      }
      warn() {
      }
      error() {
      }
    }, __name(_a6, "NoOpLogger"), _a6);
    function map2(arg0, arg1, arg2) {
      let target;
      let filter2;
      let instructions;
      if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
        target = {};
        instructions = arg0;
      } else {
        target = arg0;
        if (typeof arg1 === "function") {
          filter2 = arg1;
          instructions = arg2;
          return mapWithFilter(target, filter2, instructions);
        } else {
          instructions = arg1;
        }
      }
      for (const key of Object.keys(instructions)) {
        if (!Array.isArray(instructions[key])) {
          target[key] = instructions[key];
          continue;
        }
        applyInstruction(target, null, instructions, key);
      }
      return target;
    }
    __name(map2, "map");
    var convertMap = /* @__PURE__ */ __name((target) => {
      const output = {};
      for (const [k3, v6] of Object.entries(target || {})) {
        output[k3] = [, v6];
      }
      return output;
    }, "convertMap");
    var take2 = /* @__PURE__ */ __name((source, instructions) => {
      const out = {};
      for (const key in instructions) {
        applyInstruction(out, source, instructions, key);
      }
      return out;
    }, "take");
    var mapWithFilter = /* @__PURE__ */ __name((target, filter2, instructions) => {
      return map2(
        target,
        Object.entries(instructions).reduce(
          (_instructions, [key, value]) => {
            if (Array.isArray(value)) {
              _instructions[key] = value;
            } else {
              if (typeof value === "function") {
                _instructions[key] = [filter2, value()];
              } else {
                _instructions[key] = [filter2, value];
              }
            }
            return _instructions;
          },
          {}
        )
      );
    }, "mapWithFilter");
    var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => {
      if (source !== null) {
        let instruction = instructions[targetKey];
        if (typeof instruction === "function") {
          instruction = [, instruction];
        }
        const [filter22 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
        if (typeof filter22 === "function" && filter22(source[sourceKey]) || typeof filter22 !== "function" && !!filter22) {
          target[targetKey] = valueFn(source[sourceKey]);
        }
        return;
      }
      let [filter2, value] = instructions[targetKey];
      if (typeof value === "function") {
        let _value;
        const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed) {
          target[targetKey] = _value;
        } else if (customFilterPassed) {
          target[targetKey] = value();
        }
      } else {
        const defaultFilterPassed = filter2 === void 0 && value != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed || customFilterPassed) {
          target[targetKey] = value;
        }
      }
    }, "applyInstruction");
    var nonNullish = /* @__PURE__ */ __name((_3) => _3 != null, "nonNullish");
    var pass = /* @__PURE__ */ __name((_3) => _3, "pass");
    var serializeFloat = /* @__PURE__ */ __name((value) => {
      if (value !== value) {
        return "NaN";
      }
      switch (value) {
        case Infinity:
          return "Infinity";
        case -Infinity:
          return "-Infinity";
        default:
          return value;
      }
    }, "serializeFloat");
    var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime");
    var _json2 = /* @__PURE__ */ __name((obj) => {
      if (obj == null) {
        return {};
      }
      if (Array.isArray(obj)) {
        return obj.filter((_3) => _3 != null).map(_json2);
      }
      if (typeof obj === "object") {
        const target = {};
        for (const key of Object.keys(obj)) {
          if (obj[key] == null) {
            continue;
          }
          target[key] = _json2(obj[key]);
        }
        return target;
      }
      return obj;
    }, "_json");
    __reExport(src_exports, (init_serde(), __toCommonJS(serde_exports)), module2.exports);
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
var import_smithy_client, awsExpectUnion;
var init_awsExpectUnion = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
    import_smithy_client = __toESM(require_dist_cjs23());
    awsExpectUnion = (value) => {
      if (value == null) {
        return void 0;
      }
      if (typeof value === "object" && "__type" in value) {
        delete value.__type;
      }
      return (0, import_smithy_client.expectUnion)(value);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
var import_smithy_client2, collectBodyString;
var init_common2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
    import_smithy_client2 = __toESM(require_dist_cjs23());
    collectBodyString = (streamBody, context) => (0, import_smithy_client2.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body));
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
var init_parseJsonBody = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
    init_common2();
    parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        try {
          return JSON.parse(encoded);
        } catch (e4) {
          if ((e4 == null ? void 0 : e4.name) === "SyntaxError") {
            Object.defineProperty(e4, "$responseBodyText", {
              value: encoded
            });
          }
          throw e4;
        }
      }
      return {};
    });
    parseJsonErrorBody = async (errorBody, context) => {
      const value = await parseJsonBody(errorBody, context);
      value.message = value.message ?? value.Message;
      return value;
    };
    loadRestJsonErrorCode = (output, data) => {
      const findKey = (object, key) => Object.keys(object).find((k3) => k3.toLowerCase() === key.toLowerCase());
      const sanitizeErrorCode = (rawValue) => {
        let cleanValue = rawValue;
        if (typeof cleanValue === "number") {
          cleanValue = cleanValue.toString();
        }
        if (cleanValue.indexOf(",") >= 0) {
          cleanValue = cleanValue.split(",")[0];
        }
        if (cleanValue.indexOf(":") >= 0) {
          cleanValue = cleanValue.split(":")[0];
        }
        if (cleanValue.indexOf("#") >= 0) {
          cleanValue = cleanValue.split("#")[1];
        }
        return cleanValue;
      };
      const headerKey = findKey(output.headers, "x-amzn-errortype");
      if (headerKey !== void 0) {
        return sanitizeErrorCode(output.headers[headerKey]);
      }
      if (data && typeof data === "object") {
        const codeKey = findKey(data, "code");
        if (codeKey && data[codeKey] !== void 0) {
          return sanitizeErrorCode(data[codeKey]);
        }
        if (data["__type"] !== void 0) {
          return sanitizeErrorCode(data["__type"]);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
var require_util2 = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports2) {
    "use strict";
    var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
    var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
    var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
    var regexName = new RegExp("^" + nameRegexp + "$");
    var getAllMatches = function(string2, regex) {
      const matches = [];
      let match2 = regex.exec(string2);
      while (match2) {
        const allmatches = [];
        allmatches.startIndex = regex.lastIndex - match2[0].length;
        const len = match2.length;
        for (let index6 = 0; index6 < len; index6++) {
          allmatches.push(match2[index6]);
        }
        matches.push(allmatches);
        match2 = regex.exec(string2);
      }
      return matches;
    };
    var isName = function(string2) {
      const match2 = regexName.exec(string2);
      return !(match2 === null || typeof match2 === "undefined");
    };
    exports2.isExist = function(v6) {
      return typeof v6 !== "undefined";
    };
    exports2.isEmptyObject = function(obj) {
      return Object.keys(obj).length === 0;
    };
    exports2.merge = function(target, a3, arrayMode) {
      if (a3) {
        const keys = Object.keys(a3);
        const len = keys.length;
        for (let i4 = 0; i4 < len; i4++) {
          if (arrayMode === "strict") {
            target[keys[i4]] = [a3[keys[i4]]];
          } else {
            target[keys[i4]] = a3[keys[i4]];
          }
        }
      }
    };
    exports2.getValue = function(v6) {
      if (exports2.isExist(v6)) {
        return v6;
      } else {
        return "";
      }
    };
    exports2.isName = isName;
    exports2.getAllMatches = getAllMatches;
    exports2.nameRegexp = nameRegexp;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports2) {
    "use strict";
    var util2 = require_util2();
    var defaultOptions = {
      allowBooleanAttributes: false,
      //A tag can have attributes without any value
      unpairedTags: []
    };
    exports2.validate = function(xmlData, options) {
      options = Object.assign({}, defaultOptions, options);
      const tags = [];
      let tagFound = false;
      let reachedRoot = false;
      if (xmlData[0] === "\uFEFF") {
        xmlData = xmlData.substr(1);
      }
      for (let i4 = 0; i4 < xmlData.length; i4++) {
        if (xmlData[i4] === "<" && xmlData[i4 + 1] === "?") {
          i4 += 2;
          i4 = readPI(xmlData, i4);
          if (i4.err) return i4;
        } else if (xmlData[i4] === "<") {
          let tagStartPos = i4;
          i4++;
          if (xmlData[i4] === "!") {
            i4 = readCommentAndCDATA(xmlData, i4);
            continue;
          } else {
            let closingTag = false;
            if (xmlData[i4] === "/") {
              closingTag = true;
              i4++;
            }
            let tagName = "";
            for (; i4 < xmlData.length && xmlData[i4] !== ">" && xmlData[i4] !== " " && xmlData[i4] !== "	" && xmlData[i4] !== "\n" && xmlData[i4] !== "\r"; i4++) {
              tagName += xmlData[i4];
            }
            tagName = tagName.trim();
            if (tagName[tagName.length - 1] === "/") {
              tagName = tagName.substring(0, tagName.length - 1);
              i4--;
            }
            if (!validateTagName(tagName)) {
              let msg;
              if (tagName.trim().length === 0) {
                msg = "Invalid space after '<'.";
              } else {
                msg = "Tag '" + tagName + "' is an invalid name.";
              }
              return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i4));
            }
            const result = readAttributeStr(xmlData, i4);
            if (result === false) {
              return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i4));
            }
            let attrStr = result.value;
            i4 = result.index;
            if (attrStr[attrStr.length - 1] === "/") {
              const attrStrStart = i4 - attrStr.length;
              attrStr = attrStr.substring(0, attrStr.length - 1);
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 === true) {
                tagFound = true;
              } else {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
              }
            } else if (closingTag) {
              if (!result.tagClosed) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i4));
              } else if (attrStr.trim().length > 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
              } else if (tags.length === 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
              } else {
                const otg = tags.pop();
                if (tagName !== otg.tagName) {
                  let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
                  return getErrorObject(
                    "InvalidTag",
                    "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
                    getLineNumberForPosition(xmlData, tagStartPos)
                  );
                }
                if (tags.length == 0) {
                  reachedRoot = true;
                }
              }
            } else {
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 !== true) {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i4 - attrStr.length + isValid2.err.line));
              }
              if (reachedRoot === true) {
                return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i4));
              } else if (options.unpairedTags.indexOf(tagName) !== -1) {
              } else {
                tags.push({ tagName, tagStartPos });
              }
              tagFound = true;
            }
            for (i4++; i4 < xmlData.length; i4++) {
              if (xmlData[i4] === "<") {
                if (xmlData[i4 + 1] === "!") {
                  i4++;
                  i4 = readCommentAndCDATA(xmlData, i4);
                  continue;
                } else if (xmlData[i4 + 1] === "?") {
                  i4 = readPI(xmlData, ++i4);
                  if (i4.err) return i4;
                } else {
                  break;
                }
              } else if (xmlData[i4] === "&") {
                const afterAmp = validateAmpersand(xmlData, i4);
                if (afterAmp == -1)
                  return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i4));
                i4 = afterAmp;
              } else {
                if (reachedRoot === true && !isWhiteSpace(xmlData[i4])) {
                  return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i4));
                }
              }
            }
            if (xmlData[i4] === "<") {
              i4--;
            }
          }
        } else {
          if (isWhiteSpace(xmlData[i4])) {
            continue;
          }
          return getErrorObject("InvalidChar", "char '" + xmlData[i4] + "' is not expected.", getLineNumberForPosition(xmlData, i4));
        }
      }
      if (!tagFound) {
        return getErrorObject("InvalidXml", "Start tag expected.", 1);
      } else if (tags.length == 1) {
        return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
      } else if (tags.length > 0) {
        return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t4) => t4.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
      }
      return true;
    };
    function isWhiteSpace(char) {
      return char === " " || char === "	" || char === "\n" || char === "\r";
    }
    function readPI(xmlData, i4) {
      const start = i4;
      for (; i4 < xmlData.length; i4++) {
        if (xmlData[i4] == "?" || xmlData[i4] == " ") {
          const tagname = xmlData.substr(start, i4 - start);
          if (i4 > 5 && tagname === "xml") {
            return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i4));
          } else if (xmlData[i4] == "?" && xmlData[i4 + 1] == ">") {
            i4++;
            break;
          } else {
            continue;
          }
        }
      }
      return i4;
    }
    function readCommentAndCDATA(xmlData, i4) {
      if (xmlData.length > i4 + 5 && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === "-") {
        for (i4 += 3; i4 < xmlData.length; i4++) {
          if (xmlData[i4] === "-" && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === ">") {
            i4 += 2;
            break;
          }
        }
      } else if (xmlData.length > i4 + 8 && xmlData[i4 + 1] === "D" && xmlData[i4 + 2] === "O" && xmlData[i4 + 3] === "C" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "Y" && xmlData[i4 + 6] === "P" && xmlData[i4 + 7] === "E") {
        let angleBracketsCount = 1;
        for (i4 += 8; i4 < xmlData.length; i4++) {
          if (xmlData[i4] === "<") {
            angleBracketsCount++;
          } else if (xmlData[i4] === ">") {
            angleBracketsCount--;
            if (angleBracketsCount === 0) {
              break;
            }
          }
        }
      } else if (xmlData.length > i4 + 9 && xmlData[i4 + 1] === "[" && xmlData[i4 + 2] === "C" && xmlData[i4 + 3] === "D" && xmlData[i4 + 4] === "A" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "A" && xmlData[i4 + 7] === "[") {
        for (i4 += 8; i4 < xmlData.length; i4++) {
          if (xmlData[i4] === "]" && xmlData[i4 + 1] === "]" && xmlData[i4 + 2] === ">") {
            i4 += 2;
            break;
          }
        }
      }
      return i4;
    }
    var doubleQuote = '"';
    var singleQuote = "'";
    function readAttributeStr(xmlData, i4) {
      let attrStr = "";
      let startChar = "";
      let tagClosed = false;
      for (; i4 < xmlData.length; i4++) {
        if (xmlData[i4] === doubleQuote || xmlData[i4] === singleQuote) {
          if (startChar === "") {
            startChar = xmlData[i4];
          } else if (startChar !== xmlData[i4]) {
          } else {
            startChar = "";
          }
        } else if (xmlData[i4] === ">") {
          if (startChar === "") {
            tagClosed = true;
            break;
          }
        }
        attrStr += xmlData[i4];
      }
      if (startChar !== "") {
        return false;
      }
      return {
        value: attrStr,
        index: i4,
        tagClosed
      };
    }
    var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
    function validateAttributeString(attrStr, options) {
      const matches = util2.getAllMatches(attrStr, validAttrStrRegxp);
      const attrNames = {};
      for (let i4 = 0; i4 < matches.length; i4++) {
        if (matches[i4][1].length === 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' has no space in starting.", getPositionFromMatch(matches[i4]));
        } else if (matches[i4][3] !== void 0 && matches[i4][4] === void 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' is without value.", getPositionFromMatch(matches[i4]));
        } else if (matches[i4][3] === void 0 && !options.allowBooleanAttributes) {
          return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i4][2] + "' is not allowed.", getPositionFromMatch(matches[i4]));
        }
        const attrName = matches[i4][2];
        if (!validateAttrName(attrName)) {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i4]));
        }
        if (!attrNames.hasOwnProperty(attrName)) {
          attrNames[attrName] = 1;
        } else {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i4]));
        }
      }
      return true;
    }
    function validateNumberAmpersand(xmlData, i4) {
      let re = /\d/;
      if (xmlData[i4] === "x") {
        i4++;
        re = /[\da-fA-F]/;
      }
      for (; i4 < xmlData.length; i4++) {
        if (xmlData[i4] === ";")
          return i4;
        if (!xmlData[i4].match(re))
          break;
      }
      return -1;
    }
    function validateAmpersand(xmlData, i4) {
      i4++;
      if (xmlData[i4] === ";")
        return -1;
      if (xmlData[i4] === "#") {
        i4++;
        return validateNumberAmpersand(xmlData, i4);
      }
      let count = 0;
      for (; i4 < xmlData.length; i4++, count++) {
        if (xmlData[i4].match(/\w/) && count < 20)
          continue;
        if (xmlData[i4] === ";")
          break;
        return -1;
      }
      return i4;
    }
    function getErrorObject(code, message, lineNumber) {
      return {
        err: {
          code,
          msg: message,
          line: lineNumber.line || lineNumber,
          col: lineNumber.col
        }
      };
    }
    function validateAttrName(attrName) {
      return util2.isName(attrName);
    }
    function validateTagName(tagname) {
      return util2.isName(tagname);
    }
    function getLineNumberForPosition(xmlData, index6) {
      const lines = xmlData.substring(0, index6).split(/\r?\n/);
      return {
        line: lines.length,
        // column number is last line's length + 1, because column numbering starts at 1:
        col: lines[lines.length - 1].length + 1
      };
    }
    function getPositionFromMatch(match2) {
      return match2.startIndex + match2[1].length;
    }
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) {
    var defaultOptions = {
      preserveOrder: false,
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      removeNSPrefix: false,
      // remove NS from tag name or attribute name if true
      allowBooleanAttributes: false,
      //a tag can have attributes without any value
      //ignoreRootElement : false,
      parseTagValue: true,
      parseAttributeValue: false,
      trimValues: true,
      //Trim string values of tag and attributes
      cdataPropName: false,
      numberParseOptions: {
        hex: true,
        leadingZeros: true,
        eNotation: true
      },
      tagValueProcessor: function(tagName, val2) {
        return val2;
      },
      attributeValueProcessor: function(attrName, val2) {
        return val2;
      },
      stopNodes: [],
      //nested tags will not be parsed even for errors
      alwaysCreateTextNode: false,
      isArray: () => false,
      commentPropName: false,
      unpairedTags: [],
      processEntities: true,
      htmlEntities: false,
      ignoreDeclaration: false,
      ignorePiTags: false,
      transformTagName: false,
      transformAttributeName: false,
      updateTag: function(tagName, jPath, attrs) {
        return tagName;
      }
      // skipEmptyListItem: false
    };
    var buildOptions = function(options) {
      return Object.assign({}, defaultOptions, options);
    };
    exports2.buildOptions = buildOptions;
    exports2.defaultOptions = defaultOptions;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) {
    "use strict";
    var XmlNode = class {
      constructor(tagname) {
        this.tagname = tagname;
        this.child = [];
        this[":@"] = {};
      }
      add(key, val2) {
        if (key === "__proto__") key = "#__proto__";
        this.child.push({ [key]: val2 });
      }
      addChild(node) {
        if (node.tagname === "__proto__") node.tagname = "#__proto__";
        if (node[":@"] && Object.keys(node[":@"]).length > 0) {
          this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
        } else {
          this.child.push({ [node.tagname]: node.child });
        }
      }
    };
    module2.exports = XmlNode;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) {
    var util2 = require_util2();
    function readDocType(xmlData, i4) {
      const entities = {};
      if (xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "C" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "Y" && xmlData[i4 + 7] === "P" && xmlData[i4 + 8] === "E") {
        i4 = i4 + 9;
        let angleBracketsCount = 1;
        let hasBody = false, comment = false;
        let exp = "";
        for (; i4 < xmlData.length; i4++) {
          if (xmlData[i4] === "<" && !comment) {
            if (hasBody && isEntity(xmlData, i4)) {
              i4 += 7;
              [entityName, val, i4] = readEntityExp(xmlData, i4 + 1);
              if (val.indexOf("&") === -1)
                entities[validateEntityName(entityName)] = {
                  regx: RegExp(`&${entityName};`, "g"),
                  val
                };
            } else if (hasBody && isElement(xmlData, i4)) i4 += 8;
            else if (hasBody && isAttlist(xmlData, i4)) i4 += 8;
            else if (hasBody && isNotation(xmlData, i4)) i4 += 9;
            else if (isComment) comment = true;
            else throw new Error("Invalid DOCTYPE");
            angleBracketsCount++;
            exp = "";
          } else if (xmlData[i4] === ">") {
            if (comment) {
              if (xmlData[i4 - 1] === "-" && xmlData[i4 - 2] === "-") {
                comment = false;
                angleBracketsCount--;
              }
            } else {
              angleBracketsCount--;
            }
            if (angleBracketsCount === 0) {
              break;
            }
          } else if (xmlData[i4] === "[") {
            hasBody = true;
          } else {
            exp += xmlData[i4];
          }
        }
        if (angleBracketsCount !== 0) {
          throw new Error(`Unclosed DOCTYPE`);
        }
      } else {
        throw new Error(`Invalid Tag instead of DOCTYPE`);
      }
      return { entities, i: i4 };
    }
    function readEntityExp(xmlData, i4) {
      let entityName2 = "";
      for (; i4 < xmlData.length && (xmlData[i4] !== "'" && xmlData[i4] !== '"'); i4++) {
        entityName2 += xmlData[i4];
      }
      entityName2 = entityName2.trim();
      if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
      const startChar = xmlData[i4++];
      let val2 = "";
      for (; i4 < xmlData.length && xmlData[i4] !== startChar; i4++) {
        val2 += xmlData[i4];
      }
      return [entityName2, val2, i4];
    }
    function isComment(xmlData, i4) {
      if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "-" && xmlData[i4 + 3] === "-") return true;
      return false;
    }
    function isEntity(xmlData, i4) {
      if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "N" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "I" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "Y") return true;
      return false;
    }
    function isElement(xmlData, i4) {
      if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "L" && xmlData[i4 + 4] === "E" && xmlData[i4 + 5] === "M" && xmlData[i4 + 6] === "E" && xmlData[i4 + 7] === "N" && xmlData[i4 + 8] === "T") return true;
      return false;
    }
    function isAttlist(xmlData, i4) {
      if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "A" && xmlData[i4 + 3] === "T" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "L" && xmlData[i4 + 6] === "I" && xmlData[i4 + 7] === "S" && xmlData[i4 + 8] === "T") return true;
      return false;
    }
    function isNotation(xmlData, i4) {
      if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "N" && xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "A" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "I" && xmlData[i4 + 8] === "O" && xmlData[i4 + 9] === "N") return true;
      return false;
    }
    function validateEntityName(name) {
      if (util2.isName(name))
        return name;
      else
        throw new Error(`Invalid entity name ${name}`);
    }
    module2.exports = readDocType;
  }
});

// ../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js
var require_strnum = __commonJS({
  "../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js"(exports2, module2) {
    var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
    var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
    var consider = {
      hex: true,
      // oct: false,
      leadingZeros: true,
      decimalPoint: ".",
      eNotation: true
      //skipLike: /regex/
    };
    function toNumber(str, options = {}) {
      options = Object.assign({}, consider, options);
      if (!str || typeof str !== "string") return str;
      let trimmedStr = str.trim();
      if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
      else if (str === "0") return 0;
      else if (options.hex && hexRegex.test(trimmedStr)) {
        return parse_int(trimmedStr, 16);
      } else if (trimmedStr.search(/[eE]/) !== -1) {
        const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);
        if (notation) {
          if (options.leadingZeros) {
            trimmedStr = (notation[1] || "") + notation[3];
          } else {
            if (notation[2] === "0" && notation[3][0] === ".") {
            } else {
              return str;
            }
          }
          return options.eNotation ? Number(trimmedStr) : str;
        } else {
          return str;
        }
      } else {
        const match2 = numRegex.exec(trimmedStr);
        if (match2) {
          const sign = match2[1];
          const leadingZeros = match2[2];
          let numTrimmedByZeros = trimZeros(match2[3]);
          if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
          else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
          else if (options.leadingZeros && leadingZeros === str) return 0;
          else {
            const num = Number(trimmedStr);
            const numStr = "" + num;
            if (numStr.search(/[eE]/) !== -1) {
              if (options.eNotation) return num;
              else return str;
            } else if (trimmedStr.indexOf(".") !== -1) {
              if (numStr === "0" && numTrimmedByZeros === "") return num;
              else if (numStr === numTrimmedByZeros) return num;
              else if (sign && numStr === "-" + numTrimmedByZeros) return num;
              else return str;
            }
            if (leadingZeros) {
              return numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str;
            } else {
              return trimmedStr === numStr || trimmedStr === sign + numStr ? num : str;
            }
          }
        } else {
          return str;
        }
      }
    }
    function trimZeros(numStr) {
      if (numStr && numStr.indexOf(".") !== -1) {
        numStr = numStr.replace(/0+$/, "");
        if (numStr === ".") numStr = "0";
        else if (numStr[0] === ".") numStr = "0" + numStr;
        else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1);
        return numStr;
      }
      return numStr;
    }
    function parse_int(numStr, base) {
      if (parseInt) return parseInt(numStr, base);
      else if (Number.parseInt) return Number.parseInt(numStr, base);
      else if (window && window.parseInt) return window.parseInt(numStr, base);
      else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
    }
    module2.exports = toNumber;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) {
    "use strict";
    var util2 = require_util2();
    var xmlNode = require_xmlNode();
    var readDocType = require_DocTypeReader();
    var toNumber = require_strnum();
    var OrderedObjParser = class {
      constructor(options) {
        this.options = options;
        this.currentNode = null;
        this.tagsNodeStack = [];
        this.docTypeEntities = {};
        this.lastEntities = {
          "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
          "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
          "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
          "quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
        };
        this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
        this.htmlEntities = {
          "space": { regex: /&(nbsp|#160);/g, val: " " },
          // "lt" : { regex: /&(lt|#60);/g, val: "<" },
          // "gt" : { regex: /&(gt|#62);/g, val: ">" },
          // "amp" : { regex: /&(amp|#38);/g, val: "&" },
          // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
          // "apos" : { regex: /&(apos|#39);/g, val: "'" },
          "cent": { regex: /&(cent|#162);/g, val: "\xA2" },
          "pound": { regex: /&(pound|#163);/g, val: "\xA3" },
          "yen": { regex: /&(yen|#165);/g, val: "\xA5" },
          "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
          "copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
          "reg": { regex: /&(reg|#174);/g, val: "\xAE" },
          "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
          "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 10)) },
          "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 16)) }
        };
        this.addExternalEntities = addExternalEntities;
        this.parseXml = parseXml;
        this.parseTextData = parseTextData;
        this.resolveNameSpace = resolveNameSpace;
        this.buildAttributesMap = buildAttributesMap;
        this.isItStopNode = isItStopNode;
        this.replaceEntitiesValue = replaceEntitiesValue;
        this.readStopNodeData = readStopNodeData;
        this.saveTextToParentTag = saveTextToParentTag;
        this.addChild = addChild;
      }
    };
    function addExternalEntities(externalEntities) {
      const entKeys = Object.keys(externalEntities);
      for (let i4 = 0; i4 < entKeys.length; i4++) {
        const ent = entKeys[i4];
        this.lastEntities[ent] = {
          regex: new RegExp("&" + ent + ";", "g"),
          val: externalEntities[ent]
        };
      }
    }
    function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
      if (val2 !== void 0) {
        if (this.options.trimValues && !dontTrim) {
          val2 = val2.trim();
        }
        if (val2.length > 0) {
          if (!escapeEntities) val2 = this.replaceEntitiesValue(val2);
          const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
          if (newval === null || newval === void 0) {
            return val2;
          } else if (typeof newval !== typeof val2 || newval !== val2) {
            return newval;
          } else if (this.options.trimValues) {
            return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
          } else {
            const trimmedVal = val2.trim();
            if (trimmedVal === val2) {
              return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
            } else {
              return val2;
            }
          }
        }
      }
    }
    function resolveNameSpace(tagname) {
      if (this.options.removeNSPrefix) {
        const tags = tagname.split(":");
        const prefix2 = tagname.charAt(0) === "/" ? "/" : "";
        if (tags[0] === "xmlns") {
          return "";
        }
        if (tags.length === 2) {
          tagname = prefix2 + tags[1];
        }
      }
      return tagname;
    }
    var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
    function buildAttributesMap(attrStr, jPath, tagName) {
      if (!this.options.ignoreAttributes && typeof attrStr === "string") {
        const matches = util2.getAllMatches(attrStr, attrsRegx);
        const len = matches.length;
        const attrs = {};
        for (let i4 = 0; i4 < len; i4++) {
          const attrName = this.resolveNameSpace(matches[i4][1]);
          let oldVal = matches[i4][4];
          let aName = this.options.attributeNamePrefix + attrName;
          if (attrName.length) {
            if (this.options.transformAttributeName) {
              aName = this.options.transformAttributeName(aName);
            }
            if (aName === "__proto__") aName = "#__proto__";
            if (oldVal !== void 0) {
              if (this.options.trimValues) {
                oldVal = oldVal.trim();
              }
              oldVal = this.replaceEntitiesValue(oldVal);
              const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
              if (newVal === null || newVal === void 0) {
                attrs[aName] = oldVal;
              } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
                attrs[aName] = newVal;
              } else {
                attrs[aName] = parseValue(
                  oldVal,
                  this.options.parseAttributeValue,
                  this.options.numberParseOptions
                );
              }
            } else if (this.options.allowBooleanAttributes) {
              attrs[aName] = true;
            }
          }
        }
        if (!Object.keys(attrs).length) {
          return;
        }
        if (this.options.attributesGroupName) {
          const attrCollection = {};
          attrCollection[this.options.attributesGroupName] = attrs;
          return attrCollection;
        }
        return attrs;
      }
    }
    var parseXml = function(xmlData) {
      xmlData = xmlData.replace(/\r\n?/g, "\n");
      const xmlObj = new xmlNode("!xml");
      let currentNode = xmlObj;
      let textData = "";
      let jPath = "";
      for (let i4 = 0; i4 < xmlData.length; i4++) {
        const ch = xmlData[i4];
        if (ch === "<") {
          if (xmlData[i4 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i4, "Closing Tag is not closed.");
            let tagName = xmlData.substring(i4 + 2, closeIndex).trim();
            if (this.options.removeNSPrefix) {
              const colonIndex = tagName.indexOf(":");
              if (colonIndex !== -1) {
                tagName = tagName.substr(colonIndex + 1);
              }
            }
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode) {
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
            }
            const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
            if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
              throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
            }
            let propIndex = 0;
            if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
              propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
              this.tagsNodeStack.pop();
            } else {
              propIndex = jPath.lastIndexOf(".");
            }
            jPath = jPath.substring(0, propIndex);
            currentNode = this.tagsNodeStack.pop();
            textData = "";
            i4 = closeIndex;
          } else if (xmlData[i4 + 1] === "?") {
            let tagData = readTagExp(xmlData, i4, false, "?>");
            if (!tagData) throw new Error("Pi Tag is not closed.");
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
            } else {
              const childNode = new xmlNode(tagData.tagName);
              childNode.add(this.options.textNodeName, "");
              if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
              }
              this.addChild(currentNode, childNode, jPath);
            }
            i4 = tagData.closeIndex + 1;
          } else if (xmlData.substr(i4 + 1, 3) === "!--") {
            const endIndex = findClosingIndex(xmlData, "-->", i4 + 4, "Comment is not closed.");
            if (this.options.commentPropName) {
              const comment = xmlData.substring(i4 + 4, endIndex - 2);
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
              currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
            }
            i4 = endIndex;
          } else if (xmlData.substr(i4 + 1, 2) === "!D") {
            const result = readDocType(xmlData, i4);
            this.docTypeEntities = result.entities;
            i4 = result.i;
          } else if (xmlData.substr(i4 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i4, "CDATA is not closed.") - 2;
            const tagExp = xmlData.substring(i4 + 9, closeIndex);
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
            if (val2 == void 0) val2 = "";
            if (this.options.cdataPropName) {
              currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
            } else {
              currentNode.add(this.options.textNodeName, val2);
            }
            i4 = closeIndex + 2;
          } else {
            let result = readTagExp(xmlData, i4, this.options.removeNSPrefix);
            let tagName = result.tagName;
            const rawTagName = result.rawTagName;
            let tagExp = result.tagExp;
            let attrExpPresent = result.attrExpPresent;
            let closeIndex = result.closeIndex;
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode && textData) {
              if (currentNode.tagname !== "!xml") {
                textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
              }
            }
            const lastTag = currentNode;
            if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
              currentNode = this.tagsNodeStack.pop();
              jPath = jPath.substring(0, jPath.lastIndexOf("."));
            }
            if (tagName !== xmlObj.tagname) {
              jPath += jPath ? "." + tagName : tagName;
            }
            if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
              let tagContent = "";
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                i4 = result.closeIndex;
              } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
                i4 = result.closeIndex;
              } else {
                const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
                if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
                i4 = result2.i;
                tagContent = result2.tagContent;
              }
              const childNode = new xmlNode(tagName);
              if (tagName !== tagExp && attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
              }
              if (tagContent) {
                tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
              }
              jPath = jPath.substr(0, jPath.lastIndexOf("."));
              childNode.add(this.options.textNodeName, tagContent);
              this.addChild(currentNode, childNode, jPath);
            } else {
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                if (this.options.transformTagName) {
                  tagName = this.options.transformTagName(tagName);
                }
                const childNode = new xmlNode(tagName);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                jPath = jPath.substr(0, jPath.lastIndexOf("."));
              } else {
                const childNode = new xmlNode(tagName);
                this.tagsNodeStack.push(currentNode);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                currentNode = childNode;
              }
              textData = "";
              i4 = closeIndex;
            }
          }
        } else {
          textData += xmlData[i4];
        }
      }
      return xmlObj.child;
    };
    function addChild(currentNode, childNode, jPath) {
      const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
      if (result === false) {
      } else if (typeof result === "string") {
        childNode.tagname = result;
        currentNode.addChild(childNode);
      } else {
        currentNode.addChild(childNode);
      }
    }
    var replaceEntitiesValue = function(val2) {
      if (this.options.processEntities) {
        for (let entityName2 in this.docTypeEntities) {
          const entity = this.docTypeEntities[entityName2];
          val2 = val2.replace(entity.regx, entity.val);
        }
        for (let entityName2 in this.lastEntities) {
          const entity = this.lastEntities[entityName2];
          val2 = val2.replace(entity.regex, entity.val);
        }
        if (this.options.htmlEntities) {
          for (let entityName2 in this.htmlEntities) {
            const entity = this.htmlEntities[entityName2];
            val2 = val2.replace(entity.regex, entity.val);
          }
        }
        val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
      }
      return val2;
    };
    function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
      if (textData) {
        if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0;
        textData = this.parseTextData(
          textData,
          currentNode.tagname,
          jPath,
          false,
          currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
          isLeafNode
        );
        if (textData !== void 0 && textData !== "")
          currentNode.add(this.options.textNodeName, textData);
        textData = "";
      }
      return textData;
    }
    function isItStopNode(stopNodes, jPath, currentTagName) {
      const allNodesExp = "*." + currentTagName;
      for (const stopNodePath in stopNodes) {
        const stopNodeExp = stopNodes[stopNodePath];
        if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true;
      }
      return false;
    }
    function tagExpWithClosingIndex(xmlData, i4, closingChar = ">") {
      let attrBoundary;
      let tagExp = "";
      for (let index6 = i4; index6 < xmlData.length; index6++) {
        let ch = xmlData[index6];
        if (attrBoundary) {
          if (ch === attrBoundary) attrBoundary = "";
        } else if (ch === '"' || ch === "'") {
          attrBoundary = ch;
        } else if (ch === closingChar[0]) {
          if (closingChar[1]) {
            if (xmlData[index6 + 1] === closingChar[1]) {
              return {
                data: tagExp,
                index: index6
              };
            }
          } else {
            return {
              data: tagExp,
              index: index6
            };
          }
        } else if (ch === "	") {
          ch = " ";
        }
        tagExp += ch;
      }
    }
    function findClosingIndex(xmlData, str, i4, errMsg) {
      const closingIndex = xmlData.indexOf(str, i4);
      if (closingIndex === -1) {
        throw new Error(errMsg);
      } else {
        return closingIndex + str.length - 1;
      }
    }
    function readTagExp(xmlData, i4, removeNSPrefix, closingChar = ">") {
      const result = tagExpWithClosingIndex(xmlData, i4 + 1, closingChar);
      if (!result) return;
      let tagExp = result.data;
      const closeIndex = result.index;
      const separatorIndex = tagExp.search(/\s/);
      let tagName = tagExp;
      let attrExpPresent = true;
      if (separatorIndex !== -1) {
        tagName = tagExp.substring(0, separatorIndex);
        tagExp = tagExp.substring(separatorIndex + 1).trimStart();
      }
      const rawTagName = tagName;
      if (removeNSPrefix) {
        const colonIndex = tagName.indexOf(":");
        if (colonIndex !== -1) {
          tagName = tagName.substr(colonIndex + 1);
          attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
        }
      }
      return {
        tagName,
        tagExp,
        closeIndex,
        attrExpPresent,
        rawTagName
      };
    }
    function readStopNodeData(xmlData, tagName, i4) {
      const startIndex = i4;
      let openTagCount = 1;
      for (; i4 < xmlData.length; i4++) {
        if (xmlData[i4] === "<") {
          if (xmlData[i4 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i4, `${tagName} is not closed`);
            let closeTagName = xmlData.substring(i4 + 2, closeIndex).trim();
            if (closeTagName === tagName) {
              openTagCount--;
              if (openTagCount === 0) {
                return {
                  tagContent: xmlData.substring(startIndex, i4),
                  i: closeIndex
                };
              }
            }
            i4 = closeIndex;
          } else if (xmlData[i4 + 1] === "?") {
            const closeIndex = findClosingIndex(xmlData, "?>", i4 + 1, "StopNode is not closed.");
            i4 = closeIndex;
          } else if (xmlData.substr(i4 + 1, 3) === "!--") {
            const closeIndex = findClosingIndex(xmlData, "-->", i4 + 3, "StopNode is not closed.");
            i4 = closeIndex;
          } else if (xmlData.substr(i4 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i4, "StopNode is not closed.") - 2;
            i4 = closeIndex;
          } else {
            const tagData = readTagExp(xmlData, i4, ">");
            if (tagData) {
              const openTagName = tagData && tagData.tagName;
              if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
                openTagCount++;
              }
              i4 = tagData.closeIndex;
            }
          }
        }
      }
    }
    function parseValue(val2, shouldParse, options) {
      if (shouldParse && typeof val2 === "string") {
        const newval = val2.trim();
        if (newval === "true") return true;
        else if (newval === "false") return false;
        else return toNumber(val2, options);
      } else {
        if (util2.isExist(val2)) {
          return val2;
        } else {
          return "";
        }
      }
    }
    module2.exports = OrderedObjParser;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) {
    "use strict";
    function prettify(node, options) {
      return compress2(node, options);
    }
    function compress2(arr, options, jPath) {
      let text;
      const compressedObj = {};
      for (let i4 = 0; i4 < arr.length; i4++) {
        const tagObj = arr[i4];
        const property = propName(tagObj);
        let newJpath = "";
        if (jPath === void 0) newJpath = property;
        else newJpath = jPath + "." + property;
        if (property === options.textNodeName) {
          if (text === void 0) text = tagObj[property];
          else text += "" + tagObj[property];
        } else if (property === void 0) {
          continue;
        } else if (tagObj[property]) {
          let val2 = compress2(tagObj[property], options, newJpath);
          const isLeaf = isLeafTag(val2, options);
          if (tagObj[":@"]) {
            assignAttributes(val2, tagObj[":@"], newJpath, options);
          } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
            val2 = val2[options.textNodeName];
          } else if (Object.keys(val2).length === 0) {
            if (options.alwaysCreateTextNode) val2[options.textNodeName] = "";
            else val2 = "";
          }
          if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
            if (!Array.isArray(compressedObj[property])) {
              compressedObj[property] = [compressedObj[property]];
            }
            compressedObj[property].push(val2);
          } else {
            if (options.isArray(property, newJpath, isLeaf)) {
              compressedObj[property] = [val2];
            } else {
              compressedObj[property] = val2;
            }
          }
        }
      }
      if (typeof text === "string") {
        if (text.length > 0) compressedObj[options.textNodeName] = text;
      } else if (text !== void 0) compressedObj[options.textNodeName] = text;
      return compressedObj;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i4 = 0; i4 < keys.length; i4++) {
        const key = keys[i4];
        if (key !== ":@") return key;
      }
    }
    function assignAttributes(obj, attrMap, jpath, options) {
      if (attrMap) {
        const keys = Object.keys(attrMap);
        const len = keys.length;
        for (let i4 = 0; i4 < len; i4++) {
          const atrrName = keys[i4];
          if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
            obj[atrrName] = [attrMap[atrrName]];
          } else {
            obj[atrrName] = attrMap[atrrName];
          }
        }
      }
    }
    function isLeafTag(obj, options) {
      const { textNodeName } = options;
      const propCount = Object.keys(obj).length;
      if (propCount === 0) {
        return true;
      }
      if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
        return true;
      }
      return false;
    }
    exports2.prettify = prettify;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) {
    var { buildOptions } = require_OptionsBuilder();
    var OrderedObjParser = require_OrderedObjParser();
    var { prettify } = require_node2json();
    var validator2 = require_validator();
    var XMLParser2 = class {
      constructor(options) {
        this.externalEntities = {};
        this.options = buildOptions(options);
      }
      /**
       * Parse XML dats to JS object 
       * @param {string|Buffer} xmlData 
       * @param {boolean|Object} validationOption 
       */
      parse(xmlData, validationOption) {
        if (typeof xmlData === "string") {
        } else if (xmlData.toString) {
          xmlData = xmlData.toString();
        } else {
          throw new Error("XML data is accepted in String or Bytes[] form.");
        }
        if (validationOption) {
          if (validationOption === true) validationOption = {};
          const result = validator2.validate(xmlData, validationOption);
          if (result !== true) {
            throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
          }
        }
        const orderedObjParser = new OrderedObjParser(this.options);
        orderedObjParser.addExternalEntities(this.externalEntities);
        const orderedResult = orderedObjParser.parseXml(xmlData);
        if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
        else return prettify(orderedResult, this.options);
      }
      /**
       * Add Entity which is not by default supported by this library
       * @param {string} key 
       * @param {string} value 
       */
      addEntity(key, value) {
        if (value.indexOf("&") !== -1) {
          throw new Error("Entity value can't have '&'");
        } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
          throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
        } else if (value === "&") {
          throw new Error("An entity with value '&' is not permitted");
        } else {
          this.externalEntities[key] = value;
        }
      }
    };
    module2.exports = XMLParser2;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) {
    var EOL = "\n";
    function toXml(jArray, options) {
      let indentation = "";
      if (options.format && options.indentBy.length > 0) {
        indentation = EOL;
      }
      return arrToStr(jArray, options, "", indentation);
    }
    function arrToStr(arr, options, jPath, indentation) {
      let xmlStr = "";
      let isPreviousElementTag = false;
      for (let i4 = 0; i4 < arr.length; i4++) {
        const tagObj = arr[i4];
        const tagName = propName(tagObj);
        if (tagName === void 0) continue;
        let newJPath = "";
        if (jPath.length === 0) newJPath = tagName;
        else newJPath = `${jPath}.${tagName}`;
        if (tagName === options.textNodeName) {
          let tagText = tagObj[tagName];
          if (!isStopNode(newJPath, options)) {
            tagText = options.tagValueProcessor(tagName, tagText);
            tagText = replaceEntitiesValue(tagText, options);
          }
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += tagText;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.cdataPropName) {
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.commentPropName) {
          xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
          isPreviousElementTag = true;
          continue;
        } else if (tagName[0] === "?") {
          const attStr2 = attr_to_str(tagObj[":@"], options);
          const tempInd = tagName === "?xml" ? "" : indentation;
          let piTextNodeName = tagObj[tagName][0][options.textNodeName];
          piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
          xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
          isPreviousElementTag = true;
          continue;
        }
        let newIdentation = indentation;
        if (newIdentation !== "") {
          newIdentation += options.indentBy;
        }
        const attStr = attr_to_str(tagObj[":@"], options);
        const tagStart = indentation + `<${tagName}${attStr}`;
        const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
        if (options.unpairedTags.indexOf(tagName) !== -1) {
          if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
          else xmlStr += tagStart + "/>";
        } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
          xmlStr += tagStart + "/>";
        } else if (tagValue && tagValue.endsWith(">")) {
          xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
        } else {
          xmlStr += tagStart + ">";
          if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
            xmlStr += indentation + options.indentBy + tagValue + indentation;
          } else {
            xmlStr += tagValue;
          }
          xmlStr += `</${tagName}>`;
        }
        isPreviousElementTag = true;
      }
      return xmlStr;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i4 = 0; i4 < keys.length; i4++) {
        const key = keys[i4];
        if (!obj.hasOwnProperty(key)) continue;
        if (key !== ":@") return key;
      }
    }
    function attr_to_str(attrMap, options) {
      let attrStr = "";
      if (attrMap && !options.ignoreAttributes) {
        for (let attr in attrMap) {
          if (!attrMap.hasOwnProperty(attr)) continue;
          let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
          attrVal = replaceEntitiesValue(attrVal, options);
          if (attrVal === true && options.suppressBooleanAttributes) {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
          } else {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
          }
        }
      }
      return attrStr;
    }
    function isStopNode(jPath, options) {
      jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
      let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
      for (let index6 in options.stopNodes) {
        if (options.stopNodes[index6] === jPath || options.stopNodes[index6] === "*." + tagName) return true;
      }
      return false;
    }
    function replaceEntitiesValue(textValue, options) {
      if (textValue && textValue.length > 0 && options.processEntities) {
        for (let i4 = 0; i4 < options.entities.length; i4++) {
          const entity = options.entities[i4];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    }
    module2.exports = toXml;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) {
    "use strict";
    var buildFromOrderedJs = require_orderedJs2Xml();
    var defaultOptions = {
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      cdataPropName: false,
      format: false,
      indentBy: "  ",
      suppressEmptyNode: false,
      suppressUnpairedNode: true,
      suppressBooleanAttributes: true,
      tagValueProcessor: function(key, a3) {
        return a3;
      },
      attributeValueProcessor: function(attrName, a3) {
        return a3;
      },
      preserveOrder: false,
      commentPropName: false,
      unpairedTags: [],
      entities: [
        { regex: new RegExp("&", "g"), val: "&amp;" },
        //it must be on top
        { regex: new RegExp(">", "g"), val: "&gt;" },
        { regex: new RegExp("<", "g"), val: "&lt;" },
        { regex: new RegExp("'", "g"), val: "&apos;" },
        { regex: new RegExp('"', "g"), val: "&quot;" }
      ],
      processEntities: true,
      stopNodes: [],
      // transformTagName: false,
      // transformAttributeName: false,
      oneListGroup: false
    };
    function Builder(options) {
      this.options = Object.assign({}, defaultOptions, options);
      if (this.options.ignoreAttributes || this.options.attributesGroupName) {
        this.isAttribute = function() {
          return false;
        };
      } else {
        this.attrPrefixLen = this.options.attributeNamePrefix.length;
        this.isAttribute = isAttribute;
      }
      this.processTextOrObjNode = processTextOrObjNode;
      if (this.options.format) {
        this.indentate = indentate;
        this.tagEndChar = ">\n";
        this.newLine = "\n";
      } else {
        this.indentate = function() {
          return "";
        };
        this.tagEndChar = ">";
        this.newLine = "";
      }
    }
    Builder.prototype.build = function(jObj) {
      if (this.options.preserveOrder) {
        return buildFromOrderedJs(jObj, this.options);
      } else {
        if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
          jObj = {
            [this.options.arrayNodeName]: jObj
          };
        }
        return this.j2x(jObj, 0).val;
      }
    };
    Builder.prototype.j2x = function(jObj, level) {
      let attrStr = "";
      let val2 = "";
      for (let key in jObj) {
        if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
        if (typeof jObj[key] === "undefined") {
          if (this.isAttribute(key)) {
            val2 += "";
          }
        } else if (jObj[key] === null) {
          if (this.isAttribute(key)) {
            val2 += "";
          } else if (key[0] === "?") {
            val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
          } else {
            val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
          }
        } else if (jObj[key] instanceof Date) {
          val2 += this.buildTextValNode(jObj[key], key, "", level);
        } else if (typeof jObj[key] !== "object") {
          const attr = this.isAttribute(key);
          if (attr) {
            attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
          } else {
            if (key === this.options.textNodeName) {
              let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
              val2 += this.replaceEntitiesValue(newval);
            } else {
              val2 += this.buildTextValNode(jObj[key], key, "", level);
            }
          }
        } else if (Array.isArray(jObj[key])) {
          const arrLen = jObj[key].length;
          let listTagVal = "";
          let listTagAttr = "";
          for (let j3 = 0; j3 < arrLen; j3++) {
            const item = jObj[key][j3];
            if (typeof item === "undefined") {
            } else if (item === null) {
              if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
              else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
            } else if (typeof item === "object") {
              if (this.options.oneListGroup) {
                const result = this.j2x(item, level + 1);
                listTagVal += result.val;
                if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
                  listTagAttr += result.attrStr;
                }
              } else {
                listTagVal += this.processTextOrObjNode(item, key, level);
              }
            } else {
              if (this.options.oneListGroup) {
                let textValue = this.options.tagValueProcessor(key, item);
                textValue = this.replaceEntitiesValue(textValue);
                listTagVal += textValue;
              } else {
                listTagVal += this.buildTextValNode(item, key, "", level);
              }
            }
          }
          if (this.options.oneListGroup) {
            listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
          }
          val2 += listTagVal;
        } else {
          if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
            const Ks = Object.keys(jObj[key]);
            const L = Ks.length;
            for (let j3 = 0; j3 < L; j3++) {
              attrStr += this.buildAttrPairStr(Ks[j3], "" + jObj[key][Ks[j3]]);
            }
          } else {
            val2 += this.processTextOrObjNode(jObj[key], key, level);
          }
        }
      }
      return { attrStr, val: val2 };
    };
    Builder.prototype.buildAttrPairStr = function(attrName, val2) {
      val2 = this.options.attributeValueProcessor(attrName, "" + val2);
      val2 = this.replaceEntitiesValue(val2);
      if (this.options.suppressBooleanAttributes && val2 === "true") {
        return " " + attrName;
      } else return " " + attrName + '="' + val2 + '"';
    };
    function processTextOrObjNode(object, key, level) {
      const result = this.j2x(object, level + 1);
      if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
        return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
      } else {
        return this.buildObjectNode(result.val, key, result.attrStr, level);
      }
    }
    Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
      if (val2 === "") {
        if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
        else {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        }
      } else {
        let tagEndExp = "</" + key + this.tagEndChar;
        let piClosingChar = "";
        if (key[0] === "?") {
          piClosingChar = "?";
          tagEndExp = "";
        }
        if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
        } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
          return this.indentate(level) + `<!--${val2}-->` + this.newLine;
        } else {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
        }
      }
    };
    Builder.prototype.closeTag = function(key) {
      let closeTag = "";
      if (this.options.unpairedTags.indexOf(key) !== -1) {
        if (!this.options.suppressUnpairedNode) closeTag = "/";
      } else if (this.options.suppressEmptyNode) {
        closeTag = "/";
      } else {
        closeTag = `></${key}`;
      }
      return closeTag;
    };
    Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
      if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
        return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
      } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
        return this.indentate(level) + `<!--${val2}-->` + this.newLine;
      } else if (key[0] === "?") {
        return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
      } else {
        let textValue = this.options.tagValueProcessor(key, val2);
        textValue = this.replaceEntitiesValue(textValue);
        if (textValue === "") {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        } else {
          return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
        }
      }
    };
    Builder.prototype.replaceEntitiesValue = function(textValue) {
      if (textValue && textValue.length > 0 && this.options.processEntities) {
        for (let i4 = 0; i4 < this.options.entities.length; i4++) {
          const entity = this.options.entities[i4];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    };
    function indentate(level) {
      return this.options.indentBy.repeat(level);
    }
    function isAttribute(name) {
      if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
        return name.substr(this.attrPrefixLen);
      } else {
        return false;
      }
    }
    module2.exports = Builder;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
var require_fxp = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) {
    "use strict";
    var validator2 = require_validator();
    var XMLParser2 = require_XMLParser();
    var XMLBuilder = require_json2xml();
    module2.exports = {
      XMLParser: XMLParser2,
      XMLValidator: validator2,
      XMLBuilder
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
var import_smithy_client3, import_fast_xml_parser, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode;
var init_parseXmlBody = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
    import_smithy_client3 = __toESM(require_dist_cjs23());
    import_fast_xml_parser = __toESM(require_fxp());
    init_common2();
    parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        const parser = new import_fast_xml_parser.XMLParser({
          attributeNamePrefix: "",
          htmlEntities: true,
          ignoreAttributes: false,
          ignoreDeclaration: true,
          parseTagValue: false,
          trimValues: false,
          tagValueProcessor: (_3, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0
        });
        parser.addEntity("#xD", "\r");
        parser.addEntity("#10", "\n");
        let parsedObj;
        try {
          parsedObj = parser.parse(encoded, true);
        } catch (e4) {
          if (e4 && typeof e4 === "object") {
            Object.defineProperty(e4, "$responseBodyText", {
              value: encoded
            });
          }
          throw e4;
        }
        const textNodeName = "#text";
        const key = Object.keys(parsedObj)[0];
        const parsedObjToReturn = parsedObj[key];
        if (parsedObjToReturn[textNodeName]) {
          parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
          delete parsedObjToReturn[textNodeName];
        }
        return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn);
      }
      return {};
    });
    parseXmlErrorBody = async (errorBody, context) => {
      const value = await parseXmlBody(errorBody, context);
      if (value.Error) {
        value.Error.message = value.Error.message ?? value.Error.Message;
      }
      return value;
    };
    loadRestXmlErrorCode = (output, data) => {
      var _a2;
      if (((_a2 = data == null ? void 0 : data.Error) == null ? void 0 : _a2.Code) !== void 0) {
        return data.Error.Code;
      }
      if ((data == null ? void 0 : data.Code) !== void 0) {
        return data.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
var init_protocols2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
    init_coercing_serializers();
    init_awsExpectUnion();
    init_parseJsonBody();
    init_parseXmlBody();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js
var dist_es_exports2 = {};
__export(dist_es_exports2, {
  AWSSDKSigV4Signer: () => AWSSDKSigV4Signer,
  AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner,
  AwsSdkSigV4Signer: () => AwsSdkSigV4Signer,
  NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,
  NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS,
  _toBool: () => _toBool,
  _toNum: () => _toNum,
  _toStr: () => _toStr,
  awsExpectUnion: () => awsExpectUnion,
  emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
  getBearerTokenEnvKey: () => getBearerTokenEnvKey,
  loadRestJsonErrorCode: () => loadRestJsonErrorCode,
  loadRestXmlErrorCode: () => loadRestXmlErrorCode,
  parseJsonBody: () => parseJsonBody,
  parseJsonErrorBody: () => parseJsonErrorBody,
  parseXmlBody: () => parseXmlBody,
  parseXmlErrorBody: () => parseXmlErrorBody,
  resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config,
  resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig,
  resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config,
  setCredentialFeature: () => setCredentialFeature,
  setFeature: () => setFeature2,
  state: () => state,
  validateSigningProperties: () => validateSigningProperties
});
var init_dist_es2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js"() {
    init_client();
    init_httpAuthSchemes2();
    init_protocols2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js
var require_dist_cjs24 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID,
      getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions,
      getUserAgentPlugin: () => getUserAgentPlugin3,
      resolveUserAgentConfig: () => resolveUserAgentConfig3,
      userAgentMiddleware: () => userAgentMiddleware
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
    var DEFAULT_UA_APP_ID = void 0;
    function isValidUserAgentAppId(appId) {
      if (appId === void 0) {
        return true;
      }
      return typeof appId === "string" && appId.length <= 50;
    }
    __name(isValidUserAgentAppId, "isValidUserAgentAppId");
    function resolveUserAgentConfig3(input) {
      const normalizedAppIdProvider = (0, import_core17.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
      const { customUserAgent } = input;
      return Object.assign(input, {
        customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
        userAgentAppId: /* @__PURE__ */ __name(async () => {
          var _a2, _b;
          const appId = await normalizedAppIdProvider();
          if (!isValidUserAgentAppId(appId)) {
            const logger3 = ((_b = (_a2 = input.logger) == null ? void 0 : _a2.constructor) == null ? void 0 : _b.name) === "NoOpLogger" || !input.logger ? console : input.logger;
            if (typeof appId !== "string") {
              logger3 == null ? void 0 : logger3.warn("userAgentAppId must be a string or undefined.");
            } else if (appId.length > 50) {
              logger3 == null ? void 0 : logger3.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
            }
          }
          return appId;
        }, "userAgentAppId")
      });
    }
    __name(resolveUserAgentConfig3, "resolveUserAgentConfig");
    var import_util_endpoints5 = require_dist_cjs19();
    var import_protocol_http15 = require_dist_cjs2();
    var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
    async function checkFeatures(context, config, args) {
      var _a2, _b, _c, _d, _e, _f, _g;
      const request = args.request;
      if (((_a2 = request == null ? void 0 : request.headers) == null ? void 0 : _a2["smithy-protocol"]) === "rpc-v2-cbor") {
        (0, import_core22.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M");
      }
      if (typeof config.retryStrategy === "function") {
        const retryStrategy = await config.retryStrategy();
        if (typeof retryStrategy.acquireInitialRetryToken === "function") {
          if ((_c = (_b = retryStrategy.constructor) == null ? void 0 : _b.name) == null ? void 0 : _c.includes("Adaptive")) {
            (0, import_core22.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F");
          } else {
            (0, import_core22.setFeature)(context, "RETRY_MODE_STANDARD", "E");
          }
        } else {
          (0, import_core22.setFeature)(context, "RETRY_MODE_LEGACY", "D");
        }
      }
      if (typeof config.accountIdEndpointMode === "function") {
        const endpointV2 = context.endpointV2;
        if (String((_d = endpointV2 == null ? void 0 : endpointV2.url) == null ? void 0 : _d.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
          (0, import_core22.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O");
        }
        switch (await ((_e = config.accountIdEndpointMode) == null ? void 0 : _e.call(config))) {
          case "disabled":
            (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
            break;
          case "preferred":
            (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
            break;
          case "required":
            (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
            break;
        }
      }
      const identity = (_g = (_f = context.__smithy_context) == null ? void 0 : _f.selectedHttpAuthScheme) == null ? void 0 : _g.identity;
      if (identity == null ? void 0 : identity.$source) {
        const credentials2 = identity;
        if (credentials2.accountId) {
          (0, import_core22.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T");
        }
        for (const [key, value] of Object.entries(credentials2.$source ?? {})) {
          (0, import_core22.setFeature)(context, key, value);
        }
      }
    }
    __name(checkFeatures, "checkFeatures");
    var USER_AGENT = "user-agent";
    var X_AMZ_USER_AGENT = "x-amz-user-agent";
    var SPACE2 = " ";
    var UA_NAME_SEPARATOR = "/";
    var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
    var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
    var UA_ESCAPE_CHAR = "-";
    var BYTE_LIMIT = 1024;
    function encodeFeatures(features) {
      let buffer = "";
      for (const key in features) {
        const val2 = features[key];
        if (buffer.length + val2.length + 1 <= BYTE_LIMIT) {
          if (buffer.length) {
            buffer += "," + val2;
          } else {
            buffer += val2;
          }
          continue;
        }
        break;
      }
      return buffer;
    }
    __name(encodeFeatures, "encodeFeatures");
    var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
      var _a2, _b, _c, _d;
      const { request } = args;
      if (!import_protocol_http15.HttpRequest.isInstance(request)) {
        return next(args);
      }
      const { headers } = request;
      const userAgent = ((_a2 = context == null ? void 0 : context.userAgent) == null ? void 0 : _a2.map(escapeUserAgent)) || [];
      const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
      await checkFeatures(context, options, args);
      const awsContext = context;
      defaultUserAgent.push(
        `m/${encodeFeatures(
          Object.assign({}, (_b = context.__smithy_context) == null ? void 0 : _b.features, (_c = awsContext.__aws_sdk_context) == null ? void 0 : _c.features)
        )}`
      );
      const customUserAgent = ((_d = options == null ? void 0 : options.customUserAgent) == null ? void 0 : _d.map(escapeUserAgent)) || [];
      const appId = await options.userAgentAppId();
      if (appId) {
        defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
      }
      const prefix2 = (0, import_util_endpoints5.getUserAgentPrefix)();
      const sdkUserAgentValue = (prefix2 ? [prefix2] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE2);
      const normalUAValue = [
        ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
        ...customUserAgent
      ].join(SPACE2);
      if (options.runtime !== "browser") {
        if (normalUAValue) {
          headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
        }
        headers[USER_AGENT] = sdkUserAgentValue;
      } else {
        headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
      }
      return next({
        ...args,
        request
      });
    }, "userAgentMiddleware");
    var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => {
      var _a2;
      const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
      const version3 = (_a2 = userAgentPair[1]) == null ? void 0 : _a2.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
      const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
      const prefix2 = name.substring(0, prefixSeparatorIndex);
      let uaName = name.substring(prefixSeparatorIndex + 1);
      if (prefix2 === "api") {
        uaName = uaName.toLowerCase();
      }
      return [prefix2, uaName, version3].filter((item) => item && item.length > 0).reduce((acc, item, index6) => {
        switch (index6) {
          case 0:
            return item;
          case 1:
            return `${acc}/${item}`;
          default:
            return `${acc}#${item}`;
        }
      }, "");
    }, "escapeUserAgent");
    var getUserAgentMiddlewareOptions = {
      name: "getUserAgentMiddleware",
      step: "build",
      priority: "low",
      tags: ["SET_USER_AGENT", "USER_AGENT"],
      override: true
    };
    var getUserAgentPlugin3 = /* @__PURE__ */ __name((config) => ({
      applyToStack: /* @__PURE__ */ __name((clientStack) => {
        clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
      }, "applyToStack")
    }), "getUserAgentPlugin");
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js
var require_dist_cjs25 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      SelectorType: () => SelectorType,
      booleanSelector: () => booleanSelector,
      numberSelector: () => numberSelector
    });
    module2.exports = __toCommonJS2(src_exports);
    var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => {
      if (!(key in obj))
        return void 0;
      if (obj[key] === "true")
        return true;
      if (obj[key] === "false")
        return false;
      throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
    }, "booleanSelector");
    var numberSelector = /* @__PURE__ */ __name((obj, key, type) => {
      if (!(key in obj))
        return void 0;
      const numberValue = parseInt(obj[key], 10);
      if (Number.isNaN(numberValue)) {
        throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`);
      }
      return numberValue;
    }, "numberSelector");
    var SelectorType = /* @__PURE__ */ ((SelectorType2) => {
      SelectorType2["ENV"] = "env";
      SelectorType2["CONFIG"] = "shared config entry";
      return SelectorType2;
    })(SelectorType || {});
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-cjs/index.js
var require_dist_cjs26 = __commonJS({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT,
      CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT,
      DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT,
      DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT,
      ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT,
      ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT,
      NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS3,
      NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS3,
      NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS3,
      NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS3,
      REGION_ENV_NAME: () => REGION_ENV_NAME,
      REGION_INI_NAME: () => REGION_INI_NAME,
      getRegionInfo: () => getRegionInfo,
      resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig,
      resolveEndpointsConfig: () => resolveEndpointsConfig,
      resolveRegionConfig: () => resolveRegionConfig3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_config_provider = require_dist_cjs25();
    var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
    var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
    var DEFAULT_USE_DUALSTACK_ENDPOINT = false;
    var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS3 = {
      environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV),
      configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
      default: false
    };
    var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
    var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
    var DEFAULT_USE_FIPS_ENDPOINT = false;
    var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS3 = {
      environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV),
      configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
      default: false
    };
    var import_util_middleware7 = require_dist_cjs6();
    var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => {
      const { tls, endpoint, urlParser, useDualstackEndpoint } = input;
      return Object.assign(input, {
        tls: tls ?? true,
        endpoint: (0, import_util_middleware7.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint),
        isCustomEndpoint: true,
        useDualstackEndpoint: (0, import_util_middleware7.normalizeProvider)(useDualstackEndpoint ?? false)
      });
    }, "resolveCustomEndpointsConfig");
    var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => {
      const { tls = true } = input;
      const region = await input.region();
      const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/);
      if (!dnsHostRegex.test(region)) {
        throw new Error("Invalid region in client config");
      }
      const useDualstackEndpoint = await input.useDualstackEndpoint();
      const useFipsEndpoint = await input.useFipsEndpoint();
      const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {};
      if (!hostname) {
        throw new Error("Cannot resolve hostname from client config");
      }
      return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`);
    }, "getEndpointFromRegion");
    var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => {
      const useDualstackEndpoint = (0, import_util_middleware7.normalizeProvider)(input.useDualstackEndpoint ?? false);
      const { endpoint, useFipsEndpoint, urlParser, tls } = input;
      return Object.assign(input, {
        tls: tls ?? true,
        endpoint: endpoint ? (0, import_util_middleware7.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),
        isCustomEndpoint: !!endpoint,
        useDualstackEndpoint
      });
    }, "resolveEndpointsConfig");
    var REGION_ENV_NAME = "AWS_REGION";
    var REGION_INI_NAME = "region";
    var NODE_REGION_CONFIG_OPTIONS3 = {
      environmentVariableSelector: (env3) => env3[REGION_ENV_NAME],
      configFileSelector: (profile) => profile[REGION_INI_NAME],
      default: () => {
        throw new Error("Region is missing");
      }
    };
    var NODE_REGION_CONFIG_FILE_OPTIONS3 = {
      preferredFile: "credentials"
    };
    var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
    var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
    var resolveRegionConfig3 = /* @__PURE__ */ __name((input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return Object.assign(input, {
        region: async () => {
          if (typeof region === "string") {
            return getRealRegion(region);
          }
          const providedRegion = await region();
          return getRealRegion(providedRegion);
        },
        useFipsEndpoint: async () => {
          const providedRegion = typeof region === "string" ? region : await region();
          if (isFipsRegion(providedRegion)) {
            return true;
          }
          return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
        }
      });
    }, "resolveRegionConfig");
    var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => {
      var _a2;
      return (_a2 = variants.find(
        ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack")
      )) == null ? void 0 : _a2.hostname;
    }, "getHostnameFromVariants");
    var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname");
    var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition");
    var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => {
      if (signingRegion) {
        return signingRegion;
      } else if (useFipsEndpoint) {
        const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\.");
        const regionRegexmatchArray = hostname.match(regionRegexJs);
        if (regionRegexmatchArray) {
          return regionRegexmatchArray[0].slice(1, -1);
        }
      }
    }, "getResolvedSigningRegion");
    var getRegionInfo = /* @__PURE__ */ __name((region, {
      useFipsEndpoint = false,
      useDualstackEndpoint = false,
      signingService,
      regionHash,
      partitionHash
    }) => {
      var _a2, _b, _c, _d, _e;
      const partition = getResolvedPartition(region, { partitionHash });
      const resolvedRegion = region in regionHash ? region : ((_a2 = partitionHash[partition]) == null ? void 0 : _a2.endpoint) ?? region;
      const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint };
      const regionHostname = getHostnameFromVariants((_b = regionHash[resolvedRegion]) == null ? void 0 : _b.variants, hostnameOptions);
      const partitionHostname = getHostnameFromVariants((_c = partitionHash[partition]) == null ? void 0 : _c.variants, hostnameOptions);
      const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname });
      if (hostname === void 0) {
        throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`);
      }
      const signingRegion = getResolvedSigningRegion(hostname, {
        signingRegion: (_d = regionHash[resolvedRegion]) == null ? void 0 : _d.signingRegion,
        regionRegex: partitionHash[partition].regionRegex,
        useFipsEndpoint
      });
      return {
        partition,
        signingService,
        hostname,
        ...signingRegion && { signingRegion },
        ...((_e = regionHash[resolvedRegion]) == null ? void 0 : _e.signingService) && {
          signingService: regionHash[resolvedRegion].signingService
        }
      };
    }, "getRegionInfo");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-cjs/index.js
var require_dist_cjs27 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      contentLengthMiddleware: () => contentLengthMiddleware,
      contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions,
      getContentLengthPlugin: () => getContentLengthPlugin3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var CONTENT_LENGTH_HEADER = "content-length";
    function contentLengthMiddleware(bodyLengthChecker) {
      return (next) => async (args) => {
        const request = args.request;
        if (import_protocol_http15.HttpRequest.isInstance(request)) {
          const { body, headers } = request;
          if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
            try {
              const length = bodyLengthChecker(body);
              request.headers = {
                ...request.headers,
                [CONTENT_LENGTH_HEADER]: String(length)
              };
            } catch (error2) {
            }
          }
        }
        return next({
          ...args,
          request
        });
      };
    }
    __name(contentLengthMiddleware, "contentLengthMiddleware");
    var contentLengthMiddlewareOptions = {
      step: "build",
      tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
      name: "contentLengthMiddleware",
      override: true
    };
    var getContentLengthPlugin3 = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
      }
    }), "getContentLengthPlugin");
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js
var require_getHomeDir = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getHomeDir = void 0;
    var os_1 = require("os");
    var path_1 = require("path");
    var homeDirCache = {};
    var getHomeDirCacheKey = () => {
      if (process && process.geteuid) {
        return `${process.geteuid()}`;
      }
      return "DEFAULT";
    };
    var getHomeDir2 = () => {
      const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env;
      if (HOME)
        return HOME;
      if (USERPROFILE)
        return USERPROFILE;
      if (HOMEPATH)
        return `${HOMEDRIVE}${HOMEPATH}`;
      const homeDirCacheKey = getHomeDirCacheKey();
      if (!homeDirCache[homeDirCacheKey])
        homeDirCache[homeDirCacheKey] = (0, os_1.homedir)();
      return homeDirCache[homeDirCacheKey];
    };
    exports2.getHomeDir = getHomeDir2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js
var require_getSSOTokenFilepath = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSSOTokenFilepath = void 0;
    var crypto_1 = require("crypto");
    var path_1 = require("path");
    var getHomeDir_1 = require_getHomeDir();
    var getSSOTokenFilepath2 = (id) => {
      const hasher = (0, crypto_1.createHash)("sha1");
      const cacheName = hasher.update(id).digest("hex");
      return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`);
    };
    exports2.getSSOTokenFilepath = getSSOTokenFilepath2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js
var require_getSSOTokenFromFile = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSSOTokenFromFile = void 0;
    var fs_1 = require("fs");
    var getSSOTokenFilepath_1 = require_getSSOTokenFilepath();
    var { readFile: readFile2 } = fs_1.promises;
    var getSSOTokenFromFile2 = async (id) => {
      const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id);
      const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8");
      return JSON.parse(ssoTokenText);
    };
    exports2.getSSOTokenFromFile = getSSOTokenFromFile2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js
var require_slurpFile = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.slurpFile = void 0;
    var fs_1 = require("fs");
    var { readFile: readFile2 } = fs_1.promises;
    var filePromisesHash = {};
    var slurpFile = (path4, options) => {
      if (!filePromisesHash[path4] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) {
        filePromisesHash[path4] = readFile2(path4, "utf8");
      }
      return filePromisesHash[path4];
    };
    exports2.slurpFile = slurpFile;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js
var require_dist_cjs28 = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR,
      DEFAULT_PROFILE: () => DEFAULT_PROFILE,
      ENV_PROFILE: () => ENV_PROFILE,
      getProfileName: () => getProfileName,
      loadSharedConfigFiles: () => loadSharedConfigFiles,
      loadSsoSessionData: () => loadSsoSessionData,
      parseKnownFiles: () => parseKnownFiles
    });
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_getHomeDir(), module2.exports);
    var ENV_PROFILE = "AWS_PROFILE";
    var DEFAULT_PROFILE = "default";
    var getProfileName = /* @__PURE__ */ __name((init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName");
    __reExport(src_exports, require_getSSOTokenFilepath(), module2.exports);
    __reExport(src_exports, require_getSSOTokenFromFile(), module2.exports);
    var import_types5 = require_dist_cjs();
    var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => {
      const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
      if (indexOfSeparator === -1) {
        return false;
      }
      return Object.values(import_types5.IniSectionType).includes(key.substring(0, indexOfSeparator));
    }).reduce(
      (acc, [key, value]) => {
        const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
        const updatedKey = key.substring(0, indexOfSeparator) === import_types5.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
        acc[updatedKey] = value;
        return acc;
      },
      {
        // Populate default profile, if present.
        ...data.default && { default: data.default }
      }
    ), "getConfigData");
    var import_path8 = require("path");
    var import_getHomeDir = require_getHomeDir();
    var ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
    var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path8.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath");
    var import_getHomeDir2 = require_getHomeDir();
    var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
    var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path8.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath");
    var import_getHomeDir3 = require_getHomeDir();
    var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
    var profileNameBlockList = ["__proto__", "profile __proto__"];
    var parseIni = /* @__PURE__ */ __name((iniData) => {
      const map2 = {};
      let currentSection;
      let currentSubSection;
      for (const iniLine of iniData.split(/\r?\n/)) {
        const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
        const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
        if (isSection) {
          currentSection = void 0;
          currentSubSection = void 0;
          const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
          const matches = prefixKeyRegex.exec(sectionName);
          if (matches) {
            const [, prefix2, , name] = matches;
            if (Object.values(import_types5.IniSectionType).includes(prefix2)) {
              currentSection = [prefix2, name].join(CONFIG_PREFIX_SEPARATOR);
            }
          } else {
            currentSection = sectionName;
          }
          if (profileNameBlockList.includes(sectionName)) {
            throw new Error(`Found invalid profile name "${sectionName}"`);
          }
        } else if (currentSection) {
          const indexOfEqualsSign = trimmedLine.indexOf("=");
          if (![0, -1].includes(indexOfEqualsSign)) {
            const [name, value] = [
              trimmedLine.substring(0, indexOfEqualsSign).trim(),
              trimmedLine.substring(indexOfEqualsSign + 1).trim()
            ];
            if (value === "") {
              currentSubSection = name;
            } else {
              if (currentSubSection && iniLine.trimStart() === iniLine) {
                currentSubSection = void 0;
              }
              map2[currentSection] = map2[currentSection] || {};
              const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
              map2[currentSection][key] = value;
            }
          }
        }
      }
      return map2;
    }, "parseIni");
    var import_slurpFile = require_slurpFile();
    var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError");
    var CONFIG_PREFIX_SEPARATOR = ".";
    var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init2 = {}) => {
      const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2;
      const homeDir = (0, import_getHomeDir3.getHomeDir)();
      const relativeHomeDirPrefix = "~/";
      let resolvedFilepath = filepath;
      if (filepath.startsWith(relativeHomeDirPrefix)) {
        resolvedFilepath = (0, import_path8.join)(homeDir, filepath.slice(2));
      }
      let resolvedConfigFilepath = configFilepath;
      if (configFilepath.startsWith(relativeHomeDirPrefix)) {
        resolvedConfigFilepath = (0, import_path8.join)(homeDir, configFilepath.slice(2));
      }
      const parsedFiles = await Promise.all([
        (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).then(getConfigData).catch(swallowError),
        (0, import_slurpFile.slurpFile)(resolvedFilepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).catch(swallowError)
      ]);
      return {
        configFile: parsedFiles[0],
        credentialsFile: parsedFiles[1]
      };
    }, "loadSharedConfigFiles");
    var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types5.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData");
    var import_slurpFile2 = require_slurpFile();
    var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError");
    var loadSsoSessionData = /* @__PURE__ */ __name(async (init2 = {}) => (0, import_slurpFile2.slurpFile)(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData");
    var mergeConfigFiles = /* @__PURE__ */ __name((...files) => {
      const merged = {};
      for (const file of files) {
        for (const [key, values] of Object.entries(file)) {
          if (merged[key] !== void 0) {
            Object.assign(merged[key], values);
          } else {
            merged[key] = values;
          }
        }
      }
      return merged;
    }, "mergeConfigFiles");
    var parseKnownFiles = /* @__PURE__ */ __name(async (init2) => {
      const parsedFiles = await loadSharedConfigFiles(init2);
      return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
    }, "parseKnownFiles");
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-cjs/index.js
var require_dist_cjs29 = __commonJS({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      loadConfig: () => loadConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_property_provider2 = require_dist_cjs20();
    function getSelectorName(functionString) {
      try {
        const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
        constants.delete("CONFIG");
        constants.delete("CONFIG_PREFIX_SEPARATOR");
        constants.delete("ENV");
        return [...constants].join(", ");
      } catch (e4) {
        return functionString;
      }
    }
    __name(getSelectorName, "getSelectorName");
    var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => {
      try {
        const config = envVarSelector(process.env, options);
        if (config === void 0) {
          throw new Error();
        }
        return config;
      } catch (e4) {
        throw new import_property_provider2.CredentialsProviderError(
          e4.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`,
          { logger: options == null ? void 0 : options.logger }
        );
      }
    }, "fromEnv");
    var import_shared_ini_file_loader = require_dist_cjs28();
    var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init2 } = {}) => async () => {
      const profile = (0, import_shared_ini_file_loader.getProfileName)(init2);
      const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init2);
      const profileFromCredentials = credentialsFile[profile] || {};
      const profileFromConfig = configFile[profile] || {};
      const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
      try {
        const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
        const configValue = configSelector(mergedProfile, cfgFile);
        if (configValue === void 0) {
          throw new Error();
        }
        return configValue;
      } catch (e4) {
        throw new import_property_provider2.CredentialsProviderError(
          e4.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`,
          { logger: init2.logger }
        );
      }
    }, "fromSharedConfigFiles");
    var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction");
    var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider2.fromStatic)(defaultValue), "fromStatic");
    var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
      const { signingName, logger: logger3 } = configuration;
      const envOptions = { signingName, logger: logger3 };
      return (0, import_property_provider2.memoize)(
        (0, import_property_provider2.chain)(
          fromEnv(environmentVariableSelector, envOptions),
          fromSharedConfigFiles(configFileSelector, configuration),
          fromStatic(defaultValue)
        )
      );
    }, "loadConfig");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js
var require_getEndpointUrlConfig = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getEndpointUrlConfig = void 0;
    var shared_ini_file_loader_1 = require_dist_cjs28();
    var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
    var CONFIG_ENDPOINT_URL = "endpoint_url";
    var getEndpointUrlConfig = (serviceId) => ({
      environmentVariableSelector: (env3) => {
        const serviceSuffixParts = serviceId.split(" ").map((w3) => w3.toUpperCase());
        const serviceEndpointUrl = env3[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
        if (serviceEndpointUrl)
          return serviceEndpointUrl;
        const endpointUrl = env3[ENV_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      configFileSelector: (profile, config) => {
        if (config && profile.services) {
          const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
          if (servicesSection) {
            const servicePrefixParts = serviceId.split(" ").map((w3) => w3.toLowerCase());
            const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
            if (endpointUrl2)
              return endpointUrl2;
          }
        }
        const endpointUrl = profile[CONFIG_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      default: void 0
    });
    exports2.getEndpointUrlConfig = getEndpointUrlConfig;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js
var require_getEndpointFromConfig = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getEndpointFromConfig = void 0;
    var node_config_provider_1 = require_dist_cjs29();
    var getEndpointUrlConfig_1 = require_getEndpointUrlConfig();
    var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))();
    exports2.getEndpointFromConfig = getEndpointFromConfig;
  }
});

// ../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-cjs/index.js
var require_dist_cjs30 = __commonJS({
  "../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      parseQueryString: () => parseQueryString
    });
    module2.exports = __toCommonJS2(src_exports);
    function parseQueryString(querystring) {
      const query = {};
      querystring = querystring.replace(/^\?/, "");
      if (querystring) {
        for (const pair of querystring.split("&")) {
          let [key, value = null] = pair.split("=");
          key = decodeURIComponent(key);
          if (value) {
            value = decodeURIComponent(value);
          }
          if (!(key in query)) {
            query[key] = value;
          } else if (Array.isArray(query[key])) {
            query[key].push(value);
          } else {
            query[key] = [query[key], value];
          }
        }
      }
      return query;
    }
    __name(parseQueryString, "parseQueryString");
  }
});

// ../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-cjs/index.js
var require_dist_cjs31 = __commonJS({
  "../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      parseUrl: () => parseUrl3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_querystring_parser = require_dist_cjs30();
    var parseUrl3 = /* @__PURE__ */ __name((url) => {
      if (typeof url === "string") {
        return parseUrl3(new URL(url));
      }
      const { hostname, pathname, port, protocol, search } = url;
      let query;
      if (search) {
        query = (0, import_querystring_parser.parseQueryString)(search);
      }
      return {
        hostname,
        port: port ? parseInt(port) : void 0,
        protocol,
        path: pathname,
        query
      };
    }, "parseUrl");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js
var require_dist_cjs32 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      endpointMiddleware: () => endpointMiddleware,
      endpointMiddlewareOptions: () => endpointMiddlewareOptions,
      getEndpointFromInstructions: () => getEndpointFromInstructions,
      getEndpointPlugin: () => getEndpointPlugin4,
      resolveEndpointConfig: () => resolveEndpointConfig3,
      resolveParams: () => resolveParams,
      toEndpointV1: () => toEndpointV1
    });
    module2.exports = __toCommonJS2(src_exports);
    var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => {
      const bucket = (endpointParams == null ? void 0 : endpointParams.Bucket) || "";
      if (typeof endpointParams.Bucket === "string") {
        endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
      }
      if (isArnBucketName(bucket)) {
        if (endpointParams.ForcePathStyle === true) {
          throw new Error("Path-style addressing cannot be used with ARN buckets");
        }
      } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
        endpointParams.ForcePathStyle = true;
      }
      if (endpointParams.DisableMultiRegionAccessPoints) {
        endpointParams.disableMultiRegionAccessPoints = true;
        endpointParams.DisableMRAP = true;
      }
      return endpointParams;
    }, "resolveParamsForS3");
    var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
    var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
    var DOTS_PATTERN = /\.\./;
    var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName");
    var isArnBucketName = /* @__PURE__ */ __name((bucketName) => {
      const [arn, partition, service, , , bucket] = bucketName.split(":");
      const isArn = arn === "arn" && bucketName.split(":").length >= 6;
      const isValidArn = Boolean(isArn && partition && service && bucket);
      if (isArn && !isValidArn) {
        throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
      }
      return isValidArn;
    }, "isArnBucketName");
    var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => {
      const configProvider = /* @__PURE__ */ __name(async () => {
        const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
        if (typeof configValue === "function") {
          return configValue();
        }
        return configValue;
      }, "configProvider");
      if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
        return async () => {
          const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = (credentials2 == null ? void 0 : credentials2.credentialScope) ?? (credentials2 == null ? void 0 : credentials2.CredentialScope);
          return configValue;
        };
      }
      if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
        return async () => {
          const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = (credentials2 == null ? void 0 : credentials2.accountId) ?? (credentials2 == null ? void 0 : credentials2.AccountId);
          return configValue;
        };
      }
      if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
        return async () => {
          const endpoint = await configProvider();
          if (endpoint && typeof endpoint === "object") {
            if ("url" in endpoint) {
              return endpoint.url.href;
            }
            if ("hostname" in endpoint) {
              const { protocol, hostname, port, path: path4 } = endpoint;
              return `${protocol}//${hostname}${port ? ":" + port : ""}${path4}`;
            }
          }
          return endpoint;
        };
      }
      return configProvider;
    }, "createConfigValueProvider");
    var import_getEndpointFromConfig = require_getEndpointFromConfig();
    var import_url_parser3 = require_dist_cjs31();
    var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => {
      if (typeof endpoint === "object") {
        if ("url" in endpoint) {
          return (0, import_url_parser3.parseUrl)(endpoint.url);
        }
        return endpoint;
      }
      return (0, import_url_parser3.parseUrl)(endpoint);
    }, "toEndpointV1");
    var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => {
      if (!clientConfig.endpoint) {
        let endpointFromConfig;
        if (clientConfig.serviceConfiguredEndpoint) {
          endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
        } else {
          endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId);
        }
        if (endpointFromConfig) {
          clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
        }
      }
      const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
      if (typeof clientConfig.endpointProvider !== "function") {
        throw new Error("config.endpointProvider is not set.");
      }
      const endpoint = clientConfig.endpointProvider(endpointParams, context);
      return endpoint;
    }, "getEndpointFromInstructions");
    var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => {
      var _a2;
      const endpointParams = {};
      const instructions = ((_a2 = instructionsSupplier == null ? void 0 : instructionsSupplier.getEndpointParameterInstructions) == null ? void 0 : _a2.call(instructionsSupplier)) || {};
      for (const [name, instruction] of Object.entries(instructions)) {
        switch (instruction.type) {
          case "staticContextParams":
            endpointParams[name] = instruction.value;
            break;
          case "contextParams":
            endpointParams[name] = commandInput[instruction.name];
            break;
          case "clientContextParams":
          case "builtInParams":
            endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)();
            break;
          case "operationContextParams":
            endpointParams[name] = instruction.get(commandInput);
            break;
          default:
            throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
        }
      }
      if (Object.keys(instructions).length === 0) {
        Object.assign(endpointParams, clientConfig);
      }
      if (String(clientConfig.serviceId).toLowerCase() === "s3") {
        await resolveParamsForS3(endpointParams);
      }
      return endpointParams;
    }, "resolveParams");
    var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
    var import_util_middleware7 = require_dist_cjs6();
    var endpointMiddleware = /* @__PURE__ */ __name(({
      config,
      instructions
    }) => {
      return (next, context) => async (args) => {
        var _a2, _b, _c;
        if (config.endpoint) {
          (0, import_core17.setFeature)(context, "ENDPOINT_OVERRIDE", "N");
        }
        const endpoint = await getEndpointFromInstructions(
          args.input,
          {
            getEndpointParameterInstructions() {
              return instructions;
            }
          },
          { ...config },
          context
        );
        context.endpointV2 = endpoint;
        context.authSchemes = (_a2 = endpoint.properties) == null ? void 0 : _a2.authSchemes;
        const authScheme = (_b = context.authSchemes) == null ? void 0 : _b[0];
        if (authScheme) {
          context["signing_region"] = authScheme.signingRegion;
          context["signing_service"] = authScheme.signingName;
          const smithyContext = (0, import_util_middleware7.getSmithyContext)(context);
          const httpAuthOption = (_c = smithyContext == null ? void 0 : smithyContext.selectedHttpAuthScheme) == null ? void 0 : _c.httpAuthOption;
          if (httpAuthOption) {
            httpAuthOption.signingProperties = Object.assign(
              httpAuthOption.signingProperties || {},
              {
                signing_region: authScheme.signingRegion,
                signingRegion: authScheme.signingRegion,
                signing_service: authScheme.signingName,
                signingName: authScheme.signingName,
                signingRegionSet: authScheme.signingRegionSet
              },
              authScheme.properties
            );
          }
        }
        return next({
          ...args
        });
      };
    }, "endpointMiddleware");
    var import_middleware_serde5 = require_dist_cjs7();
    var endpointMiddlewareOptions = {
      step: "serialize",
      tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
      name: "endpointV2Middleware",
      override: true,
      relation: "before",
      toMiddleware: import_middleware_serde5.serializerMiddlewareOption.name
    };
    var getEndpointPlugin4 = /* @__PURE__ */ __name((config, instructions) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(
          endpointMiddleware({
            config,
            instructions
          }),
          endpointMiddlewareOptions
        );
      }
    }), "getEndpointPlugin");
    var import_getEndpointFromConfig2 = require_getEndpointFromConfig();
    var resolveEndpointConfig3 = /* @__PURE__ */ __name((input) => {
      const tls = input.tls ?? true;
      const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
      const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware7.normalizeProvider)(endpoint)()) : void 0;
      const isCustomEndpoint = !!endpoint;
      const resolvedConfig = Object.assign(input, {
        endpoint: customEndpointProvider,
        tls,
        isCustomEndpoint,
        useDualstackEndpoint: (0, import_util_middleware7.normalizeProvider)(useDualstackEndpoint ?? false),
        useFipsEndpoint: (0, import_util_middleware7.normalizeProvider)(useFipsEndpoint ?? false)
      });
      let configuredEndpointPromise = void 0;
      resolvedConfig.serviceConfiguredEndpoint = async () => {
        if (input.serviceId && !configuredEndpointPromise) {
          configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId);
        }
        return configuredEndpointPromise;
      };
      return resolvedConfig;
    }, "resolveEndpointConfig");
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    import_crypto2.default.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
var import_crypto2, rnds8Pool, poolPtr;
var init_rng = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() {
    import_crypto2 = __toESM(require("crypto"));
    rnds8Pool = new Uint8Array(256);
    poolPtr = rnds8Pool.length;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js
var regex_default;
var init_regex = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js"() {
    regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js
function validate(uuid) {
  return typeof uuid === "string" && regex_default.test(uuid);
}
var validate_default;
var init_validate = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js"() {
    init_regex();
    validate_default = validate;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
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]];
}
function stringify(arr, offset = 0) {
  const uuid = unsafeStringify(arr, offset);
  if (!validate_default(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
var byteToHex, stringify_default;
var init_stringify = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
    init_validate();
    byteToHex = [];
    for (let i4 = 0; i4 < 256; ++i4) {
      byteToHex.push((i4 + 256).toString(16).slice(1));
    }
    stringify_default = stringify;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js
function v1(options, buf, offset) {
  let i4 = buf && offset || 0;
  const b3 = buf || new Array(16);
  options = options || {};
  let node = options.node || _nodeId;
  let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
  if (node == null || clockseq == null) {
    const seedBytes = options.random || (options.rng || rng)();
    if (node == null) {
      node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
    }
    if (clockseq == null) {
      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
    }
  }
  let msecs = options.msecs !== void 0 ? options.msecs : Date.now();
  let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
  const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
  if (dt < 0 && options.clockseq === void 0) {
    clockseq = clockseq + 1 & 16383;
  }
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
    nsecs = 0;
  }
  if (nsecs >= 1e4) {
    throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  }
  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;
  msecs += 122192928e5;
  const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
  b3[i4++] = tl >>> 24 & 255;
  b3[i4++] = tl >>> 16 & 255;
  b3[i4++] = tl >>> 8 & 255;
  b3[i4++] = tl & 255;
  const tmh = msecs / 4294967296 * 1e4 & 268435455;
  b3[i4++] = tmh >>> 8 & 255;
  b3[i4++] = tmh & 255;
  b3[i4++] = tmh >>> 24 & 15 | 16;
  b3[i4++] = tmh >>> 16 & 255;
  b3[i4++] = clockseq >>> 8 | 128;
  b3[i4++] = clockseq & 255;
  for (let n3 = 0; n3 < 6; ++n3) {
    b3[i4 + n3] = node[n3];
  }
  return buf || unsafeStringify(b3);
}
var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default;
var init_v1 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js"() {
    init_rng();
    init_stringify();
    _lastMSecs = 0;
    _lastNSecs = 0;
    v1_default = v1;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js
function parse2(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  let v6;
  const arr = new Uint8Array(16);
  arr[0] = (v6 = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v6 >>> 16 & 255;
  arr[2] = v6 >>> 8 & 255;
  arr[3] = v6 & 255;
  arr[4] = (v6 = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v6 & 255;
  arr[6] = (v6 = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v6 & 255;
  arr[8] = (v6 = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v6 & 255;
  arr[10] = (v6 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v6 / 4294967296 & 255;
  arr[12] = v6 >>> 24 & 255;
  arr[13] = v6 >>> 16 & 255;
  arr[14] = v6 >>> 8 & 255;
  arr[15] = v6 & 255;
  return arr;
}
var parse_default;
var init_parse = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js"() {
    init_validate();
    parse_default = parse2;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js
function stringToBytes(str) {
  str = unescape(encodeURIComponent(str));
  const bytes = [];
  for (let i4 = 0; i4 < str.length; ++i4) {
    bytes.push(str.charCodeAt(i4));
  }
  return bytes;
}
function v35(name, version3, hashfunc) {
  function generateUUID(value, namespace, buf, offset) {
    var _namespace;
    if (typeof value === "string") {
      value = stringToBytes(value);
    }
    if (typeof namespace === "string") {
      namespace = parse_default(namespace);
    }
    if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
      throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
    }
    let bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 15 | version3;
    bytes[8] = bytes[8] & 63 | 128;
    if (buf) {
      offset = offset || 0;
      for (let i4 = 0; i4 < 16; ++i4) {
        buf[offset + i4] = bytes[i4];
      }
      return buf;
    }
    return unsafeStringify(bytes);
  }
  try {
    generateUUID.name = name;
  } catch (err2) {
  }
  generateUUID.DNS = DNS;
  generateUUID.URL = URL2;
  return generateUUID;
}
var DNS, URL2;
var init_v35 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js"() {
    init_stringify();
    init_parse();
    DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
    URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js
function md5(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return import_crypto3.default.createHash("md5").update(bytes).digest();
}
var import_crypto3, md5_default;
var init_md5 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js"() {
    import_crypto3 = __toESM(require("crypto"));
    md5_default = md5;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js
var v3, v3_default2;
var init_v32 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js"() {
    init_v35();
    init_md5();
    v3 = v35("v3", 48, md5_default);
    v3_default2 = v3;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
var import_crypto4, native_default;
var init_native = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
    import_crypto4 = __toESM(require("crypto"));
    native_default = {
      randomUUID: import_crypto4.default.randomUUID
    };
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
function v4(options, buf, offset) {
  if (native_default.randomUUID && !buf && !options) {
    return native_default.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (let i4 = 0; i4 < 16; ++i4) {
      buf[offset + i4] = rnds[i4];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var v4_default;
var init_v4 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js"() {
    init_native();
    init_rng();
    init_stringify();
    v4_default = v4;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js
function sha1(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return import_crypto5.default.createHash("sha1").update(bytes).digest();
}
var import_crypto5, sha1_default;
var init_sha1 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js"() {
    import_crypto5 = __toESM(require("crypto"));
    sha1_default = sha1;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js
var v5, v5_default;
var init_v5 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js"() {
    init_v35();
    init_sha1();
    v5 = v35("v5", 80, sha1_default);
    v5_default = v5;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js
var nil_default;
var init_nil = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js"() {
    nil_default = "00000000-0000-0000-0000-000000000000";
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js
function version(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  return parseInt(uuid.slice(14, 15), 16);
}
var version_default;
var init_version = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js"() {
    init_validate();
    version_default = version;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
var esm_node_exports = {};
__export(esm_node_exports, {
  NIL: () => nil_default,
  parse: () => parse_default,
  stringify: () => stringify_default,
  v1: () => v1_default,
  v3: () => v3_default2,
  v4: () => v4_default,
  v5: () => v5_default,
  validate: () => validate_default,
  version: () => version_default
});
var init_esm_node = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
    init_v1();
    init_v32();
    init_v4();
    init_v5();
    init_nil();
    init_version();
    init_validate();
    init_stringify();
    init_parse();
  }
});

// ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-cjs/index.js
var require_dist_cjs33 = __commonJS({
  "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      isBrowserNetworkError: () => isBrowserNetworkError,
      isClockSkewCorrectedError: () => isClockSkewCorrectedError,
      isClockSkewError: () => isClockSkewError,
      isRetryableByTrait: () => isRetryableByTrait,
      isServerError: () => isServerError,
      isThrottlingError: () => isThrottlingError,
      isTransientError: () => isTransientError
    });
    module2.exports = __toCommonJS2(src_exports);
    var CLOCK_SKEW_ERROR_CODES = [
      "AuthFailure",
      "InvalidSignatureException",
      "RequestExpired",
      "RequestInTheFuture",
      "RequestTimeTooSkewed",
      "SignatureDoesNotMatch"
    ];
    var THROTTLING_ERROR_CODES = [
      "BandwidthLimitExceeded",
      "EC2ThrottledException",
      "LimitExceededException",
      "PriorRequestNotComplete",
      "ProvisionedThroughputExceededException",
      "RequestLimitExceeded",
      "RequestThrottled",
      "RequestThrottledException",
      "SlowDown",
      "ThrottledException",
      "Throttling",
      "ThrottlingException",
      "TooManyRequestsException",
      "TransactionInProgressException"
      // DynamoDB
    ];
    var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
    var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
    var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
    var isRetryableByTrait = /* @__PURE__ */ __name((error2) => error2.$retryable !== void 0, "isRetryableByTrait");
    var isClockSkewError = /* @__PURE__ */ __name((error2) => CLOCK_SKEW_ERROR_CODES.includes(error2.name), "isClockSkewError");
    var isClockSkewCorrectedError = /* @__PURE__ */ __name((error2) => {
      var _a2;
      return (_a2 = error2.$metadata) == null ? void 0 : _a2.clockSkewCorrected;
    }, "isClockSkewCorrectedError");
    var isBrowserNetworkError = /* @__PURE__ */ __name((error2) => {
      const errorMessages = /* @__PURE__ */ new Set([
        "Failed to fetch",
        // Chrome
        "NetworkError when attempting to fetch resource",
        // Firefox
        "The Internet connection appears to be offline",
        // Safari 16
        "Load failed",
        // Safari 17+
        "Network request failed"
        // `cross-fetch`
      ]);
      const isValid2 = error2 && error2 instanceof TypeError;
      if (!isValid2) {
        return false;
      }
      return errorMessages.has(error2.message);
    }, "isBrowserNetworkError");
    var isThrottlingError = /* @__PURE__ */ __name((error2) => {
      var _a2, _b;
      return ((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || ((_b = error2.$retryable) == null ? void 0 : _b.throttling) == true;
    }, "isThrottlingError");
    var isTransientError = /* @__PURE__ */ __name((error2, depth = 0) => {
      var _a2;
      return isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES.includes((error2 == null ? void 0 : error2.code) || "") || TRANSIENT_ERROR_STATUS_CODES.includes(((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) || 0) || isBrowserNetworkError(error2) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1);
    }, "isTransientError");
    var isServerError = /* @__PURE__ */ __name((error2) => {
      var _a2;
      if (((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) !== void 0) {
        const statusCode = error2.$metadata.httpStatusCode;
        if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
          return true;
        }
        return false;
      }
      return false;
    }, "isServerError");
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-cjs/index.js
var require_dist_cjs34 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
      ConfiguredRetryStrategy: () => ConfiguredRetryStrategy,
      DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
      DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE,
      DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE3,
      DefaultRateLimiter: () => DefaultRateLimiter,
      INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS,
      INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER,
      MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY,
      NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT,
      REQUEST_HEADER: () => REQUEST_HEADER,
      RETRY_COST: () => RETRY_COST,
      RETRY_MODES: () => RETRY_MODES,
      StandardRetryStrategy: () => StandardRetryStrategy,
      THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE,
      TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST
    });
    module2.exports = __toCommonJS2(src_exports);
    var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => {
      RETRY_MODES2["STANDARD"] = "standard";
      RETRY_MODES2["ADAPTIVE"] = "adaptive";
      return RETRY_MODES2;
    })(RETRY_MODES || {});
    var DEFAULT_MAX_ATTEMPTS = 3;
    var DEFAULT_RETRY_MODE3 = "standard";
    var import_service_error_classification = require_dist_cjs33();
    var _a2;
    var DefaultRateLimiter = (_a2 = class {
      constructor(options) {
        this.currentCapacity = 0;
        this.enabled = false;
        this.lastMaxRate = 0;
        this.measuredTxRate = 0;
        this.requestCount = 0;
        this.lastTimestamp = 0;
        this.timeWindow = 0;
        this.beta = (options == null ? void 0 : options.beta) ?? 0.7;
        this.minCapacity = (options == null ? void 0 : options.minCapacity) ?? 1;
        this.minFillRate = (options == null ? void 0 : options.minFillRate) ?? 0.5;
        this.scaleConstant = (options == null ? void 0 : options.scaleConstant) ?? 0.4;
        this.smooth = (options == null ? void 0 : options.smooth) ?? 0.8;
        const currentTimeInSeconds = this.getCurrentTimeInSeconds();
        this.lastThrottleTime = currentTimeInSeconds;
        this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
        this.fillRate = this.minFillRate;
        this.maxCapacity = this.minCapacity;
      }
      getCurrentTimeInSeconds() {
        return Date.now() / 1e3;
      }
      async getSendToken() {
        return this.acquireTokenBucket(1);
      }
      async acquireTokenBucket(amount) {
        if (!this.enabled) {
          return;
        }
        this.refillTokenBucket();
        if (amount > this.currentCapacity) {
          const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
          await new Promise((resolve2) => _a2.setTimeoutFn(resolve2, delay));
        }
        this.currentCapacity = this.currentCapacity - amount;
      }
      refillTokenBucket() {
        const timestamp = this.getCurrentTimeInSeconds();
        if (!this.lastTimestamp) {
          this.lastTimestamp = timestamp;
          return;
        }
        const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
        this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
        this.lastTimestamp = timestamp;
      }
      updateClientSendingRate(response) {
        let calculatedRate;
        this.updateMeasuredRate();
        if ((0, import_service_error_classification.isThrottlingError)(response)) {
          const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
          this.lastMaxRate = rateToUse;
          this.calculateTimeWindow();
          this.lastThrottleTime = this.getCurrentTimeInSeconds();
          calculatedRate = this.cubicThrottle(rateToUse);
          this.enableTokenBucket();
        } else {
          this.calculateTimeWindow();
          calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
        }
        const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
        this.updateTokenBucketRate(newRate);
      }
      calculateTimeWindow() {
        this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
      }
      cubicThrottle(rateToUse) {
        return this.getPrecise(rateToUse * this.beta);
      }
      cubicSuccess(timestamp) {
        return this.getPrecise(
          this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate
        );
      }
      enableTokenBucket() {
        this.enabled = true;
      }
      updateTokenBucketRate(newRate) {
        this.refillTokenBucket();
        this.fillRate = Math.max(newRate, this.minFillRate);
        this.maxCapacity = Math.max(newRate, this.minCapacity);
        this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
      }
      updateMeasuredRate() {
        const t4 = this.getCurrentTimeInSeconds();
        const timeBucket = Math.floor(t4 * 2) / 2;
        this.requestCount++;
        if (timeBucket > this.lastTxRateBucket) {
          const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
          this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
          this.requestCount = 0;
          this.lastTxRateBucket = timeBucket;
        }
      }
      getPrecise(num) {
        return parseFloat(num.toFixed(8));
      }
    }, __name(_a2, "DefaultRateLimiter"), _a2.setTimeoutFn = setTimeout, _a2);
    var DEFAULT_RETRY_DELAY_BASE = 100;
    var MAXIMUM_RETRY_DELAY = 20 * 1e3;
    var THROTTLING_RETRY_DELAY_BASE = 500;
    var INITIAL_RETRY_TOKENS = 500;
    var RETRY_COST = 5;
    var TIMEOUT_RETRY_COST = 10;
    var NO_RETRY_INCREMENT = 1;
    var INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
    var REQUEST_HEADER = "amz-sdk-request";
    var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => {
      let delayBase = DEFAULT_RETRY_DELAY_BASE;
      const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => {
        return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
      }, "computeNextBackoffDelay");
      const setDelayBase = /* @__PURE__ */ __name((delay) => {
        delayBase = delay;
      }, "setDelayBase");
      return {
        computeNextBackoffDelay,
        setDelayBase
      };
    }, "getDefaultRetryBackoffStrategy");
    var createDefaultRetryToken = /* @__PURE__ */ __name(({
      retryDelay,
      retryCount,
      retryCost
    }) => {
      const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount");
      const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay");
      const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost");
      return {
        getRetryCount,
        getRetryDelay,
        getRetryCost
      };
    }, "createDefaultRetryToken");
    var _a3;
    var StandardRetryStrategy = (_a3 = class {
      constructor(maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.mode = "standard";
        this.capacity = INITIAL_RETRY_TOKENS;
        this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
        this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      async acquireInitialRetryToken(retryTokenScope) {
        return createDefaultRetryToken({
          retryDelay: DEFAULT_RETRY_DELAY_BASE,
          retryCount: 0
        });
      }
      async refreshRetryTokenForRetry(token, errorInfo) {
        const maxAttempts = await this.getMaxAttempts();
        if (this.shouldRetry(token, errorInfo, maxAttempts)) {
          const errorType = errorInfo.errorType;
          this.retryBackoffStrategy.setDelayBase(
            errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE
          );
          const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
          const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
          const capacityCost = this.getCapacityCost(errorType);
          this.capacity -= capacityCost;
          return createDefaultRetryToken({
            retryDelay,
            retryCount: token.getRetryCount() + 1,
            retryCost: capacityCost
          });
        }
        throw new Error("No retry token available");
      }
      recordSuccess(token) {
        this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
      }
      /**
       * @returns the current available retry capacity.
       *
       * This number decreases when retries are executed and refills when requests or retries succeed.
       */
      getCapacity() {
        return this.capacity;
      }
      async getMaxAttempts() {
        try {
          return await this.maxAttemptsProvider();
        } catch (error2) {
          console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
          return DEFAULT_MAX_ATTEMPTS;
        }
      }
      shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
        const attempts = tokenToRenew.getRetryCount() + 1;
        return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
      }
      getCapacityCost(errorType) {
        return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
      }
      isRetryableError(errorType) {
        return errorType === "THROTTLING" || errorType === "TRANSIENT";
      }
    }, __name(_a3, "StandardRetryStrategy"), _a3);
    var _a4;
    var AdaptiveRetryStrategy = (_a4 = class {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = "adaptive";
        const { rateLimiter } = options ?? {};
        this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
        this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
      }
      async acquireInitialRetryToken(retryTokenScope) {
        await this.rateLimiter.getSendToken();
        return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
      }
      async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
        this.rateLimiter.updateClientSendingRate(errorInfo);
        return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
      }
      recordSuccess(token) {
        this.rateLimiter.updateClientSendingRate({});
        this.standardRetryStrategy.recordSuccess(token);
      }
    }, __name(_a4, "AdaptiveRetryStrategy"), _a4);
    var _a5;
    var ConfiguredRetryStrategy = (_a5 = class extends StandardRetryStrategy {
      /**
       * @param maxAttempts - the maximum number of retry attempts allowed.
       *                      e.g., if set to 3, then 4 total requests are possible.
       * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt
       *                                  and returns the delay.
       *
       * @example exponential backoff.
       * ```js
       * new Client({
       *   retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2)
       * });
       * ```
       * @example constant delay.
       * ```js
       * new Client({
       *   retryStrategy: new ConfiguredRetryStrategy(3, 2000)
       * });
       * ```
       */
      constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) {
        super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts);
        if (typeof computeNextBackoffDelay === "number") {
          this.computeNextBackoffDelay = () => computeNextBackoffDelay;
        } else {
          this.computeNextBackoffDelay = computeNextBackoffDelay;
        }
      }
      async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
        const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
        token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount());
        return token;
      }
    }, __name(_a5, "ConfiguredRetryStrategy"), _a5);
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js
var require_isStreamingPayload = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isStreamingPayload = void 0;
    var stream_1 = require("stream");
    var isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream;
    exports2.isStreamingPayload = isStreamingPayload;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/index.js
var require_dist_cjs35 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
      CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS,
      CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE,
      ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS,
      ENV_RETRY_MODE: () => ENV_RETRY_MODE,
      NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS3,
      NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS3,
      StandardRetryStrategy: () => StandardRetryStrategy,
      defaultDelayDecider: () => defaultDelayDecider,
      defaultRetryDecider: () => defaultRetryDecider,
      getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin,
      getRetryAfterHint: () => getRetryAfterHint,
      getRetryPlugin: () => getRetryPlugin3,
      omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware,
      omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions,
      resolveRetryConfig: () => resolveRetryConfig3,
      retryMiddleware: () => retryMiddleware,
      retryMiddlewareOptions: () => retryMiddlewareOptions
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http15 = require_dist_cjs2();
    var import_uuid = (init_esm_node(), __toCommonJS(esm_node_exports));
    var import_util_retry3 = require_dist_cjs34();
    var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => {
      const MAX_CAPACITY = initialRetryTokens;
      const noRetryIncrement = (options == null ? void 0 : options.noRetryIncrement) ?? import_util_retry3.NO_RETRY_INCREMENT;
      const retryCost = (options == null ? void 0 : options.retryCost) ?? import_util_retry3.RETRY_COST;
      const timeoutRetryCost = (options == null ? void 0 : options.timeoutRetryCost) ?? import_util_retry3.TIMEOUT_RETRY_COST;
      let availableCapacity = initialRetryTokens;
      const getCapacityAmount = /* @__PURE__ */ __name((error2) => error2.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount");
      const hasRetryTokens = /* @__PURE__ */ __name((error2) => getCapacityAmount(error2) <= availableCapacity, "hasRetryTokens");
      const retrieveRetryTokens = /* @__PURE__ */ __name((error2) => {
        if (!hasRetryTokens(error2)) {
          throw new Error("No retry token available");
        }
        const capacityAmount = getCapacityAmount(error2);
        availableCapacity -= capacityAmount;
        return capacityAmount;
      }, "retrieveRetryTokens");
      const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => {
        availableCapacity += capacityReleaseAmount ?? noRetryIncrement;
        availableCapacity = Math.min(availableCapacity, MAX_CAPACITY);
      }, "releaseRetryTokens");
      return Object.freeze({
        hasRetryTokens,
        retrieveRetryTokens,
        releaseRetryTokens
      });
    }, "getDefaultRetryQuota");
    var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry3.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider");
    var import_service_error_classification = require_dist_cjs33();
    var defaultRetryDecider = /* @__PURE__ */ __name((error2) => {
      if (!error2) {
        return false;
      }
      return (0, import_service_error_classification.isRetryableByTrait)(error2) || (0, import_service_error_classification.isClockSkewError)(error2) || (0, import_service_error_classification.isThrottlingError)(error2) || (0, import_service_error_classification.isTransientError)(error2);
    }, "defaultRetryDecider");
    var asSdkError = /* @__PURE__ */ __name((error2) => {
      if (error2 instanceof Error)
        return error2;
      if (error2 instanceof Object)
        return Object.assign(new Error(), error2);
      if (typeof error2 === "string")
        return new Error(error2);
      return new Error(`AWS SDK error wrapper for ${error2}`);
    }, "asSdkError");
    var _a2;
    var StandardRetryStrategy = (_a2 = class {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = import_util_retry3.RETRY_MODES.STANDARD;
        this.retryDecider = (options == null ? void 0 : options.retryDecider) ?? defaultRetryDecider;
        this.delayDecider = (options == null ? void 0 : options.delayDecider) ?? defaultDelayDecider;
        this.retryQuota = (options == null ? void 0 : options.retryQuota) ?? getDefaultRetryQuota(import_util_retry3.INITIAL_RETRY_TOKENS);
      }
      shouldRetry(error2, attempts, maxAttempts) {
        return attempts < maxAttempts && this.retryDecider(error2) && this.retryQuota.hasRetryTokens(error2);
      }
      async getMaxAttempts() {
        let maxAttempts;
        try {
          maxAttempts = await this.maxAttemptsProvider();
        } catch (error2) {
          maxAttempts = import_util_retry3.DEFAULT_MAX_ATTEMPTS;
        }
        return maxAttempts;
      }
      async retry(next, args, options) {
        let retryTokenAmount;
        let attempts = 0;
        let totalDelay = 0;
        const maxAttempts = await this.getMaxAttempts();
        const { request } = args;
        if (import_protocol_http15.HttpRequest.isInstance(request)) {
          request.headers[import_util_retry3.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
        }
        while (true) {
          try {
            if (import_protocol_http15.HttpRequest.isInstance(request)) {
              request.headers[import_util_retry3.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
            }
            if (options == null ? void 0 : options.beforeRequest) {
              await options.beforeRequest();
            }
            const { response, output } = await next(args);
            if (options == null ? void 0 : options.afterRequest) {
              options.afterRequest(response);
            }
            this.retryQuota.releaseRetryTokens(retryTokenAmount);
            output.$metadata.attempts = attempts + 1;
            output.$metadata.totalRetryDelay = totalDelay;
            return { response, output };
          } catch (e4) {
            const err2 = asSdkError(e4);
            attempts++;
            if (this.shouldRetry(err2, attempts, maxAttempts)) {
              retryTokenAmount = this.retryQuota.retrieveRetryTokens(err2);
              const delayFromDecider = this.delayDecider(
                (0, import_service_error_classification.isThrottlingError)(err2) ? import_util_retry3.THROTTLING_RETRY_DELAY_BASE : import_util_retry3.DEFAULT_RETRY_DELAY_BASE,
                attempts
              );
              const delayFromResponse = getDelayFromRetryAfterHeader(err2.$response);
              const delay = Math.max(delayFromResponse || 0, delayFromDecider);
              totalDelay += delay;
              await new Promise((resolve2) => setTimeout(resolve2, delay));
              continue;
            }
            if (!err2.$metadata) {
              err2.$metadata = {};
            }
            err2.$metadata.attempts = attempts;
            err2.$metadata.totalRetryDelay = totalDelay;
            throw err2;
          }
        }
      }
    }, __name(_a2, "StandardRetryStrategy"), _a2);
    var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => {
      if (!import_protocol_http15.HttpResponse.isInstance(response))
        return;
      const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
      if (!retryAfterHeaderName)
        return;
      const retryAfter = response.headers[retryAfterHeaderName];
      const retryAfterSeconds = Number(retryAfter);
      if (!Number.isNaN(retryAfterSeconds))
        return retryAfterSeconds * 1e3;
      const retryAfterDate = new Date(retryAfter);
      return retryAfterDate.getTime() - Date.now();
    }, "getDelayFromRetryAfterHeader");
    var _a3;
    var AdaptiveRetryStrategy = (_a3 = class extends StandardRetryStrategy {
      constructor(maxAttemptsProvider, options) {
        const { rateLimiter, ...superOptions } = options ?? {};
        super(maxAttemptsProvider, superOptions);
        this.rateLimiter = rateLimiter ?? new import_util_retry3.DefaultRateLimiter();
        this.mode = import_util_retry3.RETRY_MODES.ADAPTIVE;
      }
      async retry(next, args) {
        return super.retry(next, args, {
          beforeRequest: async () => {
            return this.rateLimiter.getSendToken();
          },
          afterRequest: (response) => {
            this.rateLimiter.updateClientSendingRate(response);
          }
        });
      }
    }, __name(_a3, "AdaptiveRetryStrategy"), _a3);
    var import_util_middleware7 = require_dist_cjs6();
    var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
    var CONFIG_MAX_ATTEMPTS = "max_attempts";
    var NODE_MAX_ATTEMPT_CONFIG_OPTIONS3 = {
      environmentVariableSelector: (env3) => {
        const value = env3[ENV_MAX_ATTEMPTS];
        if (!value)
          return void 0;
        const maxAttempt = parseInt(value);
        if (Number.isNaN(maxAttempt)) {
          throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
        }
        return maxAttempt;
      },
      configFileSelector: (profile) => {
        const value = profile[CONFIG_MAX_ATTEMPTS];
        if (!value)
          return void 0;
        const maxAttempt = parseInt(value);
        if (Number.isNaN(maxAttempt)) {
          throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
        }
        return maxAttempt;
      },
      default: import_util_retry3.DEFAULT_MAX_ATTEMPTS
    };
    var resolveRetryConfig3 = /* @__PURE__ */ __name((input) => {
      const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;
      const maxAttempts = (0, import_util_middleware7.normalizeProvider)(_maxAttempts ?? import_util_retry3.DEFAULT_MAX_ATTEMPTS);
      return Object.assign(input, {
        maxAttempts,
        retryStrategy: async () => {
          if (retryStrategy) {
            return retryStrategy;
          }
          const retryMode = await (0, import_util_middleware7.normalizeProvider)(_retryMode)();
          if (retryMode === import_util_retry3.RETRY_MODES.ADAPTIVE) {
            return new import_util_retry3.AdaptiveRetryStrategy(maxAttempts);
          }
          return new import_util_retry3.StandardRetryStrategy(maxAttempts);
        }
      });
    }, "resolveRetryConfig");
    var ENV_RETRY_MODE = "AWS_RETRY_MODE";
    var CONFIG_RETRY_MODE = "retry_mode";
    var NODE_RETRY_MODE_CONFIG_OPTIONS3 = {
      environmentVariableSelector: (env3) => env3[ENV_RETRY_MODE],
      configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
      default: import_util_retry3.DEFAULT_RETRY_MODE
    };
    var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => {
      const { request } = args;
      if (import_protocol_http15.HttpRequest.isInstance(request)) {
        delete request.headers[import_util_retry3.INVOCATION_ID_HEADER];
        delete request.headers[import_util_retry3.REQUEST_HEADER];
      }
      return next(args);
    }, "omitRetryHeadersMiddleware");
    var omitRetryHeadersMiddlewareOptions = {
      name: "omitRetryHeadersMiddleware",
      tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"],
      relation: "before",
      toMiddleware: "awsAuthMiddleware",
      override: true
    };
    var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);
      }
    }), "getOmitRetryHeadersPlugin");
    var import_smithy_client25 = require_dist_cjs23();
    var import_isStreamingPayload = require_isStreamingPayload();
    var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
      var _a4;
      let retryStrategy = await options.retryStrategy();
      const maxAttempts = await options.maxAttempts();
      if (isRetryStrategyV2(retryStrategy)) {
        retryStrategy = retryStrategy;
        let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
        let lastError = new Error();
        let attempts = 0;
        let totalRetryDelay = 0;
        const { request } = args;
        const isRequest2 = import_protocol_http15.HttpRequest.isInstance(request);
        if (isRequest2) {
          request.headers[import_util_retry3.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
        }
        while (true) {
          try {
            if (isRequest2) {
              request.headers[import_util_retry3.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
            }
            const { response, output } = await next(args);
            retryStrategy.recordSuccess(retryToken);
            output.$metadata.attempts = attempts + 1;
            output.$metadata.totalRetryDelay = totalRetryDelay;
            return { response, output };
          } catch (e4) {
            const retryErrorInfo = getRetryErrorInfo(e4);
            lastError = asSdkError(e4);
            if (isRequest2 && (0, import_isStreamingPayload.isStreamingPayload)(request)) {
              (_a4 = context.logger instanceof import_smithy_client25.NoOpLogger ? console : context.logger) == null ? void 0 : _a4.warn(
                "An error was encountered in a non-retryable streaming request."
              );
              throw lastError;
            }
            try {
              retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
            } catch (refreshError) {
              if (!lastError.$metadata) {
                lastError.$metadata = {};
              }
              lastError.$metadata.attempts = attempts + 1;
              lastError.$metadata.totalRetryDelay = totalRetryDelay;
              throw lastError;
            }
            attempts = retryToken.getRetryCount();
            const delay = retryToken.getRetryDelay();
            totalRetryDelay += delay;
            await new Promise((resolve2) => setTimeout(resolve2, delay));
          }
        }
      } else {
        retryStrategy = retryStrategy;
        if (retryStrategy == null ? void 0 : retryStrategy.mode)
          context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
        return retryStrategy.retry(next, args);
      }
    }, "retryMiddleware");
    var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2");
    var getRetryErrorInfo = /* @__PURE__ */ __name((error2) => {
      const errorInfo = {
        error: error2,
        errorType: getRetryErrorType(error2)
      };
      const retryAfterHint = getRetryAfterHint(error2.$response);
      if (retryAfterHint) {
        errorInfo.retryAfterHint = retryAfterHint;
      }
      return errorInfo;
    }, "getRetryErrorInfo");
    var getRetryErrorType = /* @__PURE__ */ __name((error2) => {
      if ((0, import_service_error_classification.isThrottlingError)(error2))
        return "THROTTLING";
      if ((0, import_service_error_classification.isTransientError)(error2))
        return "TRANSIENT";
      if ((0, import_service_error_classification.isServerError)(error2))
        return "SERVER_ERROR";
      return "CLIENT_ERROR";
    }, "getRetryErrorType");
    var retryMiddlewareOptions = {
      name: "retryMiddleware",
      tags: ["RETRY"],
      step: "finalizeRequest",
      priority: "high",
      override: true
    };
    var getRetryPlugin3 = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
      }
    }), "getRetryPlugin");
    var getRetryAfterHint = /* @__PURE__ */ __name((response) => {
      if (!import_protocol_http15.HttpResponse.isInstance(response))
        return;
      const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
      if (!retryAfterHeaderName)
        return;
      const retryAfter = response.headers[retryAfterHeaderName];
      const retryAfterSeconds = Number(retryAfter);
      if (!Number.isNaN(retryAfterSeconds))
        return new Date(retryAfterSeconds * 1e3);
      const retryAfterDate = new Date(retryAfter);
      return retryAfterDate;
    }, "getRetryAfterHint");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultRDSDataHttpAuthSchemeProvider = exports2.defaultRDSDataHttpAuthSchemeParametersProvider = void 0;
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var util_middleware_1 = require_dist_cjs6();
    var defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultRDSDataHttpAuthSchemeParametersProvider = defaultRDSDataHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption3(authParameters) {
      return {
        schemeId: "aws.auth#sigv4",
        signingProperties: {
          name: "rds-data",
          region: authParameters.region
        },
        propertiesExtractor: (config, context) => ({
          signingProperties: {
            config,
            context
          }
        })
      };
    }
    var defaultRDSDataHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
        }
      }
      return options;
    };
    exports2.defaultRDSDataHttpAuthSchemeProvider = defaultRDSDataHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig3 = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return Object.assign(config_0, {
        authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? [])
      });
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig3;
  }
});

// ../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports = {};
__export(tslib_es6_exports, {
  __addDisposableResource: () => __addDisposableResource,
  __assign: () => __assign,
  __asyncDelegator: () => __asyncDelegator,
  __asyncGenerator: () => __asyncGenerator,
  __asyncValues: () => __asyncValues,
  __await: () => __await,
  __awaiter: () => __awaiter,
  __classPrivateFieldGet: () => __classPrivateFieldGet,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values,
  default: () => tslib_es6_default
});
function __extends(d3, b3) {
  if (typeof b3 !== "function" && b3 !== null)
    throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
  extendStatics(d3, b3);
  function __() {
    this.constructor = d3;
  }
  d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
}
function __rest(s4, e4) {
  var t4 = {};
  for (var p3 in s4) if (Object.prototype.hasOwnProperty.call(s4, p3) && e4.indexOf(p3) < 0)
    t4[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s4); i4 < p3.length; i4++) {
      if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i4]))
        t4[p3[i4]] = s4[p3[i4]];
    }
  return t4;
}
function __decorate(decorators, target, key, desc) {
  var c3 = arguments.length, r4 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r4 = Reflect.decorate(decorators, target, key, desc);
  else for (var i4 = decorators.length - 1; i4 >= 0; i4--) if (d3 = decorators[i4]) r4 = (c3 < 3 ? d3(r4) : c3 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  return c3 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f5) {
    if (f5 !== void 0 && typeof f5 !== "function") throw new TypeError("Function expected");
    return f5;
  }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _3, done = false;
  for (var i4 = decorators.length - 1; i4 >= 0; i4--) {
    var context = {};
    for (var p3 in contextIn) context[p3] = p3 === "access" ? {} : contextIn[p3];
    for (var p3 in contextIn.access) context.access[p3] = contextIn.access[p3];
    context.addInitializer = function(f5) {
      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f5 || null));
    };
    var result = (0, decorators[i4])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0) continue;
      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
      if (_3 = accept(result.get)) descriptor.get = _3;
      if (_3 = accept(result.set)) descriptor.set = _3;
      if (_3 = accept(result.init)) initializers.unshift(_3);
    } else if (_3 = accept(result)) {
      if (kind === "field") initializers.unshift(_3);
      else descriptor[key] = _3;
    }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i4 = 0; i4 < initializers.length; i4++) {
    value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x4) {
  return typeof x4 === "symbol" ? x4 : "".concat(x4);
}
function __setFunctionName(f5, name, prefix2) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f5, "name", { configurable: true, value: prefix2 ? "".concat(prefix2, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _3 = { label: 0, sent: function() {
    if (t4[0] & 1) throw t4[1];
    return t4[1];
  }, trys: [], ops: [] }, f5, y2, t4, g3 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g3.next = verb(0), g3["throw"] = verb(1), g3["return"] = verb(2), typeof Symbol === "function" && (g3[Symbol.iterator] = function() {
    return this;
  }), g3;
  function verb(n3) {
    return function(v6) {
      return step([n3, v6]);
    };
  }
  function step(op) {
    if (f5) throw new TypeError("Generator is already executing.");
    while (g3 && (g3 = 0, op[0] && (_3 = 0)), _3) try {
      if (f5 = 1, y2 && (t4 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t4 = y2["return"]) && t4.call(y2), 0) : y2.next) && !(t4 = t4.call(y2, op[1])).done) return t4;
      if (y2 = 0, t4) op = [op[0] & 2, t4.value];
      switch (op[0]) {
        case 0:
        case 1:
          t4 = op;
          break;
        case 4:
          _3.label++;
          return { value: op[1], done: false };
        case 5:
          _3.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _3.ops.pop();
          _3.trys.pop();
          continue;
        default:
          if (!(t4 = _3.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _3 = 0;
            continue;
          }
          if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
            _3.label = op[1];
            break;
          }
          if (op[0] === 6 && _3.label < t4[1]) {
            _3.label = t4[1];
            t4 = op;
            break;
          }
          if (t4 && _3.label < t4[2]) {
            _3.label = t4[2];
            _3.ops.push(op);
            break;
          }
          if (t4[2]) _3.ops.pop();
          _3.trys.pop();
          continue;
      }
      op = body.call(thisArg, _3);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f5 = t4 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar(m4, o3) {
  for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3)) __createBinding(o3, m4, p3);
}
function __values(o3) {
  var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o3[s4], i4 = 0;
  if (m4) return m4.call(o3);
  if (o3 && typeof o3.length === "number") return {
    next: function() {
      if (o3 && i4 >= o3.length) o3 = void 0;
      return { value: o3 && o3[i4++], done: !o3 };
    }
  };
  throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o3, n3) {
  var m4 = typeof Symbol === "function" && o3[Symbol.iterator];
  if (!m4) return o3;
  var i4 = m4.call(o3), r4, ar = [], e4;
  try {
    while ((n3 === void 0 || n3-- > 0) && !(r4 = i4.next()).done) ar.push(r4.value);
  } catch (error2) {
    e4 = { error: error2 };
  } finally {
    try {
      if (r4 && !r4.done && (m4 = i4["return"])) m4.call(i4);
    } finally {
      if (e4) throw e4.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
    ar = ar.concat(__read(arguments[i4]));
  return ar;
}
function __spreadArrays() {
  for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) s4 += arguments[i4].length;
  for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
    for (var a3 = arguments[i4], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
      r4[k3] = a3[j3];
  return r4;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) {
    if (ar || !(i4 in from)) {
      if (!ar) ar = Array.prototype.slice.call(from, 0, i4);
      ar[i4] = from[i4];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v6) {
  return this instanceof __await ? (this.v = v6, this) : new __await(v6);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g3 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
  return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
    return this;
  }, i4;
  function awaitReturn(f5) {
    return function(v6) {
      return Promise.resolve(v6).then(f5, reject);
    };
  }
  function verb(n3, f5) {
    if (g3[n3]) {
      i4[n3] = function(v6) {
        return new Promise(function(a3, b3) {
          q3.push([n3, v6, a3, b3]) > 1 || resume(n3, v6);
        });
      };
      if (f5) i4[n3] = f5(i4[n3]);
    }
  }
  function resume(n3, v6) {
    try {
      step(g3[n3](v6));
    } catch (e4) {
      settle(q3[0][3], e4);
    }
  }
  function step(r4) {
    r4.value instanceof __await ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f5, v6) {
    if (f5(v6), q3.shift(), q3.length) resume(q3[0][0], q3[0][1]);
  }
}
function __asyncDelegator(o3) {
  var i4, p3;
  return i4 = {}, verb("next"), verb("throw", function(e4) {
    throw e4;
  }), verb("return"), i4[Symbol.iterator] = function() {
    return this;
  }, i4;
  function verb(n3, f5) {
    i4[n3] = o3[n3] ? function(v6) {
      return (p3 = !p3) ? { value: __await(o3[n3](v6)), done: false } : f5 ? f5(v6) : v6;
    } : f5;
  }
}
function __asyncValues(o3) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m4 = o3[Symbol.asyncIterator], i4;
  return m4 ? m4.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
    return this;
  }, i4);
  function verb(n3) {
    i4[n3] = o3[n3] && function(v6) {
      return new Promise(function(resolve2, reject) {
        v6 = o3[n3](v6), settle(resolve2, reject, v6.done, v6.value);
      });
    };
  }
  function settle(resolve2, reject, d3, v6) {
    Promise.resolve(v6).then(function(v7) {
      resolve2({ value: v7, done: d3 });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw2) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw2 });
  } else {
    cooked.raw = raw2;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) {
    for (var k3 = ownKeys(mod), i4 = 0; i4 < k3.length; i4++) if (k3[i4] !== "default") __createBinding(result, mod, k3[i4]);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state2, kind, f5) {
  if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f5 : kind === "a" ? f5.call(receiver) : f5 ? f5.value : state2.get(receiver);
}
function __classPrivateFieldSet(receiver, state2, value, kind, f5) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state2.set(receiver, value), value;
}
function __classPrivateFieldIn(state2, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state2 === "function" ? receiver === state2 : state2.has(receiver);
}
function __addDisposableResource(env3, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e4) {
        return Promise.reject(e4);
      }
    };
    env3.stack.push({ value, dispose, async });
  } else if (async) {
    env3.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env3) {
  function fail(e4) {
    env3.error = env3.hasError ? new _SuppressedError(e4, env3.error, "An error was suppressed during disposal.") : e4;
    env3.hasError = true;
  }
  var r4, s4 = 0;
  function next() {
    while (r4 = env3.stack.pop()) {
      try {
        if (!r4.async && s4 === 1) return s4 = 0, env3.stack.push(r4), Promise.resolve().then(next);
        if (r4.dispose) {
          var result = r4.dispose.call(r4.value);
          if (r4.async) return s4 |= 2, Promise.resolve(result).then(next, function(e4) {
            fail(e4);
            return next();
          });
        } else s4 |= 1;
      } catch (e4) {
        fail(e4);
      }
    }
    if (s4 === 1) return env3.hasError ? Promise.reject(env3.error) : Promise.resolve();
    if (env3.hasError) throw env3.error;
  }
  return next();
}
function __rewriteRelativeImportExtension(path4, preserveJsx) {
  if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
    return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m4, tsx, d3, ext2, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d3 && (!ext2 || !cm) ? m4 : d3 + ext2 + "." + cm.toLowerCase() + "js";
    });
  }
  return path4;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics = function(d3, b3) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
        d4.__proto__ = b4;
      } || function(d4, b4) {
        for (var p3 in b4) if (Object.prototype.hasOwnProperty.call(b4, p3)) d4[p3] = b4[p3];
      };
      return extendStatics(d3, b3);
    };
    __assign = function() {
      __assign = Object.assign || function __assign2(t4) {
        for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) {
          s4 = arguments[i4];
          for (var p3 in s4) if (Object.prototype.hasOwnProperty.call(s4, p3)) t4[p3] = s4[p3];
        }
        return t4;
      };
      return __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    };
    __setModuleDefault = Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    };
    ownKeys = function(o3) {
      ownKeys = Object.getOwnPropertyNames || function(o4) {
        var ar = [];
        for (var k3 in o4) if (Object.prototype.hasOwnProperty.call(o4, k3)) ar[ar.length] = k3;
        return ar;
      };
      return ownKeys(o3);
    };
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
      var e4 = new Error(message);
      return e4.name = "SuppressedError", e4.error = error2, e4.suppressed = suppressed, e4;
    };
    tslib_es6_default = {
      __extends,
      __assign,
      __rest,
      __decorate,
      __param,
      __esDecorate,
      __runInitializers,
      __propKey,
      __setFunctionName,
      __metadata,
      __awaiter,
      __generator,
      __createBinding,
      __exportStar,
      __values,
      __read,
      __spread,
      __spreadArrays,
      __spreadArray,
      __await,
      __asyncGenerator,
      __asyncDelegator,
      __asyncValues,
      __makeTemplateObject,
      __importStar,
      __importDefault,
      __classPrivateFieldGet,
      __classPrivateFieldSet,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources,
      __rewriteRelativeImportExtension
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json
var require_package2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-rds-data",
      description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native",
      version: "3.817.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-rds-data",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo rds-data"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/credential-provider-node": "3.817.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node18": "18.2.4",
        "@types/node": "^18.19.69",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      engines: {
        node: ">=18.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-rds-data",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-rds-data"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js
var require_dist_cjs36 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID,
      ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
      ENV_EXPIRATION: () => ENV_EXPIRATION,
      ENV_KEY: () => ENV_KEY,
      ENV_SECRET: () => ENV_SECRET,
      ENV_SESSION: () => ENV_SESSION,
      fromEnv: () => fromEnv
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_client3 = (init_client(), __toCommonJS(client_exports));
    var import_property_provider2 = require_dist_cjs20();
    var ENV_KEY = "AWS_ACCESS_KEY_ID";
    var ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
    var ENV_SESSION = "AWS_SESSION_TOKEN";
    var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
    var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
    var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID";
    var fromEnv = /* @__PURE__ */ __name((init2) => async () => {
      var _a2;
      (_a2 = init2 == null ? void 0 : init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-env - fromEnv");
      const accessKeyId = process.env[ENV_KEY];
      const secretAccessKey = process.env[ENV_SECRET];
      const sessionToken = process.env[ENV_SESSION];
      const expiry = process.env[ENV_EXPIRATION];
      const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
      const accountId = process.env[ENV_ACCOUNT_ID];
      if (accessKeyId && secretAccessKey) {
        const credentials2 = {
          accessKeyId,
          secretAccessKey,
          ...sessionToken && { sessionToken },
          ...expiry && { expiration: new Date(expiry) },
          ...credentialScope && { credentialScope },
          ...accountId && { accountId }
        };
        (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_ENV_VARS", "g");
        return credentials2;
      }
      throw new import_property_provider2.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2 == null ? void 0 : init2.logger });
    }, "fromEnv");
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js
var require_dist_cjs37 = __commonJS({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
      DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
      ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
      ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
      ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
      Endpoint: () => Endpoint,
      fromContainerMetadata: () => fromContainerMetadata,
      fromInstanceMetadata: () => fromInstanceMetadata,
      getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
      httpRequest: () => httpRequest,
      providerConfigFromInit: () => providerConfigFromInit
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_url8 = require("url");
    var import_property_provider2 = require_dist_cjs20();
    var import_buffer2 = require("buffer");
    var import_http3 = require("http");
    function httpRequest(options) {
      return new Promise((resolve2, reject) => {
        var _a3;
        const req = (0, import_http3.request)({
          method: "GET",
          ...options,
          // Node.js http module doesn't accept hostname with square brackets
          // Refs: https://github.com/nodejs/node/issues/39738
          hostname: (_a3 = options.hostname) == null ? void 0 : _a3.replace(/^\[(.+)\]$/, "$1")
        });
        req.on("error", (err2) => {
          reject(Object.assign(new import_property_provider2.ProviderError("Unable to connect to instance metadata service"), err2));
          req.destroy();
        });
        req.on("timeout", () => {
          reject(new import_property_provider2.ProviderError("TimeoutError from instance metadata service"));
          req.destroy();
        });
        req.on("response", (res) => {
          const { statusCode = 400 } = res;
          if (statusCode < 200 || 300 <= statusCode) {
            reject(
              Object.assign(new import_property_provider2.ProviderError("Error response received from instance metadata service"), { statusCode })
            );
            req.destroy();
          }
          const chunks = [];
          res.on("data", (chunk) => {
            chunks.push(chunk);
          });
          res.on("end", () => {
            resolve2(import_buffer2.Buffer.concat(chunks));
            req.destroy();
          });
        });
        req.end();
      });
    }
    __name(httpRequest, "httpRequest");
    var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials");
    var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({
      accessKeyId: creds.AccessKeyId,
      secretAccessKey: creds.SecretAccessKey,
      sessionToken: creds.Token,
      expiration: new Date(creds.Expiration),
      ...creds.AccountId && { accountId: creds.AccountId }
    }), "fromImdsCredentials");
    var DEFAULT_TIMEOUT = 1e3;
    var DEFAULT_MAX_RETRIES = 0;
    var providerConfigFromInit = /* @__PURE__ */ __name(({
      maxRetries = DEFAULT_MAX_RETRIES,
      timeout = DEFAULT_TIMEOUT
    }) => ({ maxRetries, timeout }), "providerConfigFromInit");
    var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => {
      let promise = toRetry();
      for (let i4 = 0; i4 < maxRetries; i4++) {
        promise = promise.catch(toRetry);
      }
      return promise;
    }, "retry");
    var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    var fromContainerMetadata = /* @__PURE__ */ __name((init2 = {}) => {
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      return () => retry(async () => {
        const requestOptions = await getCmdsUri({ logger: init2.logger });
        const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
        if (!isImdsCredentials(credsResponse)) {
          throw new import_property_provider2.CredentialsProviderError("Invalid response received from instance metadata service.", {
            logger: init2.logger
          });
        }
        return fromImdsCredentials(credsResponse);
      }, maxRetries);
    }, "fromContainerMetadata");
    var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => {
      if (process.env[ENV_CMDS_AUTH_TOKEN]) {
        options.headers = {
          ...options.headers,
          Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
        };
      }
      const buffer = await httpRequest({
        ...options,
        timeout
      });
      return buffer.toString();
    }, "requestFromEcsImds");
    var CMDS_IP = "169.254.170.2";
    var GREENGRASS_HOSTS = {
      localhost: true,
      "127.0.0.1": true
    };
    var GREENGRASS_PROTOCOLS = {
      "http:": true,
      "https:": true
    };
    var getCmdsUri = /* @__PURE__ */ __name(async ({ logger: logger3 }) => {
      if (process.env[ENV_CMDS_RELATIVE_URI]) {
        return {
          hostname: CMDS_IP,
          path: process.env[ENV_CMDS_RELATIVE_URI]
        };
      }
      if (process.env[ENV_CMDS_FULL_URI]) {
        const parsed = (0, import_url8.parse)(process.env[ENV_CMDS_FULL_URI]);
        if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
          throw new import_property_provider2.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
            tryNextLink: false,
            logger: logger3
          });
        }
        if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
          throw new import_property_provider2.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
            tryNextLink: false,
            logger: logger3
          });
        }
        return {
          ...parsed,
          port: parsed.port ? parseInt(parsed.port, 10) : void 0
        };
      }
      throw new import_property_provider2.CredentialsProviderError(
        `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`,
        {
          tryNextLink: false,
          logger: logger3
        }
      );
    }, "getCmdsUri");
    var _a2;
    var InstanceMetadataV1FallbackError = (_a2 = class extends import_property_provider2.CredentialsProviderError {
      constructor(message, tryNextLink = true) {
        super(message, tryNextLink);
        this.tryNextLink = tryNextLink;
        this.name = "InstanceMetadataV1FallbackError";
        Object.setPrototypeOf(this, _a2.prototype);
      }
    }, __name(_a2, "InstanceMetadataV1FallbackError"), _a2);
    var import_node_config_provider3 = require_dist_cjs29();
    var import_url_parser3 = require_dist_cjs31();
    var Endpoint = /* @__PURE__ */ ((Endpoint2) => {
      Endpoint2["IPv4"] = "http://169.254.169.254";
      Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
      return Endpoint2;
    })(Endpoint || {});
    var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
    var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
    var ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
      default: void 0
    };
    var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => {
      EndpointMode2["IPv4"] = "IPv4";
      EndpointMode2["IPv6"] = "IPv6";
      return EndpointMode2;
    })(EndpointMode || {});
    var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
    var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
    var ENDPOINT_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_MODE_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
      default: "IPv4"
      /* IPv4 */
    };
    var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser3.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint");
    var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider3.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig");
    var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => {
      const endpointMode = await (0, import_node_config_provider3.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)();
      switch (endpointMode) {
        case "IPv4":
          return "http://169.254.169.254";
        case "IPv6":
          return "http://[fd00:ec2::254]";
        default:
          throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
      }
    }, "getFromEndpointModeConfig");
    var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
    var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
    var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
    var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials2, logger3) => {
      const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
      const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
      logger3.warn(
        `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
For more information, please visit: ` + STATIC_STABILITY_DOC_URL
      );
      const originalExpiration = credentials2.originalExpiration ?? credentials2.expiration;
      return {
        ...credentials2,
        ...originalExpiration ? { originalExpiration } : {},
        expiration: newExpiration
      };
    }, "getExtendedInstanceMetadataCredentials");
    var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => {
      const logger3 = (options == null ? void 0 : options.logger) || console;
      let pastCredentials;
      return async () => {
        let credentials2;
        try {
          credentials2 = await provider();
          if (credentials2.expiration && credentials2.expiration.getTime() < Date.now()) {
            credentials2 = getExtendedInstanceMetadataCredentials(credentials2, logger3);
          }
        } catch (e4) {
          if (pastCredentials) {
            logger3.warn("Credential renew failed: ", e4);
            credentials2 = getExtendedInstanceMetadataCredentials(pastCredentials, logger3);
          } else {
            throw e4;
          }
        }
        pastCredentials = credentials2;
        return credentials2;
      };
    }, "staticStabilityProvider");
    var IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
    var IMDS_TOKEN_PATH = "/latest/api/token";
    var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
    var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
    var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
    var fromInstanceMetadata = /* @__PURE__ */ __name((init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger }), "fromInstanceMetadata");
    var getInstanceMetadataProvider = /* @__PURE__ */ __name((init2 = {}) => {
      let disableFetchToken = false;
      const { logger: logger3, profile } = init2;
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => {
        var _a3;
        const isImdsV1Fallback = disableFetchToken || ((_a3 = options.headers) == null ? void 0 : _a3[X_AWS_EC2_METADATA_TOKEN]) == null;
        if (isImdsV1Fallback) {
          let fallbackBlockedFromProfile = false;
          let fallbackBlockedFromProcessEnv = false;
          const configValue = await (0, import_node_config_provider3.loadConfig)(
            {
              environmentVariableSelector: (env3) => {
                const envValue = env3[AWS_EC2_METADATA_V1_DISABLED];
                fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
                if (envValue === void 0) {
                  throw new import_property_provider2.CredentialsProviderError(
                    `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`,
                    { logger: init2.logger }
                  );
                }
                return fallbackBlockedFromProcessEnv;
              },
              configFileSelector: (profile2) => {
                const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
                fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
                return fallbackBlockedFromProfile;
              },
              default: false
            },
            {
              profile
            }
          )();
          if (init2.ec2MetadataV1Disabled || configValue) {
            const causes = [];
            if (init2.ec2MetadataV1Disabled)
              causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
            if (fallbackBlockedFromProfile)
              causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
            if (fallbackBlockedFromProcessEnv)
              causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
            throw new InstanceMetadataV1FallbackError(
              `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(
                ", "
              )}].`
            );
          }
        }
        const imdsProfile = (await retry(async () => {
          let profile2;
          try {
            profile2 = await getProfile(options);
          } catch (err2) {
            if (err2.statusCode === 401) {
              disableFetchToken = false;
            }
            throw err2;
          }
          return profile2;
        }, maxRetries2)).trim();
        return retry(async () => {
          let creds;
          try {
            creds = await getCredentialsFromProfile(imdsProfile, options, init2);
          } catch (err2) {
            if (err2.statusCode === 401) {
              disableFetchToken = false;
            }
            throw err2;
          }
          return creds;
        }, maxRetries2);
      }, "getCredentials");
      return async () => {
        const endpoint = await getInstanceMetadataEndpoint();
        if (disableFetchToken) {
          logger3 == null ? void 0 : logger3.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
          return getCredentials(maxRetries, { ...endpoint, timeout });
        } else {
          let token;
          try {
            token = (await getMetadataToken({ ...endpoint, timeout })).toString();
          } catch (error2) {
            if ((error2 == null ? void 0 : error2.statusCode) === 400) {
              throw Object.assign(error2, {
                message: "EC2 Metadata token request returned error"
              });
            } else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
              disableFetchToken = true;
            }
            logger3 == null ? void 0 : logger3.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
            return getCredentials(maxRetries, { ...endpoint, timeout });
          }
          return getCredentials(maxRetries, {
            ...endpoint,
            headers: {
              [X_AWS_EC2_METADATA_TOKEN]: token
            },
            timeout
          });
        }
      };
    }, "getInstanceMetadataProvider");
    var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({
      ...options,
      path: IMDS_TOKEN_PATH,
      method: "PUT",
      headers: {
        "x-aws-ec2-metadata-token-ttl-seconds": "21600"
      }
    }), "getMetadataToken");
    var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile");
    var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init2) => {
      const credentialsResponse = JSON.parse(
        (await httpRequest({
          ...options,
          path: IMDS_PATH + profile
        })).toString()
      );
      if (!isImdsCredentials(credentialsResponse)) {
        throw new import_property_provider2.CredentialsProviderError("Invalid response received from instance metadata service.", {
          logger: init2.logger
        });
      }
      return fromImdsCredentials(credentialsResponse);
    }, "getCredentialsFromProfile");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js
var require_checkUrl = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkUrl = void 0;
    var property_provider_1 = require_dist_cjs20();
    var ECS_CONTAINER_HOST = "169.254.170.2";
    var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
    var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
    var checkUrl = (url, logger3) => {
      if (url.protocol === "https:") {
        return;
      }
      if (url.hostname === ECS_CONTAINER_HOST || url.hostname === EKS_CONTAINER_HOST_IPv4 || url.hostname === EKS_CONTAINER_HOST_IPv6) {
        return;
      }
      if (url.hostname.includes("[")) {
        if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
          return;
        }
      } else {
        if (url.hostname === "localhost") {
          return;
        }
        const ipComponents = url.hostname.split(".");
        const inRange = (component) => {
          const num = parseInt(component, 10);
          return 0 <= num && num <= 255;
        };
        if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
          return;
        }
      }
      throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
  - loopback CIDR 127.0.0.0/8 or [::1/128]
  - ECS container host 169.254.170.2
  - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger3 });
    };
    exports2.checkUrl = checkUrl;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js
var require_requestHelpers = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createGetRequest = createGetRequest;
    exports2.getCredentials = getCredentials;
    var property_provider_1 = require_dist_cjs20();
    var protocol_http_1 = require_dist_cjs2();
    var smithy_client_1 = require_dist_cjs23();
    var util_stream_1 = require_dist_cjs17();
    function createGetRequest(url) {
      return new protocol_http_1.HttpRequest({
        protocol: url.protocol,
        hostname: url.hostname,
        port: Number(url.port),
        path: url.pathname,
        query: Array.from(url.searchParams.entries()).reduce((acc, [k3, v6]) => {
          acc[k3] = v6;
          return acc;
        }, {}),
        fragment: url.hash
      });
    }
    async function getCredentials(response, logger3) {
      const stream = (0, util_stream_1.sdkStreamMixin)(response.body);
      const str = await stream.transformToString();
      if (response.statusCode === 200) {
        const parsed = JSON.parse(str);
        if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
          throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger3 });
        }
        return {
          accessKeyId: parsed.AccessKeyId,
          secretAccessKey: parsed.SecretAccessKey,
          sessionToken: parsed.Token,
          expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration)
        };
      }
      if (response.statusCode >= 400 && response.statusCode < 500) {
        let parsedBody = {};
        try {
          parsedBody = JSON.parse(str);
        } catch (e4) {
        }
        throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger3 }), {
          Code: parsedBody.Code,
          Message: parsedBody.Message
        });
      }
      throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger3 });
    }
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js
var require_retry_wrapper = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.retryWrapper = void 0;
    var retryWrapper = (toRetry, maxRetries, delayMs) => {
      return async () => {
        for (let i4 = 0; i4 < maxRetries; ++i4) {
          try {
            return await toRetry();
          } catch (e4) {
            await new Promise((resolve2) => setTimeout(resolve2, delayMs));
          }
        }
        return await toRetry();
      };
    };
    exports2.retryWrapper = retryWrapper;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js
var require_fromHttp = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromHttp = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var client_1 = (init_client(), __toCommonJS(client_exports));
    var node_http_handler_1 = require_dist_cjs14();
    var property_provider_1 = require_dist_cjs20();
    var promises_1 = tslib_1.__importDefault(require("fs/promises"));
    var checkUrl_1 = require_checkUrl();
    var requestHelpers_1 = require_requestHelpers();
    var retry_wrapper_1 = require_retry_wrapper();
    var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    var DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
    var AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    var AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
    var AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    var fromHttp = (options = {}) => {
      var _a2, _b, _c;
      (_a2 = options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-http - fromHttp");
      let host;
      const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
      const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
      const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
      const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
      const warn = ((_c = (_b = options.logger) == null ? void 0 : _b.constructor) == null ? void 0 : _c.name) === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn;
      if (relative && full) {
        warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
        warn("awsContainerCredentialsFullUri will take precedence.");
      }
      if (token && tokenFile) {
        warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
        warn("awsContainerAuthorizationToken will take precedence.");
      }
      if (full) {
        host = full;
      } else if (relative) {
        host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;
      } else {
        throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided.
Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });
      }
      const url = new URL(host);
      (0, checkUrl_1.checkUrl)(url, options.logger);
      const requestHandler = new node_http_handler_1.NodeHttpHandler({
        requestTimeout: options.timeout ?? 1e3,
        connectionTimeout: options.timeout ?? 1e3
      });
      return (0, retry_wrapper_1.retryWrapper)(async () => {
        const request = (0, requestHelpers_1.createGetRequest)(url);
        if (token) {
          request.headers.Authorization = token;
        } else if (tokenFile) {
          request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString();
        }
        try {
          const result = await requestHandler.handle(request);
          return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z"));
        } catch (e4) {
          throw new property_provider_1.CredentialsProviderError(String(e4), { logger: options.logger });
        }
      }, options.maxRetries ?? 3, options.timeout ?? 1e3);
    };
    exports2.fromHttp = fromHttp;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js
var require_dist_cjs38 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromHttp = void 0;
    var fromHttp_1 = require_fromHttp();
    Object.defineProperty(exports2, "fromHttp", { enumerable: true, get: function() {
      return fromHttp_1.fromHttp;
    } });
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultSSOHttpAuthSchemeProvider = exports2.defaultSSOHttpAuthSchemeParametersProvider = void 0;
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var util_middleware_1 = require_dist_cjs6();
    var defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption3(authParameters) {
      return {
        schemeId: "aws.auth#sigv4",
        signingProperties: {
          name: "awsssoportal",
          region: authParameters.region
        },
        propertiesExtractor: (config, context) => ({
          signingProperties: {
            config,
            context
          }
        })
      };
    }
    function createSmithyApiNoAuthHttpAuthOption3(authParameters) {
      return {
        schemeId: "smithy.api#noAuth"
      };
    }
    var defaultSSOHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "GetRoleCredentials": {
          options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
          break;
        }
        case "ListAccountRoles": {
          options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
          break;
        }
        case "ListAccounts": {
          options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
          break;
        }
        case "Logout": {
          options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
        }
      }
      return options;
    };
    exports2.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig3 = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return Object.assign(config_0, {
        authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? [])
      });
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig3;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json
var require_package3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-sso",
      description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
      version: "3.817.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sso",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo sso"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node18": "18.2.4",
        "@types/node": "^18.19.69",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      engines: {
        node: ">=18.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sso"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js
var require_dist_cjs39 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS3,
      UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME,
      UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME,
      createDefaultUserAgentProvider: () => createDefaultUserAgentProvider3,
      crtAvailability: () => crtAvailability,
      defaultUserAgent: () => defaultUserAgent
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_os = require("os");
    var import_process = require("process");
    var crtAvailability = {
      isCrtAvailable: false
    };
    var isCrtAvailable = /* @__PURE__ */ __name(() => {
      if (crtAvailability.isCrtAvailable) {
        return ["md/crt-avail"];
      }
      return null;
    }, "isCrtAvailable");
    var createDefaultUserAgentProvider3 = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => {
      return async (config) => {
        var _a2;
        const sections = [
          // sdk-metadata
          ["aws-sdk-js", clientVersion],
          // ua-metadata
          ["ua", "2.1"],
          // os-metadata
          [`os/${(0, import_os.platform)()}`, (0, import_os.release)()],
          // language-metadata
          // ECMAScript edition doesn't matter in JS, so no version needed.
          ["lang/js"],
          ["md/nodejs", `${import_process.versions.node}`]
        ];
        const crtAvailable = isCrtAvailable();
        if (crtAvailable) {
          sections.push(crtAvailable);
        }
        if (serviceId) {
          sections.push([`api/${serviceId}`, clientVersion]);
        }
        if (import_process.env.AWS_EXECUTION_ENV) {
          sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]);
        }
        const appId = await ((_a2 = config == null ? void 0 : config.userAgentAppId) == null ? void 0 : _a2.call(config));
        const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
        return resolvedUserAgent;
      };
    }, "createDefaultUserAgentProvider");
    var defaultUserAgent = createDefaultUserAgentProvider3;
    var import_middleware_user_agent3 = require_dist_cjs24();
    var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
    var UA_APP_ID_INI_NAME = "sdk_ua_app_id";
    var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
    var NODE_APP_ID_CONFIG_OPTIONS3 = {
      environmentVariableSelector: /* @__PURE__ */ __name((env22) => env22[UA_APP_ID_ENV_NAME], "environmentVariableSelector"),
      configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"),
      default: import_middleware_user_agent3.DEFAULT_UA_APP_ID
    };
  }
});

// ../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-cjs/index.js
var require_dist_cjs40 = __commonJS({
  "../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Hash: () => Hash3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_buffer_from = require_dist_cjs9();
    var import_util_utf85 = require_dist_cjs10();
    var import_buffer2 = require("buffer");
    var import_crypto10 = require("crypto");
    var _a2;
    var Hash3 = (_a2 = class {
      constructor(algorithmIdentifier, secret) {
        this.algorithmIdentifier = algorithmIdentifier;
        this.secret = secret;
        this.reset();
      }
      update(toHash, encoding) {
        this.hash.update((0, import_util_utf85.toUint8Array)(castSourceData(toHash, encoding)));
      }
      digest() {
        return Promise.resolve(this.hash.digest());
      }
      reset() {
        this.hash = this.secret ? (0, import_crypto10.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto10.createHash)(this.algorithmIdentifier);
      }
    }, __name(_a2, "Hash"), _a2);
    function castSourceData(toCast, encoding) {
      if (import_buffer2.Buffer.isBuffer(toCast)) {
        return toCast;
      }
      if (typeof toCast === "string") {
        return (0, import_util_buffer_from.fromString)(toCast, encoding);
      }
      if (ArrayBuffer.isView(toCast)) {
        return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength);
      }
      return (0, import_util_buffer_from.fromArrayBuffer)(toCast);
    }
    __name(castSourceData, "castSourceData");
  }
});

// ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js
var require_dist_cjs41 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      calculateBodyLength: () => calculateBodyLength3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_fs14 = require("fs");
    var calculateBodyLength3 = /* @__PURE__ */ __name((body) => {
      if (!body) {
        return 0;
      }
      if (typeof body === "string") {
        return Buffer.byteLength(body);
      } else if (typeof body.byteLength === "number") {
        return body.byteLength;
      } else if (typeof body.size === "number") {
        return body.size;
      } else if (typeof body.start === "number" && typeof body.end === "number") {
        return body.end + 1 - body.start;
      } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
        return (0, import_fs14.lstatSync)(body.path).size;
      } else if (typeof body.fd === "number") {
        return (0, import_fs14.fstatSync)(body.fd).size;
      }
      throw new Error(`Body Length computation failed for ${body}`);
    }, "calculateBodyLength");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js
var require_ruleset = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var u3 = "required";
    var v6 = "fn";
    var w3 = "argv";
    var x4 = "ref";
    var a3 = true;
    var b3 = "isSet";
    var c3 = "booleanEquals";
    var d3 = "error";
    var e4 = "endpoint";
    var f5 = "tree";
    var g3 = "PartitionResult";
    var h4 = "getAttr";
    var i4 = { [u3]: false, "type": "String" };
    var j3 = { [u3]: true, "default": false, "type": "Boolean" };
    var k3 = { [x4]: "Endpoint" };
    var l3 = { [v6]: c3, [w3]: [{ [x4]: "UseFIPS" }, true] };
    var m4 = { [v6]: c3, [w3]: [{ [x4]: "UseDualStack" }, true] };
    var n3 = {};
    var o3 = { [v6]: h4, [w3]: [{ [x4]: g3 }, "supportsFIPS"] };
    var p3 = { [x4]: g3 };
    var q3 = { [v6]: c3, [w3]: [true, { [v6]: h4, [w3]: [p3, "supportsDualStack"] }] };
    var r4 = [l3];
    var s4 = [m4];
    var t4 = [{ [x4]: "Region" }];
    var _data3 = { version: "1.0", parameters: { Region: i4, UseDualStack: j3, UseFIPS: j3, Endpoint: i4 }, rules: [{ conditions: [{ [v6]: b3, [w3]: [k3] }], rules: [{ conditions: r4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, { conditions: s4, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d3 }, { endpoint: { url: k3, properties: n3, headers: n3 }, type: e4 }], type: f5 }, { conditions: [{ [v6]: b3, [w3]: t4 }], rules: [{ conditions: [{ [v6]: "aws.partition", [w3]: t4, assign: g3 }], rules: [{ conditions: [l3, m4], rules: [{ conditions: [{ [v6]: c3, [w3]: [a3, o3] }, q3], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d3 }], type: f5 }, { conditions: r4, rules: [{ conditions: [{ [v6]: c3, [w3]: [o3, a3] }], rules: [{ conditions: [{ [v6]: "stringEquals", [w3]: [{ [v6]: h4, [w3]: [p3, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n3, headers: n3 }, type: e4 }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d3 }], type: f5 }, { conditions: s4, rules: [{ conditions: [q3], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d3 }], type: f5 }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }], type: f5 }, { error: "Invalid Configuration: Missing Region", type: d3 }] };
    exports2.ruleSet = _data3;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs19();
    var util_endpoints_2 = require_dist_cjs18();
    var ruleset_1 = require_ruleset();
    var cache3 = new util_endpoints_2.EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    var defaultEndpointResolver3 = (endpointParams, context = {}) => {
      return cache3.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      }));
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver3;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var core_2 = (init_dist_es(), __toCommonJS(dist_es_exports));
    var smithy_client_1 = require_dist_cjs23();
    var url_parser_1 = require_dist_cjs31();
    var util_base64_1 = require_dist_cjs11();
    var util_utf8_1 = require_dist_cjs10();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider2();
    var endpointResolver_1 = require_endpointResolver();
    var getRuntimeConfig5 = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig5;
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js
var require_dist_cjs42 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js"(exports2, module2) {
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      resolveDefaultsModeConfig: () => resolveDefaultsModeConfig3
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_config_resolver5 = require_dist_cjs26();
    var import_node_config_provider3 = require_dist_cjs29();
    var import_property_provider2 = require_dist_cjs20();
    var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
    var AWS_REGION_ENV = "AWS_REGION";
    var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
    var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
    var IMDS_REGION_PATH = "/latest/meta-data/placement/region";
    var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
    var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
    var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => {
        return env3[AWS_DEFAULTS_MODE_ENV];
      },
      configFileSelector: (profile) => {
        return profile[AWS_DEFAULTS_MODE_CONFIG];
      },
      default: "legacy"
    };
    var resolveDefaultsModeConfig3 = /* @__PURE__ */ __name(({
      region = (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_REGION_CONFIG_OPTIONS),
      defaultsMode = (0, import_node_config_provider3.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS)
    } = {}) => (0, import_property_provider2.memoize)(async () => {
      const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
      switch (mode == null ? void 0 : mode.toLowerCase()) {
        case "auto":
          return resolveNodeDefaultsModeAuto(region);
        case "in-region":
        case "cross-region":
        case "mobile":
        case "standard":
        case "legacy":
          return Promise.resolve(mode == null ? void 0 : mode.toLocaleLowerCase());
        case void 0:
          return Promise.resolve("legacy");
        default:
          throw new Error(
            `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`
          );
      }
    }), "resolveDefaultsModeConfig");
    var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => {
      if (clientRegion) {
        const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
        const inferredRegion = await inferPhysicalRegion();
        if (!inferredRegion) {
          return "standard";
        }
        if (resolvedRegion === inferredRegion) {
          return "in-region";
        } else {
          return "cross-region";
        }
      }
      return "standard";
    }, "resolveNodeDefaultsModeAuto");
    var inferPhysicalRegion = /* @__PURE__ */ __name(async () => {
      if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
        return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
      }
      if (!process.env[ENV_IMDS_DISABLED]) {
        try {
          const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
          const endpoint = await getInstanceMetadataEndpoint();
          return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString();
        } catch (e4) {
        }
      }
    }, "inferPhysicalRegion");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js
var require_runtimeConfig = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package3());
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var util_user_agent_node_1 = require_dist_cjs39();
    var config_resolver_1 = require_dist_cjs26();
    var hash_node_1 = require_dist_cjs40();
    var middleware_retry_1 = require_dist_cjs35();
    var node_config_provider_1 = require_dist_cjs29();
    var node_http_handler_1 = require_dist_cjs14();
    var util_body_length_node_1 = require_dist_cjs41();
    var util_retry_1 = require_dist_cjs34();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared();
    var smithy_client_1 = require_dist_cjs23();
    var util_defaults_mode_node_1 = require_dist_cjs42();
    var smithy_client_2 = require_dist_cjs23();
    var getRuntimeConfig5 = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      const loaderConfig = {
        profile: config == null ? void 0 : config.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }, config),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
var require_dist_cjs43 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS3,
      NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS3,
      REGION_ENV_NAME: () => REGION_ENV_NAME,
      REGION_INI_NAME: () => REGION_INI_NAME,
      getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration3,
      resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration3,
      resolveRegionConfig: () => resolveRegionConfig3
    });
    module2.exports = __toCommonJS2(index_exports);
    var getAwsRegionExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
      return {
        setRegion(region) {
          runtimeConfig.region = region;
        },
        region() {
          return runtimeConfig.region;
        }
      };
    }, "getAwsRegionExtensionConfiguration");
    var resolveAwsRegionExtensionConfiguration3 = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => {
      return {
        region: awsRegionExtensionConfiguration.region()
      };
    }, "resolveAwsRegionExtensionConfiguration");
    var REGION_ENV_NAME = "AWS_REGION";
    var REGION_INI_NAME = "region";
    var NODE_REGION_CONFIG_OPTIONS3 = {
      environmentVariableSelector: /* @__PURE__ */ __name((env3) => env3[REGION_ENV_NAME], "environmentVariableSelector"),
      configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"),
      default: /* @__PURE__ */ __name(() => {
        throw new Error("Region is missing");
      }, "default")
    };
    var NODE_REGION_CONFIG_FILE_OPTIONS3 = {
      preferredFile: "credentials"
    };
    var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
    var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
    var resolveRegionConfig3 = /* @__PURE__ */ __name((input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return Object.assign(input, {
        region: /* @__PURE__ */ __name(async () => {
          if (typeof region === "string") {
            return getRealRegion(region);
          }
          const providedRegion = await region();
          return getRealRegion(providedRegion);
        }, "region"),
        useFipsEndpoint: /* @__PURE__ */ __name(async () => {
          const providedRegion = typeof region === "string" ? region : await region();
          if (isFipsRegion(providedRegion)) {
            return true;
          }
          return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
        }, "useFipsEndpoint")
      });
    }, "resolveRegionConfig");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js
var require_dist_cjs44 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
      GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog,
      GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog,
      InvalidRequestException: () => InvalidRequestException2,
      ListAccountRolesCommand: () => ListAccountRolesCommand,
      ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog,
      ListAccountsCommand: () => ListAccountsCommand,
      ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog,
      LogoutCommand: () => LogoutCommand,
      LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog,
      ResourceNotFoundException: () => ResourceNotFoundException,
      RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog,
      SSO: () => SSO,
      SSOClient: () => SSOClient,
      SSOServiceException: () => SSOServiceException,
      TooManyRequestsException: () => TooManyRequestsException,
      UnauthorizedException: () => UnauthorizedException,
      __Client: () => import_smithy_client25.Client,
      paginateListAccountRoles: () => paginateListAccountRoles,
      paginateListAccounts: () => paginateListAccounts
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_middleware_host_header3 = require_dist_cjs3();
    var import_middleware_logger3 = require_dist_cjs4();
    var import_middleware_recursion_detection3 = require_dist_cjs5();
    var import_middleware_user_agent3 = require_dist_cjs24();
    var import_config_resolver5 = require_dist_cjs26();
    var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
    var import_middleware_content_length3 = require_dist_cjs27();
    var import_middleware_endpoint6 = require_dist_cjs32();
    var import_middleware_retry5 = require_dist_cjs35();
    var import_httpAuthSchemeProvider5 = require_httpAuthSchemeProvider2();
    var resolveClientEndpointParameters3 = /* @__PURE__ */ __name((options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "awsssoportal"
      });
    }, "resolveClientEndpointParameters");
    var commonParams3 = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig5 = require_runtimeConfig();
    var import_region_config_resolver3 = require_dist_cjs43();
    var import_protocol_http15 = require_dist_cjs2();
    var import_smithy_client25 = require_dist_cjs23();
    var getHttpAuthExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var resolveRuntimeExtensions3 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(
        (0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig),
        (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig),
        (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig),
        getHttpAuthExtensionConfiguration3(runtimeConfig)
      );
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(
        runtimeConfig,
        (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration),
        (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        resolveHttpAuthRuntimeConfig3(extensionConfiguration)
      );
    }, "resolveRuntimeExtensions");
    var _a2;
    var SSOClient = (_a2 = class extends import_smithy_client25.Client {
      /**
       * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}.
       */
      config;
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig5.getRuntimeConfig)(configuration || {});
        super(_config_0);
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters3(_config_0);
        const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1);
        const _config_3 = (0, import_middleware_retry5.resolveRetryConfig)(_config_2);
        const _config_4 = (0, import_config_resolver5.resolveRegionConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_endpoint6.resolveEndpointConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider5.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions3(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_retry5.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core17.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider5.defaultSSOHttpAuthSchemeParametersProvider,
            identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core17.DefaultIdentityProviderConfig({
              "aws.auth#sigv4": config.credentials
            }), "identityProviderConfigProvider")
          })
        );
        this.middlewareStack.use((0, import_core17.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
    }, __name(_a2, "SSOClient"), _a2);
    var import_middleware_serde5 = require_dist_cjs7();
    var _a3;
    var SSOServiceException = (_a3 = class extends import_smithy_client25.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _a3.prototype);
      }
    }, __name(_a3, "SSOServiceException"), _a3);
    var _a4;
    var InvalidRequestException2 = (_a4 = class extends SSOServiceException {
      name = "InvalidRequestException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a4.prototype);
      }
    }, __name(_a4, "InvalidRequestException"), _a4);
    var _a5;
    var ResourceNotFoundException = (_a5 = class extends SSOServiceException {
      name = "ResourceNotFoundException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ResourceNotFoundException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a5.prototype);
      }
    }, __name(_a5, "ResourceNotFoundException"), _a5);
    var _a6;
    var TooManyRequestsException = (_a6 = class extends SSOServiceException {
      name = "TooManyRequestsException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "TooManyRequestsException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a6.prototype);
      }
    }, __name(_a6, "TooManyRequestsException"), _a6);
    var _a7;
    var UnauthorizedException = (_a7 = class extends SSOServiceException {
      name = "UnauthorizedException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnauthorizedException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a7.prototype);
      }
    }, __name(_a7, "UnauthorizedException"), _a7);
    var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
    }), "GetRoleCredentialsRequestFilterSensitiveLog");
    var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.secretAccessKey && { secretAccessKey: import_smithy_client25.SENSITIVE_STRING },
      ...obj.sessionToken && { sessionToken: import_smithy_client25.SENSITIVE_STRING }
    }), "RoleCredentialsFilterSensitiveLog");
    var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
    }), "GetRoleCredentialsResponseFilterSensitiveLog");
    var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
    }), "ListAccountRolesRequestFilterSensitiveLog");
    var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
    }), "ListAccountsRequestFilterSensitiveLog");
    var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
    }), "LogoutRequestFilterSensitiveLog");
    var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b3.bp("/federation/credentials");
      const query = (0, import_smithy_client25.map)({
        [_rn]: [, (0, import_smithy_client25.expectNonNull)(input[_rN], `roleName`)],
        [_ai]: [, (0, import_smithy_client25.expectNonNull)(input[_aI], `accountId`)]
      });
      let body;
      b3.m("GET").h(headers).q(query).b(body);
      return b3.build();
    }, "se_GetRoleCredentialsCommand");
    var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b3.bp("/assignment/roles");
      const query = (0, import_smithy_client25.map)({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
        [_ai]: [, (0, import_smithy_client25.expectNonNull)(input[_aI], `accountId`)]
      });
      let body;
      b3.m("GET").h(headers).q(query).b(body);
      return b3.build();
    }, "se_ListAccountRolesCommand");
    var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b3.bp("/assignment/accounts");
      const query = (0, import_smithy_client25.map)({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
      });
      let body;
      b3.m("GET").h(headers).q(query).b(body);
      return b3.build();
    }, "se_ListAccountsCommand");
    var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b3.bp("/logout");
      let body;
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_LogoutCommand");
    var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        roleCredentials: import_smithy_client25._json
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_GetRoleCredentialsCommand");
    var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        nextToken: import_smithy_client25.expectString,
        roleList: import_smithy_client25._json
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ListAccountRolesCommand");
    var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        accountList: import_smithy_client25._json,
        nextToken: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ListAccountsCommand");
    var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      await (0, import_smithy_client25.collectBody)(output.body, context);
      return contents;
    }, "de_LogoutCommand");
    var de_CommandError3 = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core22.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core22.loadRestJsonErrorCode)(output, parsedOutput.body);
      switch (errorCode) {
        case "InvalidRequestException":
        case "com.amazonaws.sso#InvalidRequestException":
          throw await de_InvalidRequestExceptionRes2(parsedOutput, context);
        case "ResourceNotFoundException":
        case "com.amazonaws.sso#ResourceNotFoundException":
          throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
        case "TooManyRequestsException":
        case "com.amazonaws.sso#TooManyRequestsException":
          throw await de_TooManyRequestsExceptionRes(parsedOutput, context);
        case "UnauthorizedException":
        case "com.amazonaws.sso#UnauthorizedException":
          throw await de_UnauthorizedExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError3({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError3 = (0, import_smithy_client25.withBaseException)(SSOServiceException);
    var de_InvalidRequestExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException2({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestExceptionRes");
    var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new ResourceNotFoundException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ResourceNotFoundExceptionRes");
    var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new TooManyRequestsException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_TooManyRequestsExceptionRes");
    var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnauthorizedExceptionRes");
    var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    }), "deserializeMetadata");
    var _aI = "accountId";
    var _aT = "accessToken";
    var _ai = "account_id";
    var _mR = "maxResults";
    var _mr = "max_result";
    var _nT = "nextToken";
    var _nt = "next_token";
    var _rN = "roleName";
    var _rn = "role_name";
    var _xasbt = "x-amz-sso_bearer_token";
    var _a8;
    var GetRoleCredentialsCommand = (_a8 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
    }, __name(_a8, "GetRoleCredentialsCommand"), _a8);
    var _a9;
    var ListAccountRolesCommand = (_a9 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
    }, __name(_a9, "ListAccountRolesCommand"), _a9);
    var _a10;
    var ListAccountsCommand = (_a10 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
    }, __name(_a10, "ListAccountsCommand"), _a10);
    var _a11;
    var LogoutCommand = (_a11 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
    }, __name(_a11, "LogoutCommand"), _a11);
    var commands3 = {
      GetRoleCredentialsCommand,
      ListAccountRolesCommand,
      ListAccountsCommand,
      LogoutCommand
    };
    var _a12;
    var SSO = (_a12 = class extends SSOClient {
    }, __name(_a12, "SSO"), _a12);
    (0, import_smithy_client25.createAggregatedClient)(commands3, SSO);
    var paginateListAccountRoles = (0, import_core17.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
    var paginateListAccounts = (0, import_core17.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "sso-oauth",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var import_util_middleware5, defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
var init_httpAuthSchemeProvider = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() {
    init_dist_es2();
    import_util_middleware5 = __toESM(require_dist_cjs6());
    defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, import_util_middleware5.getSmithyContext)(context).operation,
        region: await (0, import_util_middleware5.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "CreateToken": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = resolveAwsSdkSigV4Config(config);
      return Object.assign(config_0, {
        authSchemePreference: (0, import_util_middleware5.normalizeProvider)(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js
var resolveClientEndpointParameters, commonParams;
var init_EndpointParameters = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() {
    resolveClientEndpointParameters = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "sso-oauth"
      });
    };
    commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json
var package_default;
var init_package = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json"() {
    package_default = {
      name: "@aws-sdk/nested-clients",
      version: "3.817.0",
      description: "Nested clients for AWS SDK packages.",
      main: "./dist-cjs/index.js",
      module: "./dist-es/index.js",
      types: "./dist-types/index.d.ts",
      scripts: {
        build: "yarn lint && concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline nested-clients",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients",
        test: "yarn g:vitest run",
        "test:watch": "yarn g:vitest watch"
      },
      engines: {
        node: ">=18.0.0"
      },
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "./sso-oidc.d.ts",
        "./sso-oidc.js",
        "./sts.d.ts",
        "./sts.js",
        "dist-*/**"
      ],
      browser: {
        "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser",
        "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser"
      },
      "react-native": {},
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "packages/nested-clients"
      },
      exports: {
        "./sso-oidc": {
          types: "./dist-types/submodules/sso-oidc/index.d.ts",
          module: "./dist-es/submodules/sso-oidc/index.js",
          node: "./dist-cjs/submodules/sso-oidc/index.js",
          import: "./dist-es/submodules/sso-oidc/index.js",
          require: "./dist-cjs/submodules/sso-oidc/index.js"
        },
        "./sts": {
          types: "./dist-types/submodules/sts/index.d.ts",
          module: "./dist-es/submodules/sts/index.js",
          node: "./dist-cjs/submodules/sts/index.js",
          import: "./dist-es/submodules/sts/index.js",
          require: "./dist-cjs/submodules/sts/index.js"
        }
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js
var u, v, w, x2, a, b, c, d, e2, f3, g, h2, i2, j, k, l, m2, n, o, p, q, r2, s2, t2, _data, ruleSet;
var init_ruleset = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() {
    u = "required";
    v = "fn";
    w = "argv";
    x2 = "ref";
    a = true;
    b = "isSet";
    c = "booleanEquals";
    d = "error";
    e2 = "endpoint";
    f3 = "tree";
    g = "PartitionResult";
    h2 = "getAttr";
    i2 = { [u]: false, "type": "String" };
    j = { [u]: true, "default": false, "type": "Boolean" };
    k = { [x2]: "Endpoint" };
    l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
    m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
    n = {};
    o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
    p = { [x2]: g };
    q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
    r2 = [l];
    s2 = [m2];
    t2 = [{ [x2]: "Region" }];
    _data = { version: "1.0", parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e2 }], type: f3 }, { conditions: [{ [v]: b, [w]: t2 }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t2, assign: g }], rules: [{ conditions: [l, m2], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f3 }, { conditions: r2, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e2 }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f3 }, { conditions: s2, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f3 }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
    ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js
var import_util_endpoints, import_util_endpoints2, cache, defaultEndpointResolver;
var init_endpointResolver = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() {
    import_util_endpoints = __toESM(require_dist_cjs19());
    import_util_endpoints2 = __toESM(require_dist_cjs18());
    init_ruleset();
    cache = new import_util_endpoints2.EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    defaultEndpointResolver = (endpointParams, context = {}) => {
      return cache.get(endpointParams, () => (0, import_util_endpoints2.resolveEndpoint)(ruleSet, {
        endpointParams,
        logger: context.logger
      }));
    };
    import_util_endpoints2.customEndpointFunctions.aws = import_util_endpoints.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js
var import_smithy_client4, import_url_parser, import_util_base643, import_util_utf83, getRuntimeConfig;
var init_runtimeConfig_shared = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() {
    init_dist_es2();
    init_dist_es();
    import_smithy_client4 = __toESM(require_dist_cjs23());
    import_url_parser = __toESM(require_dist_cjs31());
    import_util_base643 = __toESM(require_dist_cjs11());
    import_util_utf83 = __toESM(require_dist_cjs10());
    init_httpAuthSchemeProvider();
    init_endpointResolver();
    getRuntimeConfig = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? import_util_base643.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? import_util_base643.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? defaultSSOOIDCHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new import_smithy_client4.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO OIDC",
        urlParser: (config == null ? void 0 : config.urlParser) ?? import_url_parser.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? import_util_utf83.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? import_util_utf83.toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js
var import_util_user_agent_node, import_config_resolver, import_hash_node, import_middleware_retry, import_node_config_provider, import_node_http_handler, import_util_body_length_node, import_util_retry, import_smithy_client5, import_util_defaults_mode_node, import_smithy_client6, getRuntimeConfig2;
var init_runtimeConfig = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() {
    init_package();
    init_dist_es2();
    import_util_user_agent_node = __toESM(require_dist_cjs39());
    import_config_resolver = __toESM(require_dist_cjs26());
    import_hash_node = __toESM(require_dist_cjs40());
    import_middleware_retry = __toESM(require_dist_cjs35());
    import_node_config_provider = __toESM(require_dist_cjs29());
    import_node_http_handler = __toESM(require_dist_cjs14());
    import_util_body_length_node = __toESM(require_dist_cjs41());
    import_util_retry = __toESM(require_dist_cjs34());
    init_runtimeConfig_shared();
    import_smithy_client5 = __toESM(require_dist_cjs23());
    import_util_defaults_mode_node = __toESM(require_dist_cjs42());
    import_smithy_client6 = __toESM(require_dist_cjs23());
    getRuntimeConfig2 = (config) => {
      (0, import_smithy_client6.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, import_util_defaults_mode_node.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(import_smithy_client5.loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config == null ? void 0 : config.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, import_node_config_provider.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? import_util_body_length_node.calculateBodyLength,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, import_util_user_agent_node.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, import_node_config_provider.loadConfig)(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: (config == null ? void 0 : config.region) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: import_node_http_handler.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, import_node_config_provider.loadConfig)({
          ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE
        }, config),
        sha256: (config == null ? void 0 : config.sha256) ?? import_hash_node.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? import_node_http_handler.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, import_node_config_provider.loadConfig)(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
var init_httpAuthExtensionConfiguration = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() {
    getHttpAuthExtensionConfiguration = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js
var import_region_config_resolver, import_protocol_http12, import_smithy_client7, resolveRuntimeExtensions;
var init_runtimeExtensions = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() {
    import_region_config_resolver = __toESM(require_dist_cjs43());
    import_protocol_http12 = __toESM(require_dist_cjs2());
    import_smithy_client7 = __toESM(require_dist_cjs23());
    init_httpAuthExtensionConfiguration();
    resolveRuntimeExtensions = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client7.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http12.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client7.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http12.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js
var import_middleware_host_header, import_middleware_logger, import_middleware_recursion_detection, import_middleware_user_agent, import_config_resolver2, import_middleware_content_length, import_middleware_endpoint, import_middleware_retry2, import_smithy_client8, SSOOIDCClient;
var init_SSOOIDCClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() {
    import_middleware_host_header = __toESM(require_dist_cjs3());
    import_middleware_logger = __toESM(require_dist_cjs4());
    import_middleware_recursion_detection = __toESM(require_dist_cjs5());
    import_middleware_user_agent = __toESM(require_dist_cjs24());
    import_config_resolver2 = __toESM(require_dist_cjs26());
    init_dist_es();
    import_middleware_content_length = __toESM(require_dist_cjs27());
    import_middleware_endpoint = __toESM(require_dist_cjs32());
    import_middleware_retry2 = __toESM(require_dist_cjs35());
    import_smithy_client8 = __toESM(require_dist_cjs23());
    init_httpAuthSchemeProvider();
    init_EndpointParameters();
    init_runtimeConfig();
    init_runtimeExtensions();
    SSOOIDCClient = class extends import_smithy_client8.Client {
      config;
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig2(configuration || {});
        super(_config_0);
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1);
        const _config_3 = (0, import_middleware_retry2.resolveRetryConfig)(_config_2);
        const _config_4 = (0, import_config_resolver2.resolveRegionConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_retry2.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js
var import_smithy_client9, SSOOIDCServiceException;
var init_SSOOIDCServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() {
    import_smithy_client9 = __toESM(require_dist_cjs23());
    SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client9.ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js
var import_smithy_client10, AccessDeniedException, AuthorizationPendingException, CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException;
var init_models_0 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() {
    import_smithy_client10 = __toESM(require_dist_cjs23());
    init_SSOOIDCServiceException();
    AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException {
      name = "AccessDeniedException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _AccessDeniedException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException {
      name = "AuthorizationPendingException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "AuthorizationPendingException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _AuthorizationPendingException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    CreateTokenRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client10.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client10.SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: import_smithy_client10.SENSITIVE_STRING }
    });
    CreateTokenResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client10.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client10.SENSITIVE_STRING },
      ...obj.idToken && { idToken: import_smithy_client10.SENSITIVE_STRING }
    });
    ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException {
      name = "ExpiredTokenException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InternalServerException = class _InternalServerException extends SSOOIDCServiceException {
      name = "InternalServerException";
      $fault = "server";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "InternalServerException",
          $fault: "server",
          ...opts
        });
        Object.setPrototypeOf(this, _InternalServerException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException {
      name = "InvalidClientException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "InvalidClientException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _InvalidClientException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException {
      name = "InvalidGrantException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "InvalidGrantException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _InvalidGrantException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException {
      name = "InvalidRequestException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _InvalidRequestException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException {
      name = "InvalidScopeException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "InvalidScopeException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _InvalidScopeException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    SlowDownException = class _SlowDownException extends SSOOIDCServiceException {
      name = "SlowDownException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "SlowDownException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _SlowDownException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException {
      name = "UnauthorizedClientException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "UnauthorizedClientException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _UnauthorizedClientException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException {
      name = "UnsupportedGrantTypeException";
      $fault = "client";
      error;
      error_description;
      constructor(opts) {
        super({
          name: "UnsupportedGrantTypeException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js
var import_smithy_client11, se_CreateTokenCommand, de_CreateTokenCommand, de_CommandError, throwDefaultError, de_AccessDeniedExceptionRes, de_AuthorizationPendingExceptionRes, de_ExpiredTokenExceptionRes, de_InternalServerExceptionRes, de_InvalidClientExceptionRes, de_InvalidGrantExceptionRes, de_InvalidRequestExceptionRes, de_InvalidScopeExceptionRes, de_SlowDownExceptionRes, de_UnauthorizedClientExceptionRes, de_UnsupportedGrantTypeExceptionRes, deserializeMetadata;
var init_Aws_restJson1 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js"() {
    init_dist_es2();
    init_dist_es();
    import_smithy_client11 = __toESM(require_dist_cjs23());
    init_models_0();
    init_SSOOIDCServiceException();
    se_CreateTokenCommand = async (input, context) => {
      const b3 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/token");
      let body;
      body = JSON.stringify((0, import_smithy_client11.take)(input, {
        clientId: [],
        clientSecret: [],
        code: [],
        codeVerifier: [],
        deviceCode: [],
        grantType: [],
        redirectUri: [],
        refreshToken: [],
        scope: (_3) => (0, import_smithy_client11._json)(_3)
      }));
      b3.m("POST").h(headers).b(body);
      return b3.build();
    };
    de_CreateTokenCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client11.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client11.expectNonNull)((0, import_smithy_client11.expectObject)(await parseJsonBody(output.body, context)), "body");
      const doc = (0, import_smithy_client11.take)(data, {
        accessToken: import_smithy_client11.expectString,
        expiresIn: import_smithy_client11.expectInt32,
        idToken: import_smithy_client11.expectString,
        refreshToken: import_smithy_client11.expectString,
        tokenType: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_CommandError = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseJsonErrorBody(output.body, context)
      };
      const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.ssooidc#AccessDeniedException":
          throw await de_AccessDeniedExceptionRes(parsedOutput, context);
        case "AuthorizationPendingException":
        case "com.amazonaws.ssooidc#AuthorizationPendingException":
          throw await de_AuthorizationPendingExceptionRes(parsedOutput, context);
        case "ExpiredTokenException":
        case "com.amazonaws.ssooidc#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes(parsedOutput, context);
        case "InternalServerException":
        case "com.amazonaws.ssooidc#InternalServerException":
          throw await de_InternalServerExceptionRes(parsedOutput, context);
        case "InvalidClientException":
        case "com.amazonaws.ssooidc#InvalidClientException":
          throw await de_InvalidClientExceptionRes(parsedOutput, context);
        case "InvalidGrantException":
        case "com.amazonaws.ssooidc#InvalidGrantException":
          throw await de_InvalidGrantExceptionRes(parsedOutput, context);
        case "InvalidRequestException":
        case "com.amazonaws.ssooidc#InvalidRequestException":
          throw await de_InvalidRequestExceptionRes(parsedOutput, context);
        case "InvalidScopeException":
        case "com.amazonaws.ssooidc#InvalidScopeException":
          throw await de_InvalidScopeExceptionRes(parsedOutput, context);
        case "SlowDownException":
        case "com.amazonaws.ssooidc#SlowDownException":
          throw await de_SlowDownExceptionRes(parsedOutput, context);
        case "UnauthorizedClientException":
        case "com.amazonaws.ssooidc#UnauthorizedClientException":
          throw await de_UnauthorizedClientExceptionRes(parsedOutput, context);
        case "UnsupportedGrantTypeException":
        case "com.amazonaws.ssooidc#UnsupportedGrantTypeException":
          throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError({
            output,
            parsedBody,
            errorCode
          });
      }
    };
    throwDefaultError = (0, import_smithy_client11.withBaseException)(SSOOIDCServiceException);
    de_AccessDeniedExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new AuthorizationPendingException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_ExpiredTokenExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_InternalServerExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new InternalServerException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_InvalidClientExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_InvalidGrantExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidGrantException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_InvalidRequestExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_InvalidScopeExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidScopeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_SlowDownExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new SlowDownException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => {
      const contents = (0, import_smithy_client11.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client11.take)(data, {
        error: import_smithy_client11.expectString,
        error_description: import_smithy_client11.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedGrantTypeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
    };
    deserializeMetadata = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js
var import_middleware_endpoint2, import_middleware_serde2, import_smithy_client12, CreateTokenCommand;
var init_CreateTokenCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() {
    import_middleware_endpoint2 = __toESM(require_dist_cjs32());
    import_middleware_serde2 = __toESM(require_dist_cjs7());
    import_smithy_client12 = __toESM(require_dist_cjs23());
    init_EndpointParameters();
    init_models_0();
    init_Aws_restJson1();
    CreateTokenCommand = class extends import_smithy_client12.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js
var import_smithy_client13, commands, SSOOIDC;
var init_SSOOIDC = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() {
    import_smithy_client13 = __toESM(require_dist_cjs23());
    init_CreateTokenCommand();
    init_SSOOIDCClient();
    commands = {
      CreateTokenCommand
    };
    SSOOIDC = class extends SSOOIDCClient {
    };
    (0, import_smithy_client13.createAggregatedClient)(commands, SSOOIDC);
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js
var init_commands = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() {
    init_CreateTokenCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js
var init_models = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js"() {
    init_models_0();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js
var sso_oidc_exports = {};
__export(sso_oidc_exports, {
  $Command: () => import_smithy_client12.Command,
  AccessDeniedException: () => AccessDeniedException,
  AuthorizationPendingException: () => AuthorizationPendingException,
  CreateTokenCommand: () => CreateTokenCommand,
  CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
  CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
  ExpiredTokenException: () => ExpiredTokenException,
  InternalServerException: () => InternalServerException,
  InvalidClientException: () => InvalidClientException,
  InvalidGrantException: () => InvalidGrantException,
  InvalidRequestException: () => InvalidRequestException,
  InvalidScopeException: () => InvalidScopeException,
  SSOOIDC: () => SSOOIDC,
  SSOOIDCClient: () => SSOOIDCClient,
  SSOOIDCServiceException: () => SSOOIDCServiceException,
  SlowDownException: () => SlowDownException,
  UnauthorizedClientException: () => UnauthorizedClientException,
  UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
  __Client: () => import_smithy_client8.Client
});
var init_sso_oidc = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() {
    init_SSOOIDCClient();
    init_SSOOIDC();
    init_commands();
    init_models();
    init_SSOOIDCServiceException();
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
var require_dist_cjs45 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      fromEnvSigningName: () => fromEnvSigningName,
      fromSso: () => fromSso,
      fromStatic: () => fromStatic,
      nodeProvider: () => nodeProvider
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_core17 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var import_property_provider2 = require_dist_cjs20();
    var fromEnvSigningName = /* @__PURE__ */ __name(({ logger: logger3, signingName } = {}) => async () => {
      var _a2;
      (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, "@aws-sdk/token-providers - fromEnvSigningName");
      if (!signingName) {
        throw new import_property_provider2.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger3 });
      }
      const bearerTokenKey = (0, import_core17.getBearerTokenEnvKey)(signingName);
      if (!(bearerTokenKey in process.env)) {
        throw new import_property_provider2.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger3 });
      }
      return { token: process.env[bearerTokenKey] };
    }, "fromEnvSigningName");
    var EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
    var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
    var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init2 = {}) => {
      var _a2, _b, _c;
      const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => __toESM3((init_sso_oidc(), __toCommonJS(sso_oidc_exports))));
      const ssoOidcClient = new SSOOIDCClient2(
        Object.assign({}, init2.clientConfig ?? {}, {
          region: ssoRegion ?? ((_a2 = init2.clientConfig) == null ? void 0 : _a2.region),
          logger: ((_b = init2.clientConfig) == null ? void 0 : _b.logger) ?? ((_c = init2.parentClientConfig) == null ? void 0 : _c.logger)
        })
      );
      return ssoOidcClient;
    }, "getSsoOidcClient");
    var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init2 = {}) => {
      const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => __toESM3((init_sso_oidc(), __toCommonJS(sso_oidc_exports))));
      const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2);
      return ssoOidcClient.send(
        new CreateTokenCommand2({
          clientId: ssoToken.clientId,
          clientSecret: ssoToken.clientSecret,
          refreshToken: ssoToken.refreshToken,
          grantType: "refresh_token"
        })
      );
    }, "getNewSsoOidcToken");
    var validateTokenExpiry = /* @__PURE__ */ __name((token) => {
      if (token.expiration && token.expiration.getTime() < Date.now()) {
        throw new import_property_provider2.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
      }
    }, "validateTokenExpiry");
    var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => {
      if (typeof value === "undefined") {
        throw new import_property_provider2.TokenProviderError(
          `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`,
          false
        );
      }
    }, "validateTokenKey");
    var import_shared_ini_file_loader = require_dist_cjs28();
    var import_fs14 = require("fs");
    var { writeFile } = import_fs14.promises;
    var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => {
      const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id);
      const tokenString = JSON.stringify(ssoToken, null, 2);
      return writeFile(tokenFilepath, tokenString);
    }, "writeSSOTokenToFile");
    var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
    var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
      var _a2;
      const init2 = {
        ..._init,
        parentClientConfig: {
          ...callerClientConfig,
          ..._init.parentClientConfig
        }
      };
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/token-providers - fromSso");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      const profileName = (0, import_shared_ini_file_loader.getProfileName)({
        profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
      });
      const profile = profiles[profileName];
      if (!profile) {
        throw new import_property_provider2.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
      } else if (!profile["sso_session"]) {
        throw new import_property_provider2.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
      }
      const ssoSessionName = profile["sso_session"];
      const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
      const ssoSession = ssoSessions[ssoSessionName];
      if (!ssoSession) {
        throw new import_property_provider2.TokenProviderError(
          `Sso session '${ssoSessionName}' could not be found in shared credentials file.`,
          false
        );
      }
      for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
        if (!ssoSession[ssoSessionRequiredKey]) {
          throw new import_property_provider2.TokenProviderError(
            `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`,
            false
          );
        }
      }
      const ssoStartUrl = ssoSession["sso_start_url"];
      const ssoRegion = ssoSession["sso_region"];
      let ssoToken;
      try {
        ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName);
      } catch (e4) {
        throw new import_property_provider2.TokenProviderError(
          `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`,
          false
        );
      }
      validateTokenKey("accessToken", ssoToken.accessToken);
      validateTokenKey("expiresAt", ssoToken.expiresAt);
      const { accessToken, expiresAt } = ssoToken;
      const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
      if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
        return existingToken;
      }
      if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
        validateTokenExpiry(existingToken);
        return existingToken;
      }
      validateTokenKey("clientId", ssoToken.clientId, true);
      validateTokenKey("clientSecret", ssoToken.clientSecret, true);
      validateTokenKey("refreshToken", ssoToken.refreshToken, true);
      try {
        lastRefreshAttemptTime.setTime(Date.now());
        const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2);
        validateTokenKey("accessToken", newSsoOidcToken.accessToken);
        validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
        const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
        try {
          await writeSSOTokenToFile(ssoSessionName, {
            ...ssoToken,
            accessToken: newSsoOidcToken.accessToken,
            expiresAt: newTokenExpiration.toISOString(),
            refreshToken: newSsoOidcToken.refreshToken
          });
        } catch (error2) {
        }
        return {
          token: newSsoOidcToken.accessToken,
          expiration: newTokenExpiration
        };
      } catch (error2) {
        validateTokenExpiry(existingToken);
        return existingToken;
      }
    }, "fromSso");
    var fromStatic = /* @__PURE__ */ __name(({ token, logger: logger3 }) => async () => {
      logger3 == null ? void 0 : logger3.debug("@aws-sdk/token-providers - fromStatic");
      if (!token || !token.token) {
        throw new import_property_provider2.TokenProviderError(`Please pass a valid token to fromStatic`, false);
      }
      return token;
    }, "fromStatic");
    var nodeProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider2.memoize)(
      (0, import_property_provider2.chain)(fromSso(init2), async () => {
        throw new import_property_provider2.TokenProviderError("Could not load token from any providers", false);
      }),
      (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5,
      (token) => token.expiration !== void 0
    ), "nodeProvider");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
var require_dist_cjs46 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __esm2 = (fn, res) => function __init() {
      return fn && (res = (0, fn[__getOwnPropNames3(fn)[0]])(fn = 0)), res;
    };
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var loadSso_exports = {};
    __export2(loadSso_exports, {
      GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand,
      SSOClient: () => import_client_sso.SSOClient
    });
    var import_client_sso;
    var init_loadSso = __esm2({
      "src/loadSso.ts"() {
        "use strict";
        import_client_sso = require_dist_cjs44();
      }
    });
    var index_exports = {};
    __export2(index_exports, {
      fromSSO: () => fromSSO,
      isSsoProfile: () => isSsoProfile,
      validateSsoProfile: () => validateSsoProfile
    });
    module2.exports = __toCommonJS2(index_exports);
    var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
    var import_client3 = (init_client(), __toCommonJS(client_exports));
    var import_token_providers = require_dist_cjs45();
    var import_property_provider2 = require_dist_cjs20();
    var import_shared_ini_file_loader = require_dist_cjs28();
    var SHOULD_FAIL_CREDENTIAL_CHAIN = false;
    var resolveSSOCredentials = /* @__PURE__ */ __name(async ({
      ssoStartUrl,
      ssoSession,
      ssoAccountId,
      ssoRegion,
      ssoRoleName,
      ssoClient,
      clientConfig,
      parentClientConfig,
      profile,
      logger: logger3
    }) => {
      let token;
      const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
      if (ssoSession) {
        try {
          const _token = await (0, import_token_providers.fromSso)({ profile })();
          token = {
            accessToken: _token.token,
            expiresAt: new Date(_token.expiration).toISOString()
          };
        } catch (e4) {
          throw new import_property_provider2.CredentialsProviderError(e4.message, {
            tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
            logger: logger3
          });
        }
      } else {
        try {
          token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl);
        } catch (e4) {
          throw new import_property_provider2.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
            tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
            logger: logger3
          });
        }
      }
      if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
        throw new import_property_provider2.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger3
        });
      }
      const { accessToken } = token;
      const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
      const sso = ssoClient || new SSOClient2(
        Object.assign({}, clientConfig ?? {}, {
          logger: (clientConfig == null ? void 0 : clientConfig.logger) ?? (parentClientConfig == null ? void 0 : parentClientConfig.logger),
          region: (clientConfig == null ? void 0 : clientConfig.region) ?? ssoRegion
        })
      );
      let ssoResp;
      try {
        ssoResp = await sso.send(
          new GetRoleCredentialsCommand2({
            accountId: ssoAccountId,
            roleName: ssoRoleName,
            accessToken
          })
        );
      } catch (e4) {
        throw new import_property_provider2.CredentialsProviderError(e4, {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger3
        });
      }
      const {
        roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}
      } = ssoResp;
      if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
        throw new import_property_provider2.CredentialsProviderError("SSO returns an invalid temporary credential.", {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger3
        });
      }
      const credentials2 = {
        accessKeyId,
        secretAccessKey,
        sessionToken,
        expiration: new Date(expiration),
        ...credentialScope && { credentialScope },
        ...accountId && { accountId }
      };
      if (ssoSession) {
        (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_SSO", "s");
      } else {
        (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_SSO_LEGACY", "u");
      }
      return credentials2;
    }, "resolveSSOCredentials");
    var validateSsoProfile = /* @__PURE__ */ __name((profile, logger3) => {
      const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
      if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
        throw new import_property_provider2.CredentialsProviderError(
          `Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(
            ", "
          )}
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,
          { tryNextLink: false, logger: logger3 }
        );
      }
      return profile;
    }, "validateSsoProfile");
    var fromSSO = /* @__PURE__ */ __name((init2 = {}) => async ({ callerClientConfig } = {}) => {
      var _a2;
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-sso - fromSSO");
      const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
      const { ssoClient } = init2;
      const profileName = (0, import_shared_ini_file_loader.getProfileName)({
        profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
      });
      if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
        const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
        const profile = profiles[profileName];
        if (!profile) {
          throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger });
        }
        if (!isSsoProfile(profile)) {
          throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
            logger: init2.logger
          });
        }
        if (profile == null ? void 0 : profile.sso_session) {
          const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
          const session = ssoSessions[profile.sso_session];
          const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;
          if (ssoRegion && ssoRegion !== session.sso_region) {
            throw new import_property_provider2.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
              tryNextLink: false,
              logger: init2.logger
            });
          }
          if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
            throw new import_property_provider2.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
              tryNextLink: false,
              logger: init2.logger
            });
          }
          profile.sso_region = session.sso_region;
          profile.sso_start_url = session.sso_start_url;
        }
        const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(
          profile,
          init2.logger
        );
        return resolveSSOCredentials({
          ssoStartUrl: sso_start_url,
          ssoSession: sso_session,
          ssoAccountId: sso_account_id,
          ssoRegion: sso_region,
          ssoRoleName: sso_role_name,
          ssoClient,
          clientConfig: init2.clientConfig,
          parentClientConfig: init2.parentClientConfig,
          profile: profileName
        });
      } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
        throw new import_property_provider2.CredentialsProviderError(
          'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',
          { tryNextLink: false, logger: init2.logger }
        );
      } else {
        return resolveSSOCredentials({
          ssoStartUrl,
          ssoSession,
          ssoAccountId,
          ssoRegion,
          ssoRoleName,
          ssoClient,
          clientConfig: init2.clientConfig,
          parentClientConfig: init2.parentClientConfig,
          profile: profileName
        });
      }
    }, "fromSSO");
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption2(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "sts",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var import_util_middleware6, defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig2;
var init_httpAuthSchemeProvider2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() {
    init_dist_es2();
    import_util_middleware6 = __toESM(require_dist_cjs6());
    init_STSClient();
    defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, import_util_middleware6.getSmithyContext)(context).operation,
        region: await (0, import_util_middleware6.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSTSHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "AssumeRoleWithWebIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
        }
      }
      return options;
    };
    resolveStsAuthConfig = (input) => Object.assign(input, {
      stsClientCtor: STSClient
    });
    resolveHttpAuthSchemeConfig2 = (config) => {
      const config_0 = resolveStsAuthConfig(config);
      const config_1 = resolveAwsSdkSigV4Config(config_0);
      return Object.assign(config_1, {
        authSchemePreference: (0, import_util_middleware6.normalizeProvider)(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js
var resolveClientEndpointParameters2, commonParams2;
var init_EndpointParameters2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() {
    resolveClientEndpointParameters2 = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        useGlobalEndpoint: options.useGlobalEndpoint ?? false,
        defaultSigningName: "sts"
      });
    };
    commonParams2 = {
      UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js
var F2, G, H, I, J, a2, b2, c2, d2, e3, f4, g2, h3, i3, j2, k2, l2, m3, n2, o2, p2, q2, r3, s3, t3, u2, v2, w2, x3, y, z, A2, B, C, D, E, _data2, ruleSet2;
var init_ruleset2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() {
    F2 = "required";
    G = "type";
    H = "fn";
    I = "argv";
    J = "ref";
    a2 = false;
    b2 = true;
    c2 = "booleanEquals";
    d2 = "stringEquals";
    e3 = "sigv4";
    f4 = "sts";
    g2 = "us-east-1";
    h3 = "endpoint";
    i3 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
    j2 = "tree";
    k2 = "error";
    l2 = "getAttr";
    m3 = { [F2]: false, [G]: "String" };
    n2 = { [F2]: true, "default": false, [G]: "Boolean" };
    o2 = { [J]: "Endpoint" };
    p2 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
    q2 = { [J]: "Region" };
    r3 = { [H]: "aws.partition", [I]: [q2], "assign": "PartitionResult" };
    s3 = { [J]: "UseFIPS" };
    t3 = { [J]: "UseDualStack" };
    u2 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e3, "signingName": f4, "signingRegion": g2 }] }, "headers": {} };
    v2 = {};
    w2 = { "conditions": [{ [H]: d2, [I]: [q2, "aws-global"] }], [h3]: u2, [G]: h3 };
    x3 = { [H]: c2, [I]: [s3, true] };
    y = { [H]: c2, [I]: [t3, true] };
    z = { [H]: l2, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
    A2 = { [J]: "PartitionResult" };
    B = { [H]: c2, [I]: [true, { [H]: l2, [I]: [A2, "supportsDualStack"] }] };
    C = [{ [H]: "isSet", [I]: [o2] }];
    D = [x3];
    E = [y];
    _data2 = { version: "1.0", parameters: { Region: m3, UseDualStack: n2, UseFIPS: n2, Endpoint: m3, UseGlobalEndpoint: n2 }, rules: [{ conditions: [{ [H]: c2, [I]: [{ [J]: "UseGlobalEndpoint" }, b2] }, { [H]: "not", [I]: C }, p2, r3, { [H]: c2, [I]: [s3, a2] }, { [H]: c2, [I]: [t3, a2] }], rules: [{ conditions: [{ [H]: d2, [I]: [q2, "ap-northeast-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-south-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-2"] }], endpoint: u2, [G]: h3 }, w2, { conditions: [{ [H]: d2, [I]: [q2, "ca-central-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-central-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-north-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-2"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-3"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "sa-east-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, g2] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-east-2"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-2"] }], endpoint: u2, [G]: h3 }, { endpoint: { url: i3, properties: { authSchemes: [{ name: e3, signingName: f4, signingRegion: "{Region}" }] }, headers: v2 }, [G]: h3 }], [G]: j2 }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k2 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k2 }, { endpoint: { url: o2, properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { conditions: [p2], rules: [{ conditions: [r3], rules: [{ conditions: [x3, y], rules: [{ conditions: [{ [H]: c2, [I]: [b2, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k2 }], [G]: j2 }, { conditions: D, rules: [{ conditions: [{ [H]: c2, [I]: [z, b2] }], rules: [{ conditions: [{ [H]: d2, [I]: [{ [H]: l2, [I]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v2, headers: v2 }, [G]: h3 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k2 }], [G]: j2 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k2 }], [G]: j2 }, w2, { endpoint: { url: i3, properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }], [G]: j2 }, { error: "Invalid Configuration: Missing Region", [G]: k2 }] };
    ruleSet2 = _data2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js
var import_util_endpoints3, import_util_endpoints4, cache2, defaultEndpointResolver2;
var init_endpointResolver2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() {
    import_util_endpoints3 = __toESM(require_dist_cjs19());
    import_util_endpoints4 = __toESM(require_dist_cjs18());
    init_ruleset2();
    cache2 = new import_util_endpoints4.EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
    });
    defaultEndpointResolver2 = (endpointParams, context = {}) => {
      return cache2.get(endpointParams, () => (0, import_util_endpoints4.resolveEndpoint)(ruleSet2, {
        endpointParams,
        logger: context.logger
      }));
    };
    import_util_endpoints4.customEndpointFunctions.aws = import_util_endpoints3.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js
var import_smithy_client14, import_url_parser2, import_util_base644, import_util_utf84, getRuntimeConfig3;
var init_runtimeConfig_shared2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() {
    init_dist_es2();
    init_dist_es();
    import_smithy_client14 = __toESM(require_dist_cjs23());
    import_url_parser2 = __toESM(require_dist_cjs31());
    import_util_base644 = __toESM(require_dist_cjs11());
    import_util_utf84 = __toESM(require_dist_cjs10());
    init_httpAuthSchemeProvider2();
    init_endpointResolver2();
    getRuntimeConfig3 = (config) => {
      return {
        apiVersion: "2011-06-15",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? import_util_base644.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? import_util_base644.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? defaultEndpointResolver2,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? defaultSTSHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new import_smithy_client14.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "STS",
        urlParser: (config == null ? void 0 : config.urlParser) ?? import_url_parser2.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? import_util_utf84.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? import_util_utf84.toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js
var import_util_user_agent_node2, import_config_resolver3, import_hash_node2, import_middleware_retry3, import_node_config_provider2, import_node_http_handler2, import_util_body_length_node2, import_util_retry2, import_smithy_client15, import_util_defaults_mode_node2, import_smithy_client16, getRuntimeConfig4;
var init_runtimeConfig2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() {
    init_package();
    init_dist_es2();
    import_util_user_agent_node2 = __toESM(require_dist_cjs39());
    import_config_resolver3 = __toESM(require_dist_cjs26());
    init_dist_es();
    import_hash_node2 = __toESM(require_dist_cjs40());
    import_middleware_retry3 = __toESM(require_dist_cjs35());
    import_node_config_provider2 = __toESM(require_dist_cjs29());
    import_node_http_handler2 = __toESM(require_dist_cjs14());
    import_util_body_length_node2 = __toESM(require_dist_cjs41());
    import_util_retry2 = __toESM(require_dist_cjs34());
    init_runtimeConfig_shared2();
    import_smithy_client15 = __toESM(require_dist_cjs23());
    import_util_defaults_mode_node2 = __toESM(require_dist_cjs42());
    import_smithy_client16 = __toESM(require_dist_cjs23());
    getRuntimeConfig4 = (config) => {
      (0, import_smithy_client16.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, import_util_defaults_mode_node2.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(import_smithy_client15.loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig3(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config == null ? void 0 : config.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, import_node_config_provider2.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? import_util_body_length_node2.calculateBodyLength,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, import_util_user_agent_node2.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config.credentialDefaultProvider((idProps == null ? void 0 : idProps.__config) || {})()),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, import_node_config_provider2.loadConfig)(import_middleware_retry3.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: (config == null ? void 0 : config.region) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver3.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: import_node_http_handler2.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, import_node_config_provider2.loadConfig)({
          ...import_middleware_retry3.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || import_util_retry2.DEFAULT_RETRY_MODE
        }, config),
        sha256: (config == null ? void 0 : config.sha256) ?? import_hash_node2.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? import_node_http_handler2.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, import_node_config_provider2.loadConfig)(import_util_user_agent_node2.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
var init_httpAuthExtensionConfiguration2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() {
    getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig2 = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js
var import_region_config_resolver2, import_protocol_http13, import_smithy_client17, resolveRuntimeExtensions2;
var init_runtimeExtensions2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() {
    import_region_config_resolver2 = __toESM(require_dist_cjs43());
    import_protocol_http13 = __toESM(require_dist_cjs2());
    import_smithy_client17 = __toESM(require_dist_cjs23());
    init_httpAuthExtensionConfiguration2();
    resolveRuntimeExtensions2 = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign((0, import_region_config_resolver2.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client17.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http13.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, (0, import_region_config_resolver2.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client17.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http13.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js
var import_middleware_host_header2, import_middleware_logger2, import_middleware_recursion_detection2, import_middleware_user_agent2, import_config_resolver4, import_middleware_content_length2, import_middleware_endpoint3, import_middleware_retry4, import_smithy_client18, STSClient;
var init_STSClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() {
    import_middleware_host_header2 = __toESM(require_dist_cjs3());
    import_middleware_logger2 = __toESM(require_dist_cjs4());
    import_middleware_recursion_detection2 = __toESM(require_dist_cjs5());
    import_middleware_user_agent2 = __toESM(require_dist_cjs24());
    import_config_resolver4 = __toESM(require_dist_cjs26());
    init_dist_es();
    import_middleware_content_length2 = __toESM(require_dist_cjs27());
    import_middleware_endpoint3 = __toESM(require_dist_cjs32());
    import_middleware_retry4 = __toESM(require_dist_cjs35());
    import_smithy_client18 = __toESM(require_dist_cjs23());
    init_httpAuthSchemeProvider2();
    init_EndpointParameters2();
    init_runtimeConfig2();
    init_runtimeExtensions2();
    STSClient = class extends import_smithy_client18.Client {
      config;
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig4(configuration || {});
        super(_config_0);
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters2(_config_0);
        const _config_2 = (0, import_middleware_user_agent2.resolveUserAgentConfig)(_config_1);
        const _config_3 = (0, import_middleware_retry4.resolveRetryConfig)(_config_2);
        const _config_4 = (0, import_config_resolver4.resolveRegionConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header2.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_endpoint3.resolveEndpointConfig)(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
        const _config_8 = resolveRuntimeExtensions2(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_user_agent2.getUserAgentPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_retry4.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length2.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header2.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger2.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection2.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js
var import_smithy_client19, STSServiceException;
var init_STSServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() {
    import_smithy_client19 = __toESM(require_dist_cjs23());
    STSServiceException = class _STSServiceException extends import_smithy_client19.ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _STSServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js
var import_smithy_client20, CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, IDPCommunicationErrorException;
var init_models_02 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() {
    import_smithy_client20 = __toESM(require_dist_cjs23());
    init_STSServiceException();
    CredentialsFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client20.SENSITIVE_STRING }
    });
    AssumeRoleResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException {
      name = "ExpiredTokenException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
      }
    };
    MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException {
      name = "MalformedPolicyDocumentException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "MalformedPolicyDocumentException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype);
      }
    };
    PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException {
      name = "PackedPolicyTooLargeException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "PackedPolicyTooLargeException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype);
      }
    };
    RegionDisabledException = class _RegionDisabledException extends STSServiceException {
      name = "RegionDisabledException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "RegionDisabledException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _RegionDisabledException.prototype);
      }
    };
    IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException {
      name = "IDPRejectedClaimException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "IDPRejectedClaimException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype);
      }
    };
    InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException {
      name = "InvalidIdentityTokenException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "InvalidIdentityTokenException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype);
      }
    };
    AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client20.SENSITIVE_STRING }
    });
    AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException {
      name = "IDPCommunicationErrorException";
      $fault = "client";
      constructor(opts) {
        super({
          name: "IDPCommunicationErrorException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js
var import_protocol_http14, import_smithy_client21, se_AssumeRoleCommand, se_AssumeRoleWithWebIdentityCommand, de_AssumeRoleCommand, de_AssumeRoleWithWebIdentityCommand, de_CommandError2, de_ExpiredTokenExceptionRes2, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithWebIdentityRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithWebIdentityResponse, de_Credentials, de_ExpiredTokenException, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata2, throwDefaultError2, buildHttpRpcRequest, SHARED_HEADERS, _2, _A, _AKI, _AR, _ARI, _ARU, _ARWWI, _Ar, _Au, _C, _CA, _DS, _E, _EI, _K, _P, _PA, _PAr, _PC, _PI, _PPS, _Pr, _RA, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _V, _Va, _WIT, _a, _m, buildFormUrlencodedString, loadQueryErrorCode;
var init_Aws_query = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js"() {
    init_dist_es2();
    import_protocol_http14 = __toESM(require_dist_cjs2());
    import_smithy_client21 = __toESM(require_dist_cjs23());
    init_models_02();
    init_STSServiceException();
    se_AssumeRoleCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleRequest(input, context),
        [_A]: _AR,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_AssumeRoleWithWebIdentityCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleWithWebIdentityRequest(input, context),
        [_A]: _ARWWI,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    de_AssumeRoleCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_AssumeRoleWithWebIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_CommandError2 = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseXmlErrorBody(output.body, context)
      };
      const errorCode = loadQueryErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "ExpiredTokenException":
        case "com.amazonaws.sts#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes2(parsedOutput, context);
        case "MalformedPolicyDocument":
        case "com.amazonaws.sts#MalformedPolicyDocumentException":
          throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context);
        case "PackedPolicyTooLarge":
        case "com.amazonaws.sts#PackedPolicyTooLargeException":
          throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context);
        case "RegionDisabledException":
        case "com.amazonaws.sts#RegionDisabledException":
          throw await de_RegionDisabledExceptionRes(parsedOutput, context);
        case "IDPCommunicationError":
        case "com.amazonaws.sts#IDPCommunicationErrorException":
          throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
        case "IDPRejectedClaim":
        case "com.amazonaws.sts#IDPRejectedClaimException":
          throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context);
        case "InvalidIdentityToken":
        case "com.amazonaws.sts#InvalidIdentityTokenException":
          throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError2({
            output,
            parsedBody: parsedBody.Error,
            errorCode
          });
      }
    };
    de_ExpiredTokenExceptionRes2 = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_ExpiredTokenException(body.Error, context);
      const exception = new ExpiredTokenException2({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPCommunicationErrorException(body.Error, context);
      const exception = new IDPCommunicationErrorException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPRejectedClaimException(body.Error, context);
      const exception = new IDPRejectedClaimException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidIdentityTokenException(body.Error, context);
      const exception = new InvalidIdentityTokenException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
      const exception = new MalformedPolicyDocumentException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
      const exception = new PackedPolicyTooLargeException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    de_RegionDisabledExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_RegionDisabledException(body.Error, context);
      const exception = new RegionDisabledException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client21.decorateServiceException)(exception, body);
    };
    se_AssumeRoleRequest = (input, context) => {
      var _a2, _b, _c, _d;
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (((_a2 = input[_PA]) == null ? void 0 : _a2.length) === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_T] != null) {
        const memberEntries = se_tagListType(input[_T], context);
        if (((_b = input[_T]) == null ? void 0 : _b.length) === 0) {
          entries.Tags = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `Tags.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_TTK] != null) {
        const memberEntries = se_tagKeyListType(input[_TTK], context);
        if (((_c = input[_TTK]) == null ? void 0 : _c.length) === 0) {
          entries.TransitiveTagKeys = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `TransitiveTagKeys.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_EI] != null) {
        entries[_EI] = input[_EI];
      }
      if (input[_SN] != null) {
        entries[_SN] = input[_SN];
      }
      if (input[_TC] != null) {
        entries[_TC] = input[_TC];
      }
      if (input[_SI] != null) {
        entries[_SI] = input[_SI];
      }
      if (input[_PC] != null) {
        const memberEntries = se_ProvidedContextsListType(input[_PC], context);
        if (((_d = input[_PC]) == null ? void 0 : _d.length) === 0) {
          entries.ProvidedContexts = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `ProvidedContexts.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    };
    se_AssumeRoleWithWebIdentityRequest = (input, context) => {
      var _a2;
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_WIT] != null) {
        entries[_WIT] = input[_WIT];
      }
      if (input[_PI] != null) {
        entries[_PI] = input[_PI];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (((_a2 = input[_PA]) == null ? void 0 : _a2.length) === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      return entries;
    };
    se_policyDescriptorListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_PolicyDescriptorType(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_PolicyDescriptorType = (input, context) => {
      const entries = {};
      if (input[_a] != null) {
        entries[_a] = input[_a];
      }
      return entries;
    };
    se_ProvidedContext = (input, context) => {
      const entries = {};
      if (input[_PAr] != null) {
        entries[_PAr] = input[_PAr];
      }
      if (input[_CA] != null) {
        entries[_CA] = input[_CA];
      }
      return entries;
    };
    se_ProvidedContextsListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_ProvidedContext(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_Tag = (input, context) => {
      const entries = {};
      if (input[_K] != null) {
        entries[_K] = input[_K];
      }
      if (input[_Va] != null) {
        entries[_Va] = input[_Va];
      }
      return entries;
    };
    se_tagKeyListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        entries[`member.${counter}`] = entry;
        counter++;
      }
      return entries;
    };
    se_tagListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_Tag(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    de_AssumedRoleUser = (output, context) => {
      const contents = {};
      if (output[_ARI] != null) {
        contents[_ARI] = (0, import_smithy_client21.expectString)(output[_ARI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = (0, import_smithy_client21.expectString)(output[_Ar]);
      }
      return contents;
    };
    de_AssumeRoleResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = (0, import_smithy_client21.strictParseInt32)(output[_PPS]);
      }
      if (output[_SI] != null) {
        contents[_SI] = (0, import_smithy_client21.expectString)(output[_SI]);
      }
      return contents;
    };
    de_AssumeRoleWithWebIdentityResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_SFWIT] != null) {
        contents[_SFWIT] = (0, import_smithy_client21.expectString)(output[_SFWIT]);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = (0, import_smithy_client21.strictParseInt32)(output[_PPS]);
      }
      if (output[_Pr] != null) {
        contents[_Pr] = (0, import_smithy_client21.expectString)(output[_Pr]);
      }
      if (output[_Au] != null) {
        contents[_Au] = (0, import_smithy_client21.expectString)(output[_Au]);
      }
      if (output[_SI] != null) {
        contents[_SI] = (0, import_smithy_client21.expectString)(output[_SI]);
      }
      return contents;
    };
    de_Credentials = (output, context) => {
      const contents = {};
      if (output[_AKI] != null) {
        contents[_AKI] = (0, import_smithy_client21.expectString)(output[_AKI]);
      }
      if (output[_SAK] != null) {
        contents[_SAK] = (0, import_smithy_client21.expectString)(output[_SAK]);
      }
      if (output[_ST] != null) {
        contents[_ST] = (0, import_smithy_client21.expectString)(output[_ST]);
      }
      if (output[_E] != null) {
        contents[_E] = (0, import_smithy_client21.expectNonNull)((0, import_smithy_client21.parseRfc3339DateTimeWithOffset)(output[_E]));
      }
      return contents;
    };
    de_ExpiredTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_IDPCommunicationErrorException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_IDPRejectedClaimException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_InvalidIdentityTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_MalformedPolicyDocumentException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_PackedPolicyTooLargeException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    de_RegionDisabledException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
      }
      return contents;
    };
    deserializeMetadata2 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
    throwDefaultError2 = (0, import_smithy_client21.withBaseException)(STSServiceException);
    buildHttpRpcRequest = async (context, headers, path4, resolvedHostname, body) => {
      const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
      const contents = {
        protocol,
        hostname,
        port,
        method: "POST",
        path: basePath.endsWith("/") ? basePath.slice(0, -1) + path4 : basePath + path4,
        headers
      };
      if (resolvedHostname !== void 0) {
        contents.hostname = resolvedHostname;
      }
      if (body !== void 0) {
        contents.body = body;
      }
      return new import_protocol_http14.HttpRequest(contents);
    };
    SHARED_HEADERS = {
      "content-type": "application/x-www-form-urlencoded"
    };
    _2 = "2011-06-15";
    _A = "Action";
    _AKI = "AccessKeyId";
    _AR = "AssumeRole";
    _ARI = "AssumedRoleId";
    _ARU = "AssumedRoleUser";
    _ARWWI = "AssumeRoleWithWebIdentity";
    _Ar = "Arn";
    _Au = "Audience";
    _C = "Credentials";
    _CA = "ContextAssertion";
    _DS = "DurationSeconds";
    _E = "Expiration";
    _EI = "ExternalId";
    _K = "Key";
    _P = "Policy";
    _PA = "PolicyArns";
    _PAr = "ProviderArn";
    _PC = "ProvidedContexts";
    _PI = "ProviderId";
    _PPS = "PackedPolicySize";
    _Pr = "Provider";
    _RA = "RoleArn";
    _RSN = "RoleSessionName";
    _SAK = "SecretAccessKey";
    _SFWIT = "SubjectFromWebIdentityToken";
    _SI = "SourceIdentity";
    _SN = "SerialNumber";
    _ST = "SessionToken";
    _T = "Tags";
    _TC = "TokenCode";
    _TTK = "TransitiveTagKeys";
    _V = "Version";
    _Va = "Value";
    _WIT = "WebIdentityToken";
    _a = "arn";
    _m = "message";
    buildFormUrlencodedString = (formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client21.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client21.extendedEncodeURIComponent)(value)).join("&");
    loadQueryErrorCode = (output, data) => {
      var _a2;
      if (((_a2 = data.Error) == null ? void 0 : _a2.Code) !== void 0) {
        return data.Error.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js
var import_middleware_endpoint4, import_middleware_serde3, import_smithy_client22, AssumeRoleCommand;
var init_AssumeRoleCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() {
    import_middleware_endpoint4 = __toESM(require_dist_cjs32());
    import_middleware_serde3 = __toESM(require_dist_cjs7());
    import_smithy_client22 = __toESM(require_dist_cjs23());
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    AssumeRoleCommand = class extends import_smithy_client22.Command.classBuilder().ep(commonParams2).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde3.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint4.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js
var import_middleware_endpoint5, import_middleware_serde4, import_smithy_client23, AssumeRoleWithWebIdentityCommand;
var init_AssumeRoleWithWebIdentityCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() {
    import_middleware_endpoint5 = __toESM(require_dist_cjs32());
    import_middleware_serde4 = __toESM(require_dist_cjs7());
    import_smithy_client23 = __toESM(require_dist_cjs23());
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    AssumeRoleWithWebIdentityCommand = class extends import_smithy_client23.Command.classBuilder().ep(commonParams2).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde4.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint5.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js
var import_smithy_client24, commands2, STS;
var init_STS = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() {
    import_smithy_client24 = __toESM(require_dist_cjs23());
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
    init_STSClient();
    commands2 = {
      AssumeRoleCommand,
      AssumeRoleWithWebIdentityCommand
    };
    STS = class extends STSClient {
    };
    (0, import_smithy_client24.createAggregatedClient)(commands2, STS);
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js
var init_commands2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() {
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js
var init_models2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js"() {
    init_models_02();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
var init_defaultStsRoleAssumers = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
    init_client();
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
    ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
    getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
      if (typeof (assumedRoleUser == null ? void 0 : assumedRoleUser.Arn) === "string") {
        const arnComponents = assumedRoleUser.Arn.split(":");
        if (arnComponents.length > 4 && arnComponents[4] !== "") {
          return arnComponents[4];
        }
      }
      return void 0;
    };
    resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
      var _a2;
      const region = typeof _region === "function" ? await _region() : _region;
      const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
      (_a2 = credentialProviderLogger == null ? void 0 : credentialProviderLogger.debug) == null ? void 0 : _a2.call(credentialProviderLogger, "@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
      return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
    };
    getDefaultRoleAssumer = (stsOptions, STSClient2) => {
      let stsClient;
      let closureSourceCreds;
      return async (sourceCreds, params) => {
        var _a2, _b, _c, _d;
        closureSourceCreds = sourceCreds;
        if (!stsClient) {
          const { logger: logger3 = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger, region, requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new STSClient2({
            profile: (_d = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _d.profile,
            credentialDefaultProvider: () => async () => closureSourceCreds,
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger3
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        const credentials2 = {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
        setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE", "i");
        return credentials2;
      };
    };
    getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => {
      let stsClient;
      return async (params) => {
        var _a2, _b, _c, _d;
        if (!stsClient) {
          const { logger: logger3 = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger, region, requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new STSClient2({
            profile: (_d = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _d.profile,
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger3
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        const credentials2 = {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
        if (accountId) {
          setCredentialFeature(credentials2, "RESOLVED_ACCOUNT_ID", "T");
        }
        setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
        return credentials2;
      };
    };
    isH2 = (requestHandler) => {
      var _a2;
      return ((_a2 = requestHandler == null ? void 0 : requestHandler.metadata) == null ? void 0 : _a2.handlerProtocol) === "h2";
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js
var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
var init_defaultRoleAssumers = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() {
    init_defaultStsRoleAssumers();
    init_STSClient();
    getCustomizableStsClientCtor = (baseCtor, customizations) => {
      if (!customizations)
        return baseCtor;
      else
        return class CustomizableSTSClient extends baseCtor {
          constructor(config) {
            super(config);
            for (const customization of customizations) {
              this.middlewareStack.use(customization);
            }
          }
        };
    };
    getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    decorateDefaultCredentialProvider = (provider) => (input) => provider({
      roleAssumer: getDefaultRoleAssumer2(input),
      roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
      ...input
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js
var sts_exports = {};
__export(sts_exports, {
  AssumeRoleCommand: () => AssumeRoleCommand,
  AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
  AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
  AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
  AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
  CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
  ExpiredTokenException: () => ExpiredTokenException2,
  IDPCommunicationErrorException: () => IDPCommunicationErrorException,
  IDPRejectedClaimException: () => IDPRejectedClaimException,
  InvalidIdentityTokenException: () => InvalidIdentityTokenException,
  MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
  PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
  RegionDisabledException: () => RegionDisabledException,
  STS: () => STS,
  STSClient: () => STSClient,
  STSServiceException: () => STSServiceException,
  __Client: () => import_smithy_client18.Client,
  decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
  getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
  getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
});
var init_sts = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() {
    init_STSClient();
    init_STS();
    init_commands2();
    init_models2();
    init_defaultRoleAssumers();
    init_STSServiceException();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js
var require_dist_cjs47 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      fromProcess: () => fromProcess
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_shared_ini_file_loader = require_dist_cjs28();
    var import_property_provider2 = require_dist_cjs20();
    var import_child_process = require("child_process");
    var import_util4 = require("util");
    var import_client3 = (init_client(), __toCommonJS(client_exports));
    var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => {
      var _a2;
      if (data.Version !== 1) {
        throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
      }
      if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) {
        throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
      }
      if (data.Expiration) {
        const currentTime = /* @__PURE__ */ new Date();
        const expireTime = new Date(data.Expiration);
        if (expireTime < currentTime) {
          throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
        }
      }
      let accountId = data.AccountId;
      if (!accountId && ((_a2 = profiles == null ? void 0 : profiles[profileName]) == null ? void 0 : _a2.aws_account_id)) {
        accountId = profiles[profileName].aws_account_id;
      }
      const credentials2 = {
        accessKeyId: data.AccessKeyId,
        secretAccessKey: data.SecretAccessKey,
        ...data.SessionToken && { sessionToken: data.SessionToken },
        ...data.Expiration && { expiration: new Date(data.Expiration) },
        ...data.CredentialScope && { credentialScope: data.CredentialScope },
        ...accountId && { accountId }
      };
      (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_PROCESS", "w");
      return credentials2;
    }, "getValidatedProcessCredentials");
    var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger3) => {
      const profile = profiles[profileName];
      if (profiles[profileName]) {
        const credentialProcess = profile["credential_process"];
        if (credentialProcess !== void 0) {
          const execPromise = (0, import_util4.promisify)(import_child_process.exec);
          try {
            const { stdout } = await execPromise(credentialProcess);
            let data;
            try {
              data = JSON.parse(stdout.trim());
            } catch {
              throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
            }
            return getValidatedProcessCredentials(profileName, data, profiles);
          } catch (error2) {
            throw new import_property_provider2.CredentialsProviderError(error2.message, { logger: logger3 });
          }
        } else {
          throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger3 });
        }
      } else {
        throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
          logger: logger3
        });
      }
    }, "resolveProcessCredentials");
    var fromProcess = /* @__PURE__ */ __name((init2 = {}) => async ({ callerClientConfig } = {}) => {
      var _a2;
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-process - fromProcess");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      return resolveProcessCredentials(
        (0, import_shared_ini_file_loader.getProfileName)({
          profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
        }),
        profiles,
        init2.logger
      );
    }, "fromProcess");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js
var require_fromWebToken = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar = [];
          for (var k3 in o4) if (Object.prototype.hasOwnProperty.call(o4, k3)) ar[ar.length] = k3;
          return ar;
        };
        return ownKeys2(o3);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k3 = ownKeys2(mod), i4 = 0; i4 < k3.length; i4++) if (k3[i4] !== "default") __createBinding2(result, mod, k3[i4]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    }();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromWebToken = void 0;
    var fromWebToken2 = (init2) => async (awsIdentityProperties) => {
      var _a2;
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
      const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy5, durationSeconds } = init2;
      let { roleAssumerWithWebIdentity } = init2;
      if (!roleAssumerWithWebIdentity) {
        const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => __importStar2((init_sts(), __toCommonJS(sts_exports))));
        roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
          ...init2.clientConfig,
          credentialProviderLogger: init2.logger,
          parentClientConfig: {
            ...awsIdentityProperties == null ? void 0 : awsIdentityProperties.callerClientConfig,
            ...init2.parentClientConfig
          }
        }, init2.clientPlugins);
      }
      return roleAssumerWithWebIdentity({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
        WebIdentityToken: webIdentityToken,
        ProviderId: providerId,
        PolicyArns: policyArns,
        Policy: policy5,
        DurationSeconds: durationSeconds
      });
    };
    exports2.fromWebToken = fromWebToken2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js
var require_fromTokenFile = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromTokenFile = void 0;
    var client_1 = (init_client(), __toCommonJS(client_exports));
    var property_provider_1 = require_dist_cjs20();
    var fs_1 = require("fs");
    var fromWebToken_1 = require_fromWebToken();
    var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
    var ENV_ROLE_ARN = "AWS_ROLE_ARN";
    var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
    var fromTokenFile2 = (init2 = {}) => async () => {
      var _a2;
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
      const webIdentityTokenFile = (init2 == null ? void 0 : init2.webIdentityTokenFile) ?? process.env[ENV_TOKEN_FILE];
      const roleArn = (init2 == null ? void 0 : init2.roleArn) ?? process.env[ENV_ROLE_ARN];
      const roleSessionName = (init2 == null ? void 0 : init2.roleSessionName) ?? process.env[ENV_ROLE_SESSION_NAME];
      if (!webIdentityTokenFile || !roleArn) {
        throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", {
          logger: init2.logger
        });
      }
      const credentials2 = await (0, fromWebToken_1.fromWebToken)({
        ...init2,
        webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
        roleArn,
        roleSessionName
      })();
      if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
        (0, client_1.setCredentialFeature)(credentials2, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
      }
      return credentials2;
    };
    exports2.fromTokenFile = fromTokenFile2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js
var require_dist_cjs48 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    module2.exports = __toCommonJS2(index_exports);
    __reExport(index_exports, require_fromTokenFile(), module2.exports);
    __reExport(index_exports, require_fromWebToken(), module2.exports);
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
var require_dist_cjs49 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      fromIni: () => fromIni
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_shared_ini_file_loader = require_dist_cjs28();
    var import_client3 = (init_client(), __toCommonJS(client_exports));
    var import_property_provider2 = require_dist_cjs20();
    var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger3) => {
      const sourceProvidersMap = {
        EcsContainer: /* @__PURE__ */ __name(async (options) => {
          const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs38()));
          const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
          logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
          return async () => (0, import_property_provider2.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);
        }, "EcsContainer"),
        Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => {
          logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
          const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
          return async () => fromInstanceMetadata(options)().then(setNamedProvider);
        }, "Ec2InstanceMetadata"),
        Environment: /* @__PURE__ */ __name(async (options) => {
          logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
          const { fromEnv } = await Promise.resolve().then(() => __toESM3(require_dist_cjs36()));
          return async () => fromEnv(options)().then(setNamedProvider);
        }, "Environment")
      };
      if (credentialSource in sourceProvidersMap) {
        return sourceProvidersMap[credentialSource];
      } else {
        throw new import_property_provider2.CredentialsProviderError(
          `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,
          { logger: logger3 }
        );
      }
    }, "resolveCredentialSource");
    var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider");
    var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger: logger3 } = {}) => {
      return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger3 }) || isCredentialSourceProfile(arg, { profile, logger: logger3 }));
    }, "isAssumeRoleProfile");
    var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger3 }) => {
      var _a2;
      const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
      if (withSourceProfile) {
        (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, `    ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
      }
      return withSourceProfile;
    }, "isAssumeRoleWithSourceProfile");
    var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger3 }) => {
      var _a2;
      const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
      if (withProviderProfile) {
        (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, `    ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
      }
      return withProviderProfile;
    }, "isCredentialSourceProfile");
    var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
      var _a2, _b, _c;
      (_a2 = options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
      const profileData = profiles[profileName];
      const { source_profile, region } = profileData;
      if (!options.roleAssumer) {
        const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => __toESM3((init_sts(), __toCommonJS(sts_exports))));
        options.roleAssumer = getDefaultRoleAssumer3(
          {
            ...options.clientConfig,
            credentialProviderLogger: options.logger,
            parentClientConfig: {
              ...options == null ? void 0 : options.parentClientConfig,
              region: region ?? ((_b = options == null ? void 0 : options.parentClientConfig) == null ? void 0 : _b.region)
            }
          },
          options.clientPlugins
        );
      }
      if (source_profile && source_profile in visitedProfiles) {
        throw new import_property_provider2.CredentialsProviderError(
          `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "),
          { logger: options.logger }
        );
      }
      (_c = options.logger) == null ? void 0 : _c.debug(
        `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`
      );
      const sourceCredsProvider = source_profile ? resolveProfileData(
        source_profile,
        profiles,
        options,
        {
          ...visitedProfiles,
          [source_profile]: true
        },
        isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})
      ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();
      if (isCredentialSourceWithoutRoleArn(profileData)) {
        return sourceCredsProvider.then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
      } else {
        const params = {
          RoleArn: profileData.role_arn,
          RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
          ExternalId: profileData.external_id,
          DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
        };
        const { mfa_serial } = profileData;
        if (mfa_serial) {
          if (!options.mfaCodeProvider) {
            throw new import_property_provider2.CredentialsProviderError(
              `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`,
              { logger: options.logger, tryNextLink: false }
            );
          }
          params.SerialNumber = mfa_serial;
          params.TokenCode = await options.mfaCodeProvider(mfa_serial);
        }
        const sourceCreds = await sourceCredsProvider;
        return options.roleAssumer(sourceCreds, params).then(
          (creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")
        );
      }
    }, "resolveAssumeRoleCredentials");
    var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => {
      return !section.role_arn && !!section.credential_source;
    }, "isCredentialSourceWithoutRoleArn");
    var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile");
    var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM3(require_dist_cjs47())).then(
      ({ fromProcess }) => fromProcess({
        ...options,
        profile
      })().then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))
    ), "resolveProcessCredentials");
    var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => {
      const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs46()));
      return fromSSO({
        profile,
        logger: options.logger,
        parentClientConfig: options.parentClientConfig,
        clientConfig: options.clientConfig
      })().then((creds) => {
        if (profileData.sso_session) {
          return (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r");
        } else {
          return (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
        }
      });
    }, "resolveSsoCredentials");
    var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
    var isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile");
    var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => {
      var _a2;
      (_a2 = options == null ? void 0 : options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
      const credentials2 = {
        accessKeyId: profile.aws_access_key_id,
        secretAccessKey: profile.aws_secret_access_key,
        sessionToken: profile.aws_session_token,
        ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope },
        ...profile.aws_account_id && { accountId: profile.aws_account_id }
      };
      return (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_PROFILE", "n");
    }, "resolveStaticCredentials");
    var isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile");
    var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM3(require_dist_cjs48())).then(
      ({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({
        webIdentityTokenFile: profile.web_identity_token_file,
        roleArn: profile.role_arn,
        roleSessionName: profile.role_session_name,
        roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,
        logger: options.logger,
        parentClientConfig: options.parentClientConfig
      })().then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))
    ), "resolveWebIdentityCredentials");
    var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
      const data = profiles[profileName];
      if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {
        return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
      }
      if (isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isWebIdentityProfile(data)) {
        return resolveWebIdentityCredentials(data, options);
      }
      if (isProcessProfile(data)) {
        return resolveProcessCredentials(options, profileName);
      }
      if (isSsoProfile(data)) {
        return await resolveSsoCredentials(profileName, data, options);
      }
      throw new import_property_provider2.CredentialsProviderError(
        `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`,
        { logger: options.logger }
      );
    }, "resolveProfileData");
    var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
      var _a2;
      const init2 = {
        ..._init,
        parentClientConfig: {
          ...callerClientConfig,
          ..._init.parentClientConfig
        }
      };
      (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - fromIni");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      return resolveProfileData(
        (0, import_shared_ini_file_loader.getProfileName)({
          profile: _init.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
        }),
        profiles,
        init2
      );
    }, "fromIni");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
var require_dist_cjs50 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      credentialsTreatedAsExpired: () => credentialsTreatedAsExpired,
      credentialsWillNeedRefresh: () => credentialsWillNeedRefresh,
      defaultProvider: () => defaultProvider
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_credential_provider_env = require_dist_cjs36();
    var import_shared_ini_file_loader = require_dist_cjs28();
    var import_property_provider2 = require_dist_cjs20();
    var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    var remoteProvider = /* @__PURE__ */ __name(async (init2) => {
      var _a2, _b;
      const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
      if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {
        (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
        const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs38()));
        return (0, import_property_provider2.chain)(fromHttp(init2), fromContainerMetadata(init2));
      }
      if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") {
        return async () => {
          throw new import_property_provider2.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger });
        };
      }
      (_b = init2.logger) == null ? void 0 : _b.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
      return fromInstanceMetadata(init2);
    }, "remoteProvider");
    var multipleCredentialSourceWarningEmitted = false;
    var defaultProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider2.memoize)(
      (0, import_property_provider2.chain)(
        async () => {
          var _a2, _b, _c, _d;
          const profile = init2.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE];
          if (profile) {
            const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET];
            if (envStaticCredentialsAreSet) {
              if (!multipleCredentialSourceWarningEmitted) {
                const warnFn = ((_a2 = init2.logger) == null ? void 0 : _a2.warn) && ((_c = (_b = init2.logger) == null ? void 0 : _b.constructor) == null ? void 0 : _c.name) !== "NoOpLogger" ? init2.logger.warn : console.warn;
                warnFn(
                  `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
    Multiple credential sources detected: 
    Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
    This SDK will proceed with the AWS_PROFILE value.
    
    However, a future version may change this behavior to prefer the ENV static credentials.
    Please ensure that your environment only sets either the AWS_PROFILE or the
    AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
`
                );
                multipleCredentialSourceWarningEmitted = true;
              }
            }
            throw new import_property_provider2.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
              logger: init2.logger,
              tryNextLink: true
            });
          }
          (_d = init2.logger) == null ? void 0 : _d.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
          return (0, import_credential_provider_env.fromEnv)(init2)();
        },
        async () => {
          var _a2;
          (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
          const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
          if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
            throw new import_property_provider2.CredentialsProviderError(
              "Skipping SSO provider in default chain (inputs do not include SSO fields).",
              { logger: init2.logger }
            );
          }
          const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs46()));
          return fromSSO(init2)();
        },
        async () => {
          var _a2;
          (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
          const { fromIni } = await Promise.resolve().then(() => __toESM3(require_dist_cjs49()));
          return fromIni(init2)();
        },
        async () => {
          var _a2;
          (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
          const { fromProcess } = await Promise.resolve().then(() => __toESM3(require_dist_cjs47()));
          return fromProcess(init2)();
        },
        async () => {
          var _a2;
          (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
          const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => __toESM3(require_dist_cjs48()));
          return fromTokenFile2(init2)();
        },
        async () => {
          var _a2;
          (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
          return (await remoteProvider(init2))();
        },
        async () => {
          throw new import_property_provider2.CredentialsProviderError("Could not load credentials from any providers", {
            tryNextLink: false,
            logger: init2.logger
          });
        }
      ),
      credentialsTreatedAsExpired,
      credentialsWillNeedRefresh
    ), "defaultProvider");
    var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0, "credentialsWillNeedRefresh");
    var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js
var require_ruleset2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var s4 = "required";
    var t4 = "fn";
    var u3 = "argv";
    var v6 = "ref";
    var a3 = true;
    var b3 = "isSet";
    var c3 = "booleanEquals";
    var d3 = "error";
    var e4 = "endpoint";
    var f5 = "tree";
    var g3 = "PartitionResult";
    var h4 = { [s4]: false, "type": "String" };
    var i4 = { [s4]: true, "default": false, "type": "Boolean" };
    var j3 = { [v6]: "Endpoint" };
    var k3 = { [t4]: c3, [u3]: [{ [v6]: "UseFIPS" }, true] };
    var l3 = { [t4]: c3, [u3]: [{ [v6]: "UseDualStack" }, true] };
    var m4 = {};
    var n3 = { [t4]: "getAttr", [u3]: [{ [v6]: g3 }, "supportsFIPS"] };
    var o3 = { [t4]: c3, [u3]: [true, { [t4]: "getAttr", [u3]: [{ [v6]: g3 }, "supportsDualStack"] }] };
    var p3 = [k3];
    var q3 = [l3];
    var r4 = [{ [v6]: "Region" }];
    var _data3 = { version: "1.0", parameters: { Region: h4, UseDualStack: i4, UseFIPS: i4, Endpoint: h4 }, rules: [{ conditions: [{ [t4]: b3, [u3]: [j3] }], rules: [{ conditions: p3, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, { conditions: q3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d3 }, { endpoint: { url: j3, properties: m4, headers: m4 }, type: e4 }], type: f5 }, { conditions: [{ [t4]: b3, [u3]: r4 }], rules: [{ conditions: [{ [t4]: "aws.partition", [u3]: r4, assign: g3 }], rules: [{ conditions: [k3, l3], rules: [{ conditions: [{ [t4]: c3, [u3]: [a3, n3] }, o3], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d3 }], type: f5 }, { conditions: p3, rules: [{ conditions: [{ [t4]: c3, [u3]: [n3, a3] }], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d3 }], type: f5 }, { conditions: q3, rules: [{ conditions: [o3], rules: [{ endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d3 }], type: f5 }, { endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }], type: f5 }, { error: "Invalid Configuration: Missing Region", type: d3 }] };
    exports2.ruleSet = _data3;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs19();
    var util_endpoints_2 = require_dist_cjs18();
    var ruleset_1 = require_ruleset2();
    var cache3 = new util_endpoints_2.EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    var defaultEndpointResolver3 = (endpointParams, context = {}) => {
      return cache3.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      }));
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver3;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var smithy_client_1 = require_dist_cjs23();
    var url_parser_1 = require_dist_cjs31();
    var util_base64_1 = require_dist_cjs11();
    var util_utf8_1 = require_dist_cjs10();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider();
    var endpointResolver_1 = require_endpointResolver2();
    var getRuntimeConfig5 = (config) => {
      return {
        apiVersion: "2018-08-01",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultRDSDataHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "RDS Data",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js
var require_runtimeConfig2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package2());
    var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var credential_provider_node_1 = require_dist_cjs50();
    var util_user_agent_node_1 = require_dist_cjs39();
    var config_resolver_1 = require_dist_cjs26();
    var hash_node_1 = require_dist_cjs40();
    var middleware_retry_1 = require_dist_cjs35();
    var node_config_provider_1 = require_dist_cjs29();
    var node_http_handler_1 = require_dist_cjs14();
    var util_body_length_node_1 = require_dist_cjs41();
    var util_retry_1 = require_dist_cjs34();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared2();
    var smithy_client_1 = require_dist_cjs23();
    var util_defaults_mode_node_1 = require_dist_cjs42();
    var smithy_client_2 = require_dist_cjs23();
    var getRuntimeConfig5 = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      const loaderConfig = {
        profile: config == null ? void 0 : config.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }, config),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js
var require_dist_cjs51 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var index_exports = {};
    __export2(index_exports, {
      AccessDeniedException: () => AccessDeniedException2,
      ArrayValue: () => ArrayValue,
      BadRequestException: () => BadRequestException,
      BatchExecuteStatementCommand: () => BatchExecuteStatementCommand,
      BeginTransactionCommand: () => BeginTransactionCommand,
      CommitTransactionCommand: () => CommitTransactionCommand,
      DatabaseErrorException: () => DatabaseErrorException,
      DatabaseNotFoundException: () => DatabaseNotFoundException,
      DatabaseResumingException: () => DatabaseResumingException,
      DatabaseUnavailableException: () => DatabaseUnavailableException,
      DecimalReturnType: () => DecimalReturnType,
      ExecuteSqlCommand: () => ExecuteSqlCommand,
      ExecuteStatementCommand: () => ExecuteStatementCommand,
      Field: () => Field,
      ForbiddenException: () => ForbiddenException,
      HttpEndpointNotEnabledException: () => HttpEndpointNotEnabledException,
      InternalServerErrorException: () => InternalServerErrorException,
      InvalidResourceStateException: () => InvalidResourceStateException,
      InvalidSecretException: () => InvalidSecretException,
      LongReturnType: () => LongReturnType,
      NotFoundException: () => NotFoundException,
      RDSData: () => RDSData,
      RDSDataClient: () => RDSDataClient,
      RDSDataServiceException: () => RDSDataServiceException,
      RecordsFormatType: () => RecordsFormatType,
      RollbackTransactionCommand: () => RollbackTransactionCommand,
      SecretsErrorException: () => SecretsErrorException,
      ServiceUnavailableError: () => ServiceUnavailableError,
      StatementTimeoutException: () => StatementTimeoutException,
      TransactionNotFoundException: () => TransactionNotFoundException,
      TypeHint: () => TypeHint,
      UnsupportedResultException: () => UnsupportedResultException,
      Value: () => Value,
      __Client: () => import_smithy_client25.Client
    });
    module2.exports = __toCommonJS2(index_exports);
    var import_middleware_host_header3 = require_dist_cjs3();
    var import_middleware_logger3 = require_dist_cjs4();
    var import_middleware_recursion_detection3 = require_dist_cjs5();
    var import_middleware_user_agent3 = require_dist_cjs24();
    var import_config_resolver5 = require_dist_cjs26();
    var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
    var import_middleware_content_length3 = require_dist_cjs27();
    var import_middleware_endpoint6 = require_dist_cjs32();
    var import_middleware_retry5 = require_dist_cjs35();
    var import_httpAuthSchemeProvider5 = require_httpAuthSchemeProvider();
    var resolveClientEndpointParameters3 = /* @__PURE__ */ __name((options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "rds-data"
      });
    }, "resolveClientEndpointParameters");
    var commonParams3 = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig5 = require_runtimeConfig2();
    var import_region_config_resolver3 = require_dist_cjs43();
    var import_protocol_http15 = require_dist_cjs2();
    var import_smithy_client25 = require_dist_cjs23();
    var getHttpAuthExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var resolveRuntimeExtensions3 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(
        (0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig),
        (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig),
        (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig),
        getHttpAuthExtensionConfiguration3(runtimeConfig)
      );
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(
        runtimeConfig,
        (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration),
        (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        resolveHttpAuthRuntimeConfig3(extensionConfiguration)
      );
    }, "resolveRuntimeExtensions");
    var _a2;
    var RDSDataClient = (_a2 = class extends import_smithy_client25.Client {
      /**
       * The resolved configuration of RDSDataClient class. This is resolved and normalized from the {@link RDSDataClientConfig | constructor configuration interface}.
       */
      config;
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig5.getRuntimeConfig)(configuration || {});
        super(_config_0);
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters3(_config_0);
        const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1);
        const _config_3 = (0, import_middleware_retry5.resolveRetryConfig)(_config_2);
        const _config_4 = (0, import_config_resolver5.resolveRegionConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_endpoint6.resolveEndpointConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider5.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions3(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_retry5.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core17.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider5.defaultRDSDataHttpAuthSchemeParametersProvider,
            identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core17.DefaultIdentityProviderConfig({
              "aws.auth#sigv4": config.credentials
            }), "identityProviderConfigProvider")
          })
        );
        this.middlewareStack.use((0, import_core17.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
    }, __name(_a2, "RDSDataClient"), _a2);
    var import_middleware_serde5 = require_dist_cjs7();
    var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
    var _a3;
    var RDSDataServiceException = (_a3 = class extends import_smithy_client25.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _a3.prototype);
      }
    }, __name(_a3, "RDSDataServiceException"), _a3);
    var _a4;
    var AccessDeniedException2 = (_a4 = class extends RDSDataServiceException {
      name = "AccessDeniedException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a4.prototype);
      }
    }, __name(_a4, "AccessDeniedException"), _a4);
    var _a5;
    var BadRequestException = (_a5 = class extends RDSDataServiceException {
      name = "BadRequestException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "BadRequestException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a5.prototype);
      }
    }, __name(_a5, "BadRequestException"), _a5);
    var TypeHint = {
      DATE: "DATE",
      DECIMAL: "DECIMAL",
      JSON: "JSON",
      TIME: "TIME",
      TIMESTAMP: "TIMESTAMP",
      UUID: "UUID"
    };
    var _a6;
    var DatabaseErrorException = (_a6 = class extends RDSDataServiceException {
      name = "DatabaseErrorException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseErrorException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a6.prototype);
      }
    }, __name(_a6, "DatabaseErrorException"), _a6);
    var _a7;
    var DatabaseNotFoundException = (_a7 = class extends RDSDataServiceException {
      name = "DatabaseNotFoundException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseNotFoundException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a7.prototype);
      }
    }, __name(_a7, "DatabaseNotFoundException"), _a7);
    var _a8;
    var DatabaseResumingException = (_a8 = class extends RDSDataServiceException {
      name = "DatabaseResumingException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseResumingException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a8.prototype);
      }
    }, __name(_a8, "DatabaseResumingException"), _a8);
    var _a9;
    var DatabaseUnavailableException = (_a9 = class extends RDSDataServiceException {
      name = "DatabaseUnavailableException";
      $fault = "server";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseUnavailableException",
          $fault: "server",
          ...opts
        });
        Object.setPrototypeOf(this, _a9.prototype);
      }
    }, __name(_a9, "DatabaseUnavailableException"), _a9);
    var _a10;
    var ForbiddenException = (_a10 = class extends RDSDataServiceException {
      name = "ForbiddenException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ForbiddenException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a10.prototype);
      }
    }, __name(_a10, "ForbiddenException"), _a10);
    var _a11;
    var HttpEndpointNotEnabledException = (_a11 = class extends RDSDataServiceException {
      name = "HttpEndpointNotEnabledException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "HttpEndpointNotEnabledException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a11.prototype);
      }
    }, __name(_a11, "HttpEndpointNotEnabledException"), _a11);
    var _a12;
    var InternalServerErrorException = (_a12 = class extends RDSDataServiceException {
      name = "InternalServerErrorException";
      $fault = "server";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InternalServerErrorException",
          $fault: "server",
          ...opts
        });
        Object.setPrototypeOf(this, _a12.prototype);
      }
    }, __name(_a12, "InternalServerErrorException"), _a12);
    var _a13;
    var InvalidResourceStateException = (_a13 = class extends RDSDataServiceException {
      name = "InvalidResourceStateException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidResourceStateException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a13.prototype);
      }
    }, __name(_a13, "InvalidResourceStateException"), _a13);
    var _a14;
    var InvalidSecretException = (_a14 = class extends RDSDataServiceException {
      name = "InvalidSecretException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidSecretException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a14.prototype);
      }
    }, __name(_a14, "InvalidSecretException"), _a14);
    var _a15;
    var SecretsErrorException = (_a15 = class extends RDSDataServiceException {
      name = "SecretsErrorException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "SecretsErrorException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a15.prototype);
      }
    }, __name(_a15, "SecretsErrorException"), _a15);
    var _a16;
    var ServiceUnavailableError = (_a16 = class extends RDSDataServiceException {
      name = "ServiceUnavailableError";
      $fault = "server";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ServiceUnavailableError",
          $fault: "server",
          ...opts
        });
        Object.setPrototypeOf(this, _a16.prototype);
      }
    }, __name(_a16, "ServiceUnavailableError"), _a16);
    var _a17;
    var StatementTimeoutException = (_a17 = class extends RDSDataServiceException {
      name = "StatementTimeoutException";
      $fault = "client";
      /**
       * <p>The database connection ID that executed the SQL statement.</p>
       * @public
       */
      dbConnectionId;
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "StatementTimeoutException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a17.prototype);
        this.dbConnectionId = opts.dbConnectionId;
      }
    }, __name(_a17, "StatementTimeoutException"), _a17);
    var _a18;
    var TransactionNotFoundException = (_a18 = class extends RDSDataServiceException {
      name = "TransactionNotFoundException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "TransactionNotFoundException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a18.prototype);
      }
    }, __name(_a18, "TransactionNotFoundException"), _a18);
    var _a19;
    var NotFoundException = (_a19 = class extends RDSDataServiceException {
      name = "NotFoundException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "NotFoundException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a19.prototype);
      }
    }, __name(_a19, "NotFoundException"), _a19);
    var DecimalReturnType = {
      DOUBLE_OR_LONG: "DOUBLE_OR_LONG",
      STRING: "STRING"
    };
    var RecordsFormatType = {
      JSON: "JSON",
      NONE: "NONE"
    };
    var LongReturnType = {
      LONG: "LONG",
      STRING: "STRING"
    };
    var _a20;
    var UnsupportedResultException = (_a20 = class extends RDSDataServiceException {
      name = "UnsupportedResultException";
      $fault = "client";
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnsupportedResultException",
          $fault: "client",
          ...opts
        });
        Object.setPrototypeOf(this, _a20.prototype);
      }
    }, __name(_a20, "UnsupportedResultException"), _a20);
    var ArrayValue;
    ((ArrayValue2) => {
      ArrayValue2.visit = /* @__PURE__ */ __name((value, visitor) => {
        if (value.booleanValues !== void 0) return visitor.booleanValues(value.booleanValues);
        if (value.longValues !== void 0) return visitor.longValues(value.longValues);
        if (value.doubleValues !== void 0) return visitor.doubleValues(value.doubleValues);
        if (value.stringValues !== void 0) return visitor.stringValues(value.stringValues);
        if (value.arrayValues !== void 0) return visitor.arrayValues(value.arrayValues);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      }, "visit");
    })(ArrayValue || (ArrayValue = {}));
    var Field;
    ((Field2) => {
      Field2.visit = /* @__PURE__ */ __name((value, visitor) => {
        if (value.isNull !== void 0) return visitor.isNull(value.isNull);
        if (value.booleanValue !== void 0) return visitor.booleanValue(value.booleanValue);
        if (value.longValue !== void 0) return visitor.longValue(value.longValue);
        if (value.doubleValue !== void 0) return visitor.doubleValue(value.doubleValue);
        if (value.stringValue !== void 0) return visitor.stringValue(value.stringValue);
        if (value.blobValue !== void 0) return visitor.blobValue(value.blobValue);
        if (value.arrayValue !== void 0) return visitor.arrayValue(value.arrayValue);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      }, "visit");
    })(Field || (Field = {}));
    var Value;
    ((Value3) => {
      Value3.visit = /* @__PURE__ */ __name((value, visitor) => {
        if (value.isNull !== void 0) return visitor.isNull(value.isNull);
        if (value.bitValue !== void 0) return visitor.bitValue(value.bitValue);
        if (value.bigIntValue !== void 0) return visitor.bigIntValue(value.bigIntValue);
        if (value.intValue !== void 0) return visitor.intValue(value.intValue);
        if (value.doubleValue !== void 0) return visitor.doubleValue(value.doubleValue);
        if (value.realValue !== void 0) return visitor.realValue(value.realValue);
        if (value.stringValue !== void 0) return visitor.stringValue(value.stringValue);
        if (value.blobValue !== void 0) return visitor.blobValue(value.blobValue);
        if (value.arrayValues !== void 0) return visitor.arrayValues(value.arrayValues);
        if (value.structValue !== void 0) return visitor.structValue(value.structValue);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      }, "visit");
    })(Value || (Value = {}));
    var se_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/BatchExecute");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          database: [],
          parameterSets: /* @__PURE__ */ __name((_3) => se_SqlParameterSets(_3, context), "parameterSets"),
          resourceArn: [],
          schema: [],
          secretArn: [],
          sql: [],
          transactionId: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_BatchExecuteStatementCommand");
    var se_BeginTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/BeginTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          database: [],
          resourceArn: [],
          schema: [],
          secretArn: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_BeginTransactionCommand");
    var se_CommitTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/CommitTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          resourceArn: [],
          secretArn: [],
          transactionId: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_CommitTransactionCommand");
    var se_ExecuteSqlCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/ExecuteSql");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          awsSecretStoreArn: [],
          database: [],
          dbClusterOrInstanceArn: [],
          schema: [],
          sqlStatements: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_ExecuteSqlCommand");
    var se_ExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/Execute");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          continueAfterTimeout: [],
          database: [],
          formatRecordsAs: [],
          includeResultMetadata: [],
          parameters: /* @__PURE__ */ __name((_3) => se_SqlParametersList(_3, context), "parameters"),
          resourceArn: [],
          resultSetOptions: /* @__PURE__ */ __name((_3) => (0, import_smithy_client25._json)(_3), "resultSetOptions"),
          schema: [],
          secretArn: [],
          sql: [],
          transactionId: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_ExecuteStatementCommand");
    var se_RollbackTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b3 = (0, import_core17.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b3.bp("/RollbackTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client25.take)(input, {
          resourceArn: [],
          secretArn: [],
          transactionId: []
        })
      );
      b3.m("POST").h(headers).b(body);
      return b3.build();
    }, "se_RollbackTransactionCommand");
    var de_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        updateResults: /* @__PURE__ */ __name((_3) => de_UpdateResults(_3, context), "updateResults")
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_BatchExecuteStatementCommand");
    var de_BeginTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        transactionId: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_BeginTransactionCommand");
    var de_CommitTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        transactionStatus: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CommitTransactionCommand");
    var de_ExecuteSqlCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        sqlStatementResults: /* @__PURE__ */ __name((_3) => de_SqlStatementResults(_3, context), "sqlStatementResults")
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ExecuteSqlCommand");
    var de_ExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        columnMetadata: import_smithy_client25._json,
        formattedRecords: import_smithy_client25.expectString,
        generatedFields: /* @__PURE__ */ __name((_3) => de_FieldList(_3, context), "generatedFields"),
        numberOfRecordsUpdated: import_smithy_client25.expectLong,
        records: /* @__PURE__ */ __name((_3) => de_SqlRecords(_3, context), "records")
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ExecuteStatementCommand");
    var de_RollbackTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const contents = (0, import_smithy_client25.map)({
        $metadata: deserializeMetadata3(output)
      });
      const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client25.take)(data, {
        transactionStatus: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_RollbackTransactionCommand");
    var de_CommandError3 = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core22.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core22.loadRestJsonErrorCode)(output, parsedOutput.body);
      switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.rdsdata#AccessDeniedException":
          throw await de_AccessDeniedExceptionRes2(parsedOutput, context);
        case "BadRequestException":
        case "com.amazonaws.rdsdata#BadRequestException":
          throw await de_BadRequestExceptionRes(parsedOutput, context);
        case "DatabaseErrorException":
        case "com.amazonaws.rdsdata#DatabaseErrorException":
          throw await de_DatabaseErrorExceptionRes(parsedOutput, context);
        case "DatabaseNotFoundException":
        case "com.amazonaws.rdsdata#DatabaseNotFoundException":
          throw await de_DatabaseNotFoundExceptionRes(parsedOutput, context);
        case "DatabaseResumingException":
        case "com.amazonaws.rdsdata#DatabaseResumingException":
          throw await de_DatabaseResumingExceptionRes(parsedOutput, context);
        case "DatabaseUnavailableException":
        case "com.amazonaws.rdsdata#DatabaseUnavailableException":
          throw await de_DatabaseUnavailableExceptionRes(parsedOutput, context);
        case "ForbiddenException":
        case "com.amazonaws.rdsdata#ForbiddenException":
          throw await de_ForbiddenExceptionRes(parsedOutput, context);
        case "HttpEndpointNotEnabledException":
        case "com.amazonaws.rdsdata#HttpEndpointNotEnabledException":
          throw await de_HttpEndpointNotEnabledExceptionRes(parsedOutput, context);
        case "InternalServerErrorException":
        case "com.amazonaws.rdsdata#InternalServerErrorException":
          throw await de_InternalServerErrorExceptionRes(parsedOutput, context);
        case "InvalidResourceStateException":
        case "com.amazonaws.rdsdata#InvalidResourceStateException":
          throw await de_InvalidResourceStateExceptionRes(parsedOutput, context);
        case "InvalidSecretException":
        case "com.amazonaws.rdsdata#InvalidSecretException":
          throw await de_InvalidSecretExceptionRes(parsedOutput, context);
        case "SecretsErrorException":
        case "com.amazonaws.rdsdata#SecretsErrorException":
          throw await de_SecretsErrorExceptionRes(parsedOutput, context);
        case "ServiceUnavailableError":
        case "com.amazonaws.rdsdata#ServiceUnavailableError":
          throw await de_ServiceUnavailableErrorRes(parsedOutput, context);
        case "StatementTimeoutException":
        case "com.amazonaws.rdsdata#StatementTimeoutException":
          throw await de_StatementTimeoutExceptionRes(parsedOutput, context);
        case "TransactionNotFoundException":
        case "com.amazonaws.rdsdata#TransactionNotFoundException":
          throw await de_TransactionNotFoundExceptionRes(parsedOutput, context);
        case "NotFoundException":
        case "com.amazonaws.rdsdata#NotFoundException":
          throw await de_NotFoundExceptionRes(parsedOutput, context);
        case "UnsupportedResultException":
        case "com.amazonaws.rdsdata#UnsupportedResultException":
          throw await de_UnsupportedResultExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError3({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError3 = (0, import_smithy_client25.withBaseException)(RDSDataServiceException);
    var de_AccessDeniedExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException2({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AccessDeniedExceptionRes");
    var de_BadRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new BadRequestException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_BadRequestExceptionRes");
    var de_DatabaseErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseErrorException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseErrorExceptionRes");
    var de_DatabaseNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseNotFoundException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseNotFoundExceptionRes");
    var de_DatabaseResumingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseResumingException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseResumingExceptionRes");
    var de_DatabaseUnavailableExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {});
      Object.assign(contents, doc);
      const exception = new DatabaseUnavailableException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseUnavailableExceptionRes");
    var de_ForbiddenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new ForbiddenException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ForbiddenExceptionRes");
    var de_HttpEndpointNotEnabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new HttpEndpointNotEnabledException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_HttpEndpointNotEnabledExceptionRes");
    var de_InternalServerErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {});
      Object.assign(contents, doc);
      const exception = new InternalServerErrorException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InternalServerErrorExceptionRes");
    var de_InvalidResourceStateExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidResourceStateException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidResourceStateExceptionRes");
    var de_InvalidSecretExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidSecretException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidSecretExceptionRes");
    var de_NotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new NotFoundException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_NotFoundExceptionRes");
    var de_SecretsErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new SecretsErrorException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_SecretsErrorExceptionRes");
    var de_ServiceUnavailableErrorRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {});
      Object.assign(contents, doc);
      const exception = new ServiceUnavailableError({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ServiceUnavailableErrorRes");
    var de_StatementTimeoutExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        dbConnectionId: import_smithy_client25.expectLong,
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new StatementTimeoutException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_StatementTimeoutExceptionRes");
    var de_TransactionNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new TransactionNotFoundException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_TransactionNotFoundExceptionRes");
    var de_UnsupportedResultExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client25.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client25.take)(data, {
        message: import_smithy_client25.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedResultException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnsupportedResultExceptionRes");
    var se_ArrayOfArray = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e4) => e4 != null).map((entry) => {
        return se_ArrayValue(entry, context);
      });
    }, "se_ArrayOfArray");
    var se_ArrayValue = /* @__PURE__ */ __name((input, context) => {
      return ArrayValue.visit(input, {
        arrayValues: /* @__PURE__ */ __name((value) => ({ arrayValues: se_ArrayOfArray(value, context) }), "arrayValues"),
        booleanValues: /* @__PURE__ */ __name((value) => ({ booleanValues: (0, import_smithy_client25._json)(value) }), "booleanValues"),
        doubleValues: /* @__PURE__ */ __name((value) => ({ doubleValues: se_DoubleArray(value, context) }), "doubleValues"),
        longValues: /* @__PURE__ */ __name((value) => ({ longValues: (0, import_smithy_client25._json)(value) }), "longValues"),
        stringValues: /* @__PURE__ */ __name((value) => ({ stringValues: (0, import_smithy_client25._json)(value) }), "stringValues"),
        _: /* @__PURE__ */ __name((name, value) => ({ [name]: value }), "_")
      });
    }, "se_ArrayValue");
    var se_DoubleArray = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e4) => e4 != null).map((entry) => {
        return (0, import_smithy_client25.serializeFloat)(entry);
      });
    }, "se_DoubleArray");
    var se_Field = /* @__PURE__ */ __name((input, context) => {
      return Field.visit(input, {
        arrayValue: /* @__PURE__ */ __name((value) => ({ arrayValue: se_ArrayValue(value, context) }), "arrayValue"),
        blobValue: /* @__PURE__ */ __name((value) => ({ blobValue: context.base64Encoder(value) }), "blobValue"),
        booleanValue: /* @__PURE__ */ __name((value) => ({ booleanValue: value }), "booleanValue"),
        doubleValue: /* @__PURE__ */ __name((value) => ({ doubleValue: (0, import_smithy_client25.serializeFloat)(value) }), "doubleValue"),
        isNull: /* @__PURE__ */ __name((value) => ({ isNull: value }), "isNull"),
        longValue: /* @__PURE__ */ __name((value) => ({ longValue: value }), "longValue"),
        stringValue: /* @__PURE__ */ __name((value) => ({ stringValue: value }), "stringValue"),
        _: /* @__PURE__ */ __name((name, value) => ({ [name]: value }), "_")
      });
    }, "se_Field");
    var se_SqlParameter = /* @__PURE__ */ __name((input, context) => {
      return (0, import_smithy_client25.take)(input, {
        name: [],
        typeHint: [],
        value: /* @__PURE__ */ __name((_3) => se_Field(_3, context), "value")
      });
    }, "se_SqlParameter");
    var se_SqlParameterSets = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e4) => e4 != null).map((entry) => {
        return se_SqlParametersList(entry, context);
      });
    }, "se_SqlParameterSets");
    var se_SqlParametersList = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e4) => e4 != null).map((entry) => {
        return se_SqlParameter(entry, context);
      });
    }, "se_SqlParametersList");
    var de_ArrayOfArray = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_ArrayValue((0, import_core22.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_ArrayOfArray");
    var de_ArrayValue = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayOfArray(output.arrayValues, context)
        };
      }
      if (output.booleanValues != null) {
        return {
          booleanValues: (0, import_smithy_client25._json)(output.booleanValues)
        };
      }
      if (output.doubleValues != null) {
        return {
          doubleValues: de_DoubleArray(output.doubleValues, context)
        };
      }
      if (output.longValues != null) {
        return {
          longValues: (0, import_smithy_client25._json)(output.longValues)
        };
      }
      if (output.stringValues != null) {
        return {
          stringValues: (0, import_smithy_client25._json)(output.stringValues)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_ArrayValue");
    var de_ArrayValueList = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_Value((0, import_core22.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_ArrayValueList");
    var de_DoubleArray = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return (0, import_smithy_client25.limitedParseDouble)(entry);
      });
      return retVal;
    }, "de_DoubleArray");
    var de_Field = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValue != null) {
        return {
          arrayValue: de_ArrayValue((0, import_core22.awsExpectUnion)(output.arrayValue), context)
        };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if ((0, import_smithy_client25.expectBoolean)(output.booleanValue) !== void 0) {
        return { booleanValue: (0, import_smithy_client25.expectBoolean)(output.booleanValue) };
      }
      if ((0, import_smithy_client25.limitedParseDouble)(output.doubleValue) !== void 0) {
        return { doubleValue: (0, import_smithy_client25.limitedParseDouble)(output.doubleValue) };
      }
      if ((0, import_smithy_client25.expectBoolean)(output.isNull) !== void 0) {
        return { isNull: (0, import_smithy_client25.expectBoolean)(output.isNull) };
      }
      if ((0, import_smithy_client25.expectLong)(output.longValue) !== void 0) {
        return { longValue: (0, import_smithy_client25.expectLong)(output.longValue) };
      }
      if ((0, import_smithy_client25.expectString)(output.stringValue) !== void 0) {
        return { stringValue: (0, import_smithy_client25.expectString)(output.stringValue) };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_Field");
    var de_FieldList = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_Field((0, import_core22.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_FieldList");
    var de__Record = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client25.take)(output, {
        values: /* @__PURE__ */ __name((_3) => de_Row(_3, context), "values")
      });
    }, "de__Record");
    var de_Records = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de__Record(entry, context);
      });
      return retVal;
    }, "de_Records");
    var de_ResultFrame = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client25.take)(output, {
        records: /* @__PURE__ */ __name((_3) => de_Records(_3, context), "records"),
        resultSetMetadata: import_smithy_client25._json
      });
    }, "de_ResultFrame");
    var de_Row = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_Value((0, import_core22.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_Row");
    var de_SqlRecords = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_FieldList(entry, context);
      });
      return retVal;
    }, "de_SqlRecords");
    var de_SqlStatementResult = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client25.take)(output, {
        numberOfRecordsUpdated: import_smithy_client25.expectLong,
        resultFrame: /* @__PURE__ */ __name((_3) => de_ResultFrame(_3, context), "resultFrame")
      });
    }, "de_SqlStatementResult");
    var de_SqlStatementResults = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_SqlStatementResult(entry, context);
      });
      return retVal;
    }, "de_SqlStatementResults");
    var de_StructValue = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client25.take)(output, {
        attributes: /* @__PURE__ */ __name((_3) => de_ArrayValueList(_3, context), "attributes")
      });
    }, "de_StructValue");
    var de_UpdateResult = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client25.take)(output, {
        generatedFields: /* @__PURE__ */ __name((_3) => de_FieldList(_3, context), "generatedFields")
      });
    }, "de_UpdateResult");
    var de_UpdateResults = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
        return de_UpdateResult(entry, context);
      });
      return retVal;
    }, "de_UpdateResults");
    var de_Value = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayValueList(output.arrayValues, context)
        };
      }
      if ((0, import_smithy_client25.expectLong)(output.bigIntValue) !== void 0) {
        return { bigIntValue: (0, import_smithy_client25.expectLong)(output.bigIntValue) };
      }
      if ((0, import_smithy_client25.expectBoolean)(output.bitValue) !== void 0) {
        return { bitValue: (0, import_smithy_client25.expectBoolean)(output.bitValue) };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if ((0, import_smithy_client25.limitedParseDouble)(output.doubleValue) !== void 0) {
        return { doubleValue: (0, import_smithy_client25.limitedParseDouble)(output.doubleValue) };
      }
      if ((0, import_smithy_client25.expectInt32)(output.intValue) !== void 0) {
        return { intValue: (0, import_smithy_client25.expectInt32)(output.intValue) };
      }
      if ((0, import_smithy_client25.expectBoolean)(output.isNull) !== void 0) {
        return { isNull: (0, import_smithy_client25.expectBoolean)(output.isNull) };
      }
      if ((0, import_smithy_client25.limitedParseFloat32)(output.realValue) !== void 0) {
        return { realValue: (0, import_smithy_client25.limitedParseFloat32)(output.realValue) };
      }
      if ((0, import_smithy_client25.expectString)(output.stringValue) !== void 0) {
        return { stringValue: (0, import_smithy_client25.expectString)(output.stringValue) };
      }
      if (output.structValue != null) {
        return {
          structValue: de_StructValue(output.structValue, context)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_Value");
    var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    }), "deserializeMetadata");
    var _a21;
    var BatchExecuteStatementCommand = (_a21 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BatchExecuteStatement", {}).n("RDSDataClient", "BatchExecuteStatementCommand").f(void 0, void 0).ser(se_BatchExecuteStatementCommand).de(de_BatchExecuteStatementCommand).build() {
    }, __name(_a21, "BatchExecuteStatementCommand"), _a21);
    var _a22;
    var BeginTransactionCommand = (_a22 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BeginTransaction", {}).n("RDSDataClient", "BeginTransactionCommand").f(void 0, void 0).ser(se_BeginTransactionCommand).de(de_BeginTransactionCommand).build() {
    }, __name(_a22, "BeginTransactionCommand"), _a22);
    var _a23;
    var CommitTransactionCommand = (_a23 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "CommitTransaction", {}).n("RDSDataClient", "CommitTransactionCommand").f(void 0, void 0).ser(se_CommitTransactionCommand).de(de_CommitTransactionCommand).build() {
    }, __name(_a23, "CommitTransactionCommand"), _a23);
    var _a24;
    var ExecuteSqlCommand = (_a24 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteSql", {}).n("RDSDataClient", "ExecuteSqlCommand").f(void 0, void 0).ser(se_ExecuteSqlCommand).de(de_ExecuteSqlCommand).build() {
    }, __name(_a24, "ExecuteSqlCommand"), _a24);
    var _a25;
    var ExecuteStatementCommand = (_a25 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteStatement", {}).n("RDSDataClient", "ExecuteStatementCommand").f(void 0, void 0).ser(se_ExecuteStatementCommand).de(de_ExecuteStatementCommand).build() {
    }, __name(_a25, "ExecuteStatementCommand"), _a25);
    var _a26;
    var RollbackTransactionCommand = (_a26 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
      return [
        (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "RollbackTransaction", {}).n("RDSDataClient", "RollbackTransactionCommand").f(void 0, void 0).ser(se_RollbackTransactionCommand).de(de_RollbackTransactionCommand).build() {
    }, __name(_a26, "RollbackTransactionCommand"), _a26);
    var commands3 = {
      BatchExecuteStatementCommand,
      BeginTransactionCommand,
      CommitTransactionCommand,
      ExecuteSqlCommand,
      ExecuteStatementCommand,
      RollbackTransactionCommand
    };
    var _a27;
    var RDSData = (_a27 = class extends RDSDataClient {
    }, __name(_a27, "RDSData"), _a27);
    (0, import_smithy_client25.createAggregatedClient)(commands3, RDSData);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js
var require_chars = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.$v = exports2.$s = exports2.$r = exports2.$p = exports2.$o = exports2.$n = exports2.$m = exports2.$j = exports2.$b = exports2.$Z = exports2.$Y = exports2.$X = exports2.$V = exports2.$T = exports2.$S = exports2.$R = exports2.$Q = exports2.$P = exports2.$O = exports2.$M = exports2.$L = exports2.$K = exports2.$I = exports2.$H = exports2.$E = exports2.$D = exports2.$C = exports2.$A = exports2.$1 = exports2.$0 = void 0;
    exports2.ord = ord;
    exports2.chr = chr;
    exports2.$0 = ord("0");
    exports2.$1 = ord("1");
    exports2.$A = ord("A");
    exports2.$C = ord("C");
    exports2.$D = ord("D");
    exports2.$E = ord("E");
    exports2.$H = ord("H");
    exports2.$I = ord("I");
    exports2.$K = ord("K");
    exports2.$L = ord("L");
    exports2.$M = ord("M");
    exports2.$O = ord("O");
    exports2.$P = ord("P");
    exports2.$Q = ord("Q");
    exports2.$R = ord("R");
    exports2.$S = ord("S");
    exports2.$T = ord("T");
    exports2.$V = ord("V");
    exports2.$X = ord("X");
    exports2.$Y = ord("Y");
    exports2.$Z = ord("Z");
    exports2.$b = ord("b");
    exports2.$j = ord("j");
    exports2.$m = ord("m");
    exports2.$n = ord("n");
    exports2.$o = ord("o");
    exports2.$p = ord("p");
    exports2.$r = ord("r");
    exports2.$s = ord("s");
    exports2.$v = ord("v");
    function ord(str) {
      const ch = str.charCodeAt(0);
      if (ch <= 0 || ch >= 255) {
        throw new TypeError(`char "${ch}" is outside ASCII`);
      }
      return ch & 255;
    }
    function chr(ch) {
      if (ch <= 0 || ch >= 255) {
        throw new TypeError(`char "${ch}" is outside ASCII`);
      }
      return String.fromCharCode(ch);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js
var require_buffer = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReadBuffer = exports2.ReadMessageBuffer = exports2.WriteMessageBuffer = exports2.WriteBuffer = exports2.BufferError = exports2.encodeB64 = exports2.decodeB64 = exports2.utf8Decoder = exports2.utf8Encoder = void 0;
    exports2.uuidToBuffer = uuidToBuffer;
    var chars = __importStar2(require_chars());
    exports2.utf8Encoder = new TextEncoder();
    exports2.utf8Decoder = new TextDecoder("utf8");
    var decodeB64;
    var encodeB64;
    if (typeof Buffer === "function") {
      exports2.decodeB64 = decodeB64 = (b64) => {
        return Buffer.from(b64, "base64");
      };
      exports2.encodeB64 = encodeB64 = (data) => {
        const buf = !Buffer.isBuffer(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : data;
        return buf.toString("base64");
      };
    } else {
      exports2.decodeB64 = decodeB64 = (b64) => {
        const binaryString = atob(b64);
        const size = binaryString.length;
        const bytes = new Uint8Array(size);
        for (let i4 = 0; i4 < size; i4++) {
          bytes[i4] = binaryString.charCodeAt(i4);
        }
        return bytes;
      };
      exports2.encodeB64 = encodeB64 = (data) => {
        const binaryString = String.fromCharCode(...data);
        return btoa(binaryString);
      };
    }
    var BUFFER_INC_SIZE = 4096;
    var EMPTY_BUFFER = new Uint8Array(0);
    var BufferError = class extends Error {
    };
    exports2.BufferError = BufferError;
    var WriteBuffer = class {
      _rawBuffer;
      buffer;
      size;
      pos;
      constructor() {
        this.size = BUFFER_INC_SIZE;
        this.pos = 0;
        this._rawBuffer = new Uint8Array(this.size);
        this.buffer = new DataView(this._rawBuffer.buffer);
      }
      get position() {
        return this.pos;
      }
      reset() {
        this.pos = 0;
      }
      ensureAlloced(extraLength) {
        const newSize = this.pos + extraLength;
        if (newSize > this.size) {
          this.__realloc(newSize);
        }
      }
      __realloc(newSize) {
        newSize += BUFFER_INC_SIZE;
        const newBuffer = new Uint8Array(newSize);
        newBuffer.set(this._rawBuffer);
        this._rawBuffer = newBuffer;
        this.buffer = new DataView(this._rawBuffer.buffer);
        this.size = newSize;
      }
      writeChar(ch) {
        this.ensureAlloced(1);
        this.buffer.setUint8(this.pos, ch);
        this.pos++;
        return this;
      }
      writeString(s4) {
        return this.writeBytes(exports2.utf8Encoder.encode(s4));
      }
      writeBytes(buf) {
        this.ensureAlloced(buf.length + 4);
        this.buffer.setInt32(this.pos, buf.length);
        this.pos += 4;
        this._rawBuffer.set(buf, this.pos);
        this.pos += buf.length;
        return this;
      }
      writeInt16(i4) {
        this.ensureAlloced(2);
        this.buffer.setInt16(this.pos, i4);
        this.pos += 2;
        return this;
      }
      writeInt32(i4) {
        this.ensureAlloced(4);
        this.buffer.setInt32(this.pos, i4);
        this.pos += 4;
        return this;
      }
      writeFloat32(i4) {
        this.ensureAlloced(4);
        this.buffer.setFloat32(this.pos, i4);
        this.pos += 4;
        return this;
      }
      writeFloat64(i4) {
        this.ensureAlloced(8);
        this.buffer.setFloat64(this.pos, i4);
        this.pos += 8;
        return this;
      }
      writeUInt8(i4) {
        this.ensureAlloced(1);
        this.buffer.setUint8(this.pos, i4);
        this.pos += 1;
        return this;
      }
      writeUInt16(i4) {
        this.ensureAlloced(2);
        this.buffer.setUint16(this.pos, i4);
        this.pos += 2;
        return this;
      }
      writeUInt32(i4) {
        this.ensureAlloced(4);
        this.buffer.setUint32(this.pos, i4);
        this.pos += 4;
        return this;
      }
      writeInt64(i4) {
        this.ensureAlloced(8);
        const hi = Math.floor(i4 / 4294967296);
        const lo = i4 - hi * 4294967296;
        this.buffer.setInt32(this.pos, hi);
        this.buffer.setUint32(this.pos + 4, lo);
        this.pos += 8;
        return this;
      }
      writeBigInt64(i4) {
        let ii = i4;
        if (ii < 0n) {
          ii = 18446744073709551616n + i4;
        }
        const hi = ii >> 32n;
        const lo = ii & 0xffffffffn;
        this.writeUInt32(Number(hi));
        this.writeUInt32(Number(lo));
        return this;
      }
      writeBuffer(buf) {
        const len = buf.length;
        this.ensureAlloced(len);
        this._rawBuffer.set(buf, this.pos);
        this.pos += len;
        return this;
      }
      writeDeferredSize() {
        const startPos = this.pos;
        this.writeInt32(0);
        return () => {
          this.buffer.setInt32(startPos, this.pos - (startPos + 4));
        };
      }
      unwrap() {
        return this._rawBuffer.subarray(0, this.pos);
      }
    };
    exports2.WriteBuffer = WriteBuffer;
    var WriteMessageBuffer = class {
      buffer;
      messagePos;
      constructor() {
        this.messagePos = -1;
        this.buffer = new WriteBuffer();
      }
      reset() {
        this.messagePos = -1;
        this.buffer.reset();
        return this;
      }
      beginMessage(mtype) {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot begin a new message: the previous message is not finished");
        }
        this.messagePos = this.buffer.position;
        this.buffer.writeChar(mtype);
        this.buffer.writeInt32(0);
        return this;
      }
      endMessage() {
        if (this.messagePos < 0) {
          throw new BufferError("cannot end the message: no current message");
        }
        this.buffer.buffer.setInt32(this.messagePos + 1, this.buffer.position - this.messagePos - 1);
        this.messagePos = -1;
        return this;
      }
      writeChar(ch) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeChar(ch);
        return this;
      }
      writeString(s4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeString: no current message");
        }
        this.buffer.writeString(s4);
        return this;
      }
      writeBytes(val2) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeBytes: no current message");
        }
        this.buffer.writeBytes(val2);
        return this;
      }
      writeInt16(i4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt16: no current message");
        }
        this.buffer.writeInt16(i4);
        return this;
      }
      writeInt32(i4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt32: no current message");
        }
        this.buffer.writeInt32(i4);
        return this;
      }
      writeUInt16(i4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt16: no current message");
        }
        this.buffer.writeUInt16(i4);
        return this;
      }
      writeUInt32(i4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt32: no current message");
        }
        this.buffer.writeUInt32(i4);
        return this;
      }
      writeBigInt64(i4) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeBigInt64(i4);
        return this;
      }
      writeFlags(h4, l3) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeUInt32(h4);
        this.buffer.writeUInt32(l3);
        return this;
      }
      writeBuffer(buf) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeBuffer: no current message");
        }
        this.buffer.writeBuffer(buf);
        return this;
      }
      writeSync() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot writeSync: the previous message is not finished");
        }
        this.buffer.writeBuffer(SYNC_MESSAGE);
        return this;
      }
      writeFlush() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot writeFlush: the previous message is not finished");
        }
        this.buffer.writeBuffer(FLUSH_MESSAGE);
        return this;
      }
      unwrap() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot unwrap: an unfinished message is in the buffer");
        }
        return this.buffer.unwrap();
      }
    };
    exports2.WriteMessageBuffer = WriteMessageBuffer;
    var SYNC_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$S).endMessage().unwrap();
    var FLUSH_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$H).endMessage().unwrap();
    var byteToHex2 = [];
    for (let i4 = 0; i4 < 256; ++i4) {
      byteToHex2.push((i4 + 256).toString(16).slice(1));
    }
    function uuidToBuffer(uuid) {
      const buf = new Uint8Array(16);
      for (let i4 = 0; i4 < 16; i4++) {
        buf[i4] = parseInt(uuid.slice(i4 * 2, i4 * 2 + 2), 16);
      }
      return buf;
    }
    var ReadMessageBuffer = class {
      bufs;
      len;
      buf0;
      pos0;
      len0;
      curMessageType;
      curMessageLen;
      curMessageLenUnread;
      curMessageReady;
      constructor() {
        this.bufs = [];
        this.buf0 = null;
        this.pos0 = 0;
        this.len0 = 0;
        this.len = 0;
        this.curMessageType = 0;
        this.curMessageLen = 0;
        this.curMessageLenUnread = 0;
        this.curMessageReady = false;
      }
      get length() {
        return this.len;
      }
      feed(buf) {
        if (this.buf0 == null || this.pos0 === this.len0 && this.bufs.length === 0) {
          this.buf0 = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
          this.len0 = buf.byteLength;
          this.pos0 = 0;
          this.len = this.len0;
        } else {
          this.feedEnqueue(buf);
        }
      }
      feedEnqueue(buf) {
        this.bufs.push(buf);
        this.len += buf.byteLength;
      }
      ensureFirstBuf() {
        if (this.pos0 === this.len0) {
          this.__nextBuf();
        }
        const buf0 = this.buf0;
        if (buf0 == null || buf0.byteLength < 1) {
          throw new BufferError("empty buffer");
        }
        return buf0;
      }
      checkOverread(size) {
        if (this.curMessageLenUnread < size || size > this.len) {
          throw new BufferError("buffer overread");
        }
      }
      __nextBuf() {
        const nextBuf = this.bufs.shift();
        if (nextBuf == null) {
          throw new BufferError("buffer overread");
        }
        this.buf0 = new DataView(nextBuf.buffer, nextBuf.byteOffset, nextBuf.byteLength);
        this.pos0 = 0;
        this.len0 = nextBuf.byteLength;
      }
      discardBuffer(size) {
        this.ensureFirstBuf();
        while (true) {
          if (this.pos0 + size > this.len0) {
            const nread = this.len0 - this.pos0;
            this.pos0 = this.len0;
            this.len -= nread;
            size -= nread;
            this.ensureFirstBuf();
          } else {
            this.pos0 += size;
            this.len -= size;
            break;
          }
        }
      }
      _finishMessage() {
        this.curMessageLen = 0;
        this.curMessageLenUnread = 0;
        this.curMessageReady = false;
        this.curMessageType = 0;
      }
      __readBufferCopy(buf0, size) {
        const ret = new Uint8Array(size);
        let retPos = 0;
        while (true) {
          if (this.pos0 + size > this.len0) {
            const nread = this.len0 - this.pos0;
            ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, nread), retPos);
            retPos += nread;
            this.pos0 = this.len0;
            this.len -= nread;
            size -= nread;
            buf0 = this.ensureFirstBuf();
          } else {
            ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size), retPos);
            this.pos0 += size;
            this.len -= size;
            break;
          }
        }
        return ret;
      }
      _readBuffer(size) {
        if (size === 0) {
          return EMPTY_BUFFER;
        }
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + size <= this.len0) {
          const ret = new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size);
          this.pos0 += size;
          this.len -= size;
          return ret;
        }
        return this.__readBufferCopy(buf0, size);
      }
      readBuffer(size) {
        this.checkOverread(size);
        const buf = this._readBuffer(size);
        this.curMessageLenUnread -= size;
        return buf;
      }
      readUUID() {
        const buf = this.readBuffer(16);
        return byteToHex2[buf[0]] + byteToHex2[buf[1]] + byteToHex2[buf[2]] + byteToHex2[buf[3]] + byteToHex2[buf[4]] + byteToHex2[buf[5]] + byteToHex2[buf[6]] + byteToHex2[buf[7]] + byteToHex2[buf[8]] + byteToHex2[buf[9]] + byteToHex2[buf[10]] + byteToHex2[buf[11]] + byteToHex2[buf[12]] + byteToHex2[buf[13]] + byteToHex2[buf[14]] + byteToHex2[buf[15]];
      }
      readChar() {
        this.checkOverread(1);
        const buf0 = this.ensureFirstBuf();
        const ret = buf0.getUint8(this.pos0);
        this.pos0++;
        this.curMessageLenUnread--;
        this.len--;
        return ret;
      }
      readInt16() {
        this.checkOverread(2);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 2 <= this.len0) {
          const ret = buf0.getInt16(this.pos0);
          this.pos0 += 2;
          this.curMessageLenUnread -= 2;
          this.len -= 2;
          return ret;
        }
        const buf = this._readBuffer(2);
        this.curMessageLenUnread -= 2;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt16(0);
      }
      readInt32() {
        this.checkOverread(4);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 4 <= this.len0) {
          const ret = buf0.getInt32(this.pos0);
          this.pos0 += 4;
          this.curMessageLenUnread -= 4;
          this.len -= 4;
          return ret;
        }
        const buf = this._readBuffer(4);
        this.curMessageLenUnread -= 4;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
      }
      readUInt16() {
        this.checkOverread(2);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 2 <= this.len0) {
          const ret = buf0.getUint16(this.pos0);
          this.pos0 += 2;
          this.curMessageLenUnread -= 2;
          this.len -= 2;
          return ret;
        }
        const buf = this._readBuffer(2);
        this.curMessageLenUnread -= 2;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint16(0);
      }
      readUInt32() {
        this.checkOverread(4);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 4 <= this.len0) {
          const ret = buf0.getUint32(this.pos0);
          this.pos0 += 4;
          this.curMessageLenUnread -= 4;
          this.len -= 4;
          return ret;
        }
        const buf = this._readBuffer(4);
        this.curMessageLenUnread -= 4;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint32(0);
      }
      readBigInt64() {
        this.checkOverread(8);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 8 <= this.len0) {
          const ret = buf0.getBigInt64(this.pos0);
          this.pos0 += 8;
          this.curMessageLenUnread -= 8;
          this.len -= 8;
          return ret;
        }
        const buf = this._readBuffer(8);
        this.curMessageLenUnread -= 8;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getBigInt64(0);
      }
      readString() {
        const len = this.readInt32();
        const buf = this.readBuffer(len);
        return exports2.utf8Decoder.decode(buf);
      }
      readLenPrefixedBuffer() {
        const len = this.readInt32();
        return this.readBuffer(len);
      }
      takeMessage() {
        if (this.curMessageReady) {
          return true;
        }
        if (this.curMessageType === 0) {
          if (this.len < 1) {
            return false;
          }
          const buf0 = this.ensureFirstBuf();
          this.curMessageType = buf0.getUint8(this.pos0);
          this.pos0++;
          this.len--;
        }
        if (this.curMessageLen === 0) {
          if (this.len < 4) {
            return false;
          }
          const buf0 = this.ensureFirstBuf();
          if (this.pos0 + 4 <= this.len0) {
            this.curMessageLen = buf0.getInt32(this.pos0);
            this.pos0 += 4;
            this.len -= 4;
          } else {
            const buf = this._readBuffer(4);
            this.curMessageLen = new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
          }
          this.curMessageLenUnread = this.curMessageLen - 4;
        }
        if (this.len < this.curMessageLenUnread) {
          return false;
        }
        this.curMessageReady = true;
        return true;
      }
      getMessageType() {
        return this.curMessageType;
      }
      takeMessageType(mtype) {
        if (this.curMessageReady) {
          return this.curMessageType === mtype;
        }
        if (this.len >= 1) {
          const buf0 = this.ensureFirstBuf();
          const unreadMessageType = buf0.getUint8(this.pos0);
          return mtype === unreadMessageType && this.takeMessage();
        }
        return false;
      }
      putMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("cannot put message: no message taken");
        }
        if (this.curMessageLenUnread !== this.curMessageLen - 4) {
          throw new BufferError("cannot put message: message is partially read");
        }
        this.curMessageReady = false;
      }
      discardMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("no message to discard");
        }
        if (this.curMessageLenUnread > 0) {
          this.discardBuffer(this.curMessageLenUnread);
        }
        this._finishMessage();
      }
      consumeMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("no message to consume");
        }
        let buf;
        if (this.curMessageLenUnread > 0) {
          buf = this._readBuffer(this.curMessageLenUnread);
          this.curMessageLenUnread = 0;
        } else {
          buf = EMPTY_BUFFER;
        }
        this._finishMessage();
        return buf;
      }
      consumeMessageInto(frb) {
        if (!this.curMessageReady) {
          throw new BufferError("no message to consume");
        }
        if (this.curMessageLenUnread > 0) {
          if (this.pos0 + this.curMessageLenUnread <= this.len0) {
            ReadBuffer.init(frb, new Uint8Array(this.buf0.buffer, this.buf0.byteOffset + this.pos0, this.curMessageLenUnread));
            this.pos0 += this.curMessageLenUnread;
            this.len -= this.curMessageLenUnread;
          } else {
            const buf = this._readBuffer(this.curMessageLenUnread);
            ReadBuffer.init(frb, buf);
          }
          this.curMessageLenUnread = 0;
        } else {
          ReadBuffer.init(frb, EMPTY_BUFFER);
        }
        this._finishMessage();
      }
      finishMessage() {
        if (this.curMessageType === 0 || !this.curMessageReady) {
          return;
        }
        if (this.curMessageLenUnread) {
          throw new BufferError(`cannot finishMessage: unread data in message "${chars.chr(this.curMessageType)}"`);
        }
        this._finishMessage();
      }
    };
    exports2.ReadMessageBuffer = ReadMessageBuffer;
    var ReadBuffer = class {
      _rawBuffer;
      buffer;
      pos;
      len;
      constructor(buf) {
        this._rawBuffer = buf;
        this.buffer = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
        this.len = buf.length;
        this.pos = 0;
      }
      get position() {
        return this.pos;
      }
      get length() {
        return this.len - this.pos;
      }
      finish(message) {
        if (this.len !== this.pos) {
          throw new BufferError(message ?? "unexpected trailing data in buffer");
        }
      }
      discard(size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        this.pos += size;
      }
      readUInt8() {
        if (this.pos + 1 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint8(this.pos);
        this.pos++;
        return num;
      }
      readUInt16() {
        if (this.pos + 2 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint16(this.pos);
        this.pos += 2;
        return num;
      }
      readInt8() {
        if (this.pos + 1 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt8(this.pos);
        this.pos++;
        return num;
      }
      readInt16() {
        if (this.pos + 2 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt16(this.pos);
        this.pos += 2;
        return num;
      }
      readInt32() {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt32(this.pos);
        this.pos += 4;
        return num;
      }
      readFloat32() {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getFloat32(this.pos);
        this.pos += 4;
        return num;
      }
      readFloat64(le) {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getFloat64(this.pos, le);
        this.pos += 8;
        return num;
      }
      readUInt32(le) {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint32(this.pos, le);
        this.pos += 4;
        return num;
      }
      reportInt64Overflow(hi, lo) {
        const bhi = BigInt(hi);
        const blo = BigInt(lo >>> 0);
        const num = bhi * BigInt(4294967296) + blo;
        throw new BufferError(`integer overflow: cannot unpack <std::int64>'${num.toString()}' into JavaScript Number type without losing precision`);
      }
      readInt64() {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const hi = this.buffer.getInt32(this.pos);
        const lo = this.buffer.getInt32(this.pos + 4);
        this.pos += 8;
        if (hi === 0) {
          return lo >>> 0;
        } else if (hi >= -2097152 && hi < 2097152) {
          return hi * 4294967296 + (lo >>> 0);
        }
        return this.reportInt64Overflow(hi, lo);
      }
      readBigInt64() {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const ret = this.buffer.getBigInt64(this.pos);
        this.pos += 8;
        return ret;
      }
      readBoolean() {
        return this.readUInt8() !== 0;
      }
      readBuffer(size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        const buf = this._rawBuffer.subarray(this.pos, this.pos + size);
        this.pos += size;
        return buf;
      }
      readUUIDBytes() {
        return this.readBuffer(16);
      }
      readUUID(dash = "") {
        if (this.pos + 16 > this.len) {
          throw new BufferError("buffer overread");
        }
        const buf = this._rawBuffer;
        const pos = this.pos;
        const uuid = byteToHex2[buf[pos + 0]] + byteToHex2[buf[pos + 1]] + byteToHex2[buf[pos + 2]] + byteToHex2[buf[pos + 3]] + dash + byteToHex2[buf[pos + 4]] + byteToHex2[buf[pos + 5]] + dash + byteToHex2[buf[pos + 6]] + byteToHex2[buf[pos + 7]] + dash + byteToHex2[buf[pos + 8]] + byteToHex2[buf[pos + 9]] + dash + byteToHex2[buf[pos + 10]] + byteToHex2[buf[pos + 11]] + byteToHex2[buf[pos + 12]] + byteToHex2[buf[pos + 13]] + byteToHex2[buf[pos + 14]] + byteToHex2[buf[pos + 15]];
        this.pos += 16;
        return uuid;
      }
      readString() {
        const len = this.readUInt32();
        const buf = this.readBuffer(len);
        return exports2.utf8Decoder.decode(buf);
      }
      consumeAsString() {
        if (this.pos === this.len) {
          return "";
        }
        const res = exports2.utf8Decoder.decode(this._rawBuffer.subarray(this.pos, this.len));
        this.pos = this.len;
        return res;
      }
      consumeAsBuffer() {
        const res = this._rawBuffer.subarray(this.pos, this.len);
        this.pos = this.len;
        return res;
      }
      sliceInto(frb, size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        frb._rawBuffer = this._rawBuffer;
        frb.buffer = this.buffer;
        frb.pos = this.pos;
        frb.len = this.pos + size;
        this.pos += size;
      }
      static init(frb, buffer) {
        frb._rawBuffer = buffer;
        frb.buffer = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
        frb.pos = 0;
        frb.len = buffer.byteLength;
      }
      static alloc() {
        return new this(EMPTY_BUFFER);
      }
    };
    exports2.ReadBuffer = ReadBuffer;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js
var require_base = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ErrorAttr = exports2.GelError = void 0;
    exports2.prettyPrintError = prettyPrintError;
    var buffer_1 = require_buffer();
    var GelError = class extends Error {
      static tags = {};
      _message;
      _query;
      _attrs;
      constructor(message, options) {
        super(void 0, options);
        Object.defineProperties(this, {
          _message: { writable: true, enumerable: false },
          _query: { writable: true, enumerable: false },
          _attrs: { writable: true, enumerable: false }
        });
        this._message = message ?? "";
      }
      get message() {
        return this._message + (this._query && this._attrs ? prettyPrintError(this._attrs, this._query) : "");
      }
      get name() {
        return this.constructor.name;
      }
      hasTag(tag) {
        const error_type = this.constructor;
        return error_type.tags[tag] ?? false;
      }
    };
    exports2.GelError = GelError;
    var ErrorAttr;
    (function(ErrorAttr2) {
      ErrorAttr2[ErrorAttr2["hint"] = 1] = "hint";
      ErrorAttr2[ErrorAttr2["details"] = 2] = "details";
      ErrorAttr2[ErrorAttr2["serverTraceback"] = 257] = "serverTraceback";
      ErrorAttr2[ErrorAttr2["positionStart"] = -15] = "positionStart";
      ErrorAttr2[ErrorAttr2["positionEnd"] = -14] = "positionEnd";
      ErrorAttr2[ErrorAttr2["lineStart"] = -13] = "lineStart";
      ErrorAttr2[ErrorAttr2["columnStart"] = -12] = "columnStart";
      ErrorAttr2[ErrorAttr2["utf16ColumnStart"] = -11] = "utf16ColumnStart";
      ErrorAttr2[ErrorAttr2["lineEnd"] = -10] = "lineEnd";
      ErrorAttr2[ErrorAttr2["columnEnd"] = -9] = "columnEnd";
      ErrorAttr2[ErrorAttr2["utf16ColumnEnd"] = -8] = "utf16ColumnEnd";
      ErrorAttr2[ErrorAttr2["characterStart"] = -7] = "characterStart";
      ErrorAttr2[ErrorAttr2["characterEnd"] = -6] = "characterEnd";
    })(ErrorAttr || (exports2.ErrorAttr = ErrorAttr = {}));
    function tryParseInt(val2) {
      if (val2 == null)
        return null;
      try {
        return parseInt(val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2, 10);
      } catch {
        return null;
      }
    }
    function readAttrStr(val2) {
      return val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2 ?? "";
    }
    function prettyPrintError(attrs, query) {
      let errMessage = "\n";
      const lineStart = tryParseInt(attrs.get(ErrorAttr.lineStart));
      const lineEnd = tryParseInt(attrs.get(ErrorAttr.lineEnd));
      const colStart = tryParseInt(attrs.get(ErrorAttr.utf16ColumnStart));
      const colEnd = tryParseInt(attrs.get(ErrorAttr.utf16ColumnEnd));
      if (lineStart != null && lineEnd != null && colStart != null && colEnd != null) {
        const queryLines = query.split("\n");
        const lineNoWidth = lineEnd.toString().length;
        errMessage += "|".padStart(lineNoWidth + 3) + "\n";
        for (let i4 = lineStart; i4 < lineEnd + 1; i4++) {
          const line = queryLines[i4 - 1];
          const start = i4 === lineStart ? colStart : 0;
          const end = i4 === lineEnd ? colEnd : line.length;
          errMessage += ` ${i4.toString().padStart(lineNoWidth)} | ${line}
`;
          errMessage += `${"|".padStart(lineNoWidth + 3)} ${"".padStart(end - start, "^").padStart(end)}
`;
        }
      }
      if (attrs.has(ErrorAttr.details)) {
        errMessage += `Details: ${readAttrStr(attrs.get(ErrorAttr.details))}
`;
      }
      if (attrs.has(ErrorAttr.hint)) {
        errMessage += `Hint: ${readAttrStr(attrs.get(ErrorAttr.hint))}
`;
      }
      return errMessage;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js
var require_tags = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SHOULD_RETRY = exports2.SHOULD_RECONNECT = void 0;
    exports2.SHOULD_RECONNECT = Symbol("SHOULD_RECONNECT");
    exports2.SHOULD_RETRY = Symbol("SHOULD_RETRY");
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js
var require_errors = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
      for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DuplicatePropertyDefinitionError = exports2.DuplicateLinkDefinitionError = exports2.DuplicateModuleDefinitionError = exports2.DuplicateDefinitionError = exports2.InvalidCastDefinitionError = exports2.InvalidConstraintDefinitionError = exports2.InvalidFunctionDefinitionError = exports2.InvalidAliasDefinitionError = exports2.InvalidOperatorDefinitionError = exports2.InvalidDatabaseDefinitionError = exports2.InvalidUserDefinitionError = exports2.InvalidPropertyDefinitionError = exports2.InvalidLinkDefinitionError = exports2.InvalidModuleDefinitionError = exports2.InvalidDefinitionError = exports2.SchemaDefinitionError = exports2.SchemaError = exports2.DeprecatedScopingError = exports2.UnknownParameterError = exports2.UnknownDatabaseError = exports2.UnknownUserError = exports2.UnknownPropertyError = exports2.UnknownLinkError = exports2.UnknownModuleError = exports2.InvalidReferenceError = exports2.InvalidPropertyTargetError = exports2.InvalidLinkTargetError = exports2.InvalidTargetError = exports2.InvalidTypeError = exports2.GraphQLSyntaxError = exports2.SchemaSyntaxError = exports2.EdgeQLSyntaxError = exports2.InvalidSyntaxError = exports2.QueryError = exports2.UnsafeIsolationLevelError = exports2.DisabledCapabilityError = exports2.UnsupportedCapabilityError = exports2.CapabilityError = exports2.ResultCardinalityMismatchError = exports2.StateMismatchError = exports2.ParameterTypeMismatchError = exports2.InputDataError = exports2.UnexpectedMessageError = exports2.TypeSpecNotFoundError = exports2.UnsupportedProtocolVersionError = exports2.BinaryProtocolError = exports2.ProtocolError = exports2.UnsupportedFeatureError = exports2.InternalServerError = exports2.GelError = void 0;
    exports2.QueryArgumentError = exports2.InterfaceError = exports2.ClientConnectionClosedError = exports2.ClientConnectionTimeoutError = exports2.ClientConnectionFailedTemporarilyError = exports2.ClientConnectionFailedError = exports2.ClientConnectionError = exports2.ClientError = exports2.MigrationStatusMessage = exports2.StatusMessage = exports2.WarningMessage = exports2.LogMessage = exports2.UnsupportedBackendFeatureError = exports2.BackendError = exports2.ServerBlockedError = exports2.UnknownTenantError = exports2.ServerOfflineError = exports2.BackendUnavailableError = exports2.AvailabilityError = exports2.AuthenticationError = exports2.AccessError = exports2.ConfigurationError = exports2.WatchError = exports2.TransactionDeadlockError = exports2.TransactionSerializationError = exports2.TransactionConflictError = exports2.TransactionError = exports2.MissingRequiredError = exports2.CardinalityViolationError = exports2.ConstraintViolationError = exports2.IntegrityError = exports2.QueryAssertionError = exports2.AccessPolicyError = exports2.NumericOutOfRangeError = exports2.DivisionByZeroError = exports2.InvalidValueError = exports2.ExecutionError = exports2.IdleTransactionTimeoutError = exports2.TransactionTimeoutError = exports2.QueryTimeoutError = exports2.IdleSessionTimeoutError = exports2.SessionTimeoutError = exports2.DuplicateMigrationError = exports2.DuplicateCastDefinitionError = exports2.DuplicateConstraintDefinitionError = exports2.DuplicateFunctionDefinitionError = exports2.DuplicateViewDefinitionError = exports2.DuplicateOperatorDefinitionError = exports2.DuplicateDatabaseDefinitionError = exports2.DuplicateUserDefinitionError = void 0;
    exports2.InternalClientError = exports2.NoDataError = exports2.InvalidArgumentError = exports2.UnknownArgumentError = exports2.MissingArgumentError = void 0;
    var base_1 = require_base();
    var tags = __importStar2(require_tags());
    var base_2 = require_base();
    Object.defineProperty(exports2, "GelError", { enumerable: true, get: function() {
      return base_2.GelError;
    } });
    __exportStar2(require_tags(), exports2);
    var InternalServerError = class extends base_1.GelError {
      get code() {
        return 16777216;
      }
    };
    exports2.InternalServerError = InternalServerError;
    var UnsupportedFeatureError = class extends base_1.GelError {
      get code() {
        return 33554432;
      }
    };
    exports2.UnsupportedFeatureError = UnsupportedFeatureError;
    var ProtocolError = class extends base_1.GelError {
      get code() {
        return 50331648;
      }
    };
    exports2.ProtocolError = ProtocolError;
    var BinaryProtocolError = class extends ProtocolError {
      get code() {
        return 50397184;
      }
    };
    exports2.BinaryProtocolError = BinaryProtocolError;
    var UnsupportedProtocolVersionError = class extends BinaryProtocolError {
      get code() {
        return 50397185;
      }
    };
    exports2.UnsupportedProtocolVersionError = UnsupportedProtocolVersionError;
    var TypeSpecNotFoundError = class extends BinaryProtocolError {
      get code() {
        return 50397186;
      }
    };
    exports2.TypeSpecNotFoundError = TypeSpecNotFoundError;
    var UnexpectedMessageError = class extends BinaryProtocolError {
      get code() {
        return 50397187;
      }
    };
    exports2.UnexpectedMessageError = UnexpectedMessageError;
    var InputDataError = class extends ProtocolError {
      get code() {
        return 50462720;
      }
    };
    exports2.InputDataError = InputDataError;
    var ParameterTypeMismatchError = class extends InputDataError {
      get code() {
        return 50462976;
      }
    };
    exports2.ParameterTypeMismatchError = ParameterTypeMismatchError;
    var StateMismatchError = class extends InputDataError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 50463232;
      }
    };
    exports2.StateMismatchError = StateMismatchError;
    var ResultCardinalityMismatchError = class extends ProtocolError {
      get code() {
        return 50528256;
      }
    };
    exports2.ResultCardinalityMismatchError = ResultCardinalityMismatchError;
    var CapabilityError = class extends ProtocolError {
      get code() {
        return 50593792;
      }
    };
    exports2.CapabilityError = CapabilityError;
    var UnsupportedCapabilityError = class extends CapabilityError {
      get code() {
        return 50594048;
      }
    };
    exports2.UnsupportedCapabilityError = UnsupportedCapabilityError;
    var DisabledCapabilityError = class extends CapabilityError {
      get code() {
        return 50594304;
      }
    };
    exports2.DisabledCapabilityError = DisabledCapabilityError;
    var UnsafeIsolationLevelError = class extends CapabilityError {
      get code() {
        return 50594560;
      }
    };
    exports2.UnsafeIsolationLevelError = UnsafeIsolationLevelError;
    var QueryError = class extends base_1.GelError {
      get code() {
        return 67108864;
      }
    };
    exports2.QueryError = QueryError;
    var InvalidSyntaxError = class extends QueryError {
      get code() {
        return 67174400;
      }
    };
    exports2.InvalidSyntaxError = InvalidSyntaxError;
    var EdgeQLSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67174656;
      }
    };
    exports2.EdgeQLSyntaxError = EdgeQLSyntaxError;
    var SchemaSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67174912;
      }
    };
    exports2.SchemaSyntaxError = SchemaSyntaxError;
    var GraphQLSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67175168;
      }
    };
    exports2.GraphQLSyntaxError = GraphQLSyntaxError;
    var InvalidTypeError = class extends QueryError {
      get code() {
        return 67239936;
      }
    };
    exports2.InvalidTypeError = InvalidTypeError;
    var InvalidTargetError = class extends InvalidTypeError {
      get code() {
        return 67240192;
      }
    };
    exports2.InvalidTargetError = InvalidTargetError;
    var InvalidLinkTargetError = class extends InvalidTargetError {
      get code() {
        return 67240193;
      }
    };
    exports2.InvalidLinkTargetError = InvalidLinkTargetError;
    var InvalidPropertyTargetError = class extends InvalidTargetError {
      get code() {
        return 67240194;
      }
    };
    exports2.InvalidPropertyTargetError = InvalidPropertyTargetError;
    var InvalidReferenceError = class extends QueryError {
      get code() {
        return 67305472;
      }
    };
    exports2.InvalidReferenceError = InvalidReferenceError;
    var UnknownModuleError = class extends InvalidReferenceError {
      get code() {
        return 67305473;
      }
    };
    exports2.UnknownModuleError = UnknownModuleError;
    var UnknownLinkError = class extends InvalidReferenceError {
      get code() {
        return 67305474;
      }
    };
    exports2.UnknownLinkError = UnknownLinkError;
    var UnknownPropertyError = class extends InvalidReferenceError {
      get code() {
        return 67305475;
      }
    };
    exports2.UnknownPropertyError = UnknownPropertyError;
    var UnknownUserError = class extends InvalidReferenceError {
      get code() {
        return 67305476;
      }
    };
    exports2.UnknownUserError = UnknownUserError;
    var UnknownDatabaseError = class extends InvalidReferenceError {
      get code() {
        return 67305477;
      }
    };
    exports2.UnknownDatabaseError = UnknownDatabaseError;
    var UnknownParameterError = class extends InvalidReferenceError {
      get code() {
        return 67305478;
      }
    };
    exports2.UnknownParameterError = UnknownParameterError;
    var DeprecatedScopingError = class extends InvalidReferenceError {
      get code() {
        return 67305479;
      }
    };
    exports2.DeprecatedScopingError = DeprecatedScopingError;
    var SchemaError = class extends QueryError {
      get code() {
        return 67371008;
      }
    };
    exports2.SchemaError = SchemaError;
    var SchemaDefinitionError = class extends QueryError {
      get code() {
        return 67436544;
      }
    };
    exports2.SchemaDefinitionError = SchemaDefinitionError;
    var InvalidDefinitionError = class extends SchemaDefinitionError {
      get code() {
        return 67436800;
      }
    };
    exports2.InvalidDefinitionError = InvalidDefinitionError;
    var InvalidModuleDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436801;
      }
    };
    exports2.InvalidModuleDefinitionError = InvalidModuleDefinitionError;
    var InvalidLinkDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436802;
      }
    };
    exports2.InvalidLinkDefinitionError = InvalidLinkDefinitionError;
    var InvalidPropertyDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436803;
      }
    };
    exports2.InvalidPropertyDefinitionError = InvalidPropertyDefinitionError;
    var InvalidUserDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436804;
      }
    };
    exports2.InvalidUserDefinitionError = InvalidUserDefinitionError;
    var InvalidDatabaseDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436805;
      }
    };
    exports2.InvalidDatabaseDefinitionError = InvalidDatabaseDefinitionError;
    var InvalidOperatorDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436806;
      }
    };
    exports2.InvalidOperatorDefinitionError = InvalidOperatorDefinitionError;
    var InvalidAliasDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436807;
      }
    };
    exports2.InvalidAliasDefinitionError = InvalidAliasDefinitionError;
    var InvalidFunctionDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436808;
      }
    };
    exports2.InvalidFunctionDefinitionError = InvalidFunctionDefinitionError;
    var InvalidConstraintDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436809;
      }
    };
    exports2.InvalidConstraintDefinitionError = InvalidConstraintDefinitionError;
    var InvalidCastDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436810;
      }
    };
    exports2.InvalidCastDefinitionError = InvalidCastDefinitionError;
    var DuplicateDefinitionError = class extends SchemaDefinitionError {
      get code() {
        return 67437056;
      }
    };
    exports2.DuplicateDefinitionError = DuplicateDefinitionError;
    var DuplicateModuleDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437057;
      }
    };
    exports2.DuplicateModuleDefinitionError = DuplicateModuleDefinitionError;
    var DuplicateLinkDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437058;
      }
    };
    exports2.DuplicateLinkDefinitionError = DuplicateLinkDefinitionError;
    var DuplicatePropertyDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437059;
      }
    };
    exports2.DuplicatePropertyDefinitionError = DuplicatePropertyDefinitionError;
    var DuplicateUserDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437060;
      }
    };
    exports2.DuplicateUserDefinitionError = DuplicateUserDefinitionError;
    var DuplicateDatabaseDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437061;
      }
    };
    exports2.DuplicateDatabaseDefinitionError = DuplicateDatabaseDefinitionError;
    var DuplicateOperatorDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437062;
      }
    };
    exports2.DuplicateOperatorDefinitionError = DuplicateOperatorDefinitionError;
    var DuplicateViewDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437063;
      }
    };
    exports2.DuplicateViewDefinitionError = DuplicateViewDefinitionError;
    var DuplicateFunctionDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437064;
      }
    };
    exports2.DuplicateFunctionDefinitionError = DuplicateFunctionDefinitionError;
    var DuplicateConstraintDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437065;
      }
    };
    exports2.DuplicateConstraintDefinitionError = DuplicateConstraintDefinitionError;
    var DuplicateCastDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437066;
      }
    };
    exports2.DuplicateCastDefinitionError = DuplicateCastDefinitionError;
    var DuplicateMigrationError = class extends DuplicateDefinitionError {
      get code() {
        return 67437067;
      }
    };
    exports2.DuplicateMigrationError = DuplicateMigrationError;
    var SessionTimeoutError = class extends QueryError {
      get code() {
        return 67502080;
      }
    };
    exports2.SessionTimeoutError = SessionTimeoutError;
    var IdleSessionTimeoutError = class extends SessionTimeoutError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 67502336;
      }
    };
    exports2.IdleSessionTimeoutError = IdleSessionTimeoutError;
    var QueryTimeoutError = class extends SessionTimeoutError {
      get code() {
        return 67502592;
      }
    };
    exports2.QueryTimeoutError = QueryTimeoutError;
    var TransactionTimeoutError = class extends SessionTimeoutError {
      get code() {
        return 67504640;
      }
    };
    exports2.TransactionTimeoutError = TransactionTimeoutError;
    var IdleTransactionTimeoutError = class extends TransactionTimeoutError {
      get code() {
        return 67504641;
      }
    };
    exports2.IdleTransactionTimeoutError = IdleTransactionTimeoutError;
    var ExecutionError = class extends base_1.GelError {
      get code() {
        return 83886080;
      }
    };
    exports2.ExecutionError = ExecutionError;
    var InvalidValueError = class extends ExecutionError {
      get code() {
        return 83951616;
      }
    };
    exports2.InvalidValueError = InvalidValueError;
    var DivisionByZeroError = class extends InvalidValueError {
      get code() {
        return 83951617;
      }
    };
    exports2.DivisionByZeroError = DivisionByZeroError;
    var NumericOutOfRangeError = class extends InvalidValueError {
      get code() {
        return 83951618;
      }
    };
    exports2.NumericOutOfRangeError = NumericOutOfRangeError;
    var AccessPolicyError = class extends InvalidValueError {
      get code() {
        return 83951619;
      }
    };
    exports2.AccessPolicyError = AccessPolicyError;
    var QueryAssertionError = class extends InvalidValueError {
      get code() {
        return 83951620;
      }
    };
    exports2.QueryAssertionError = QueryAssertionError;
    var IntegrityError = class extends ExecutionError {
      get code() {
        return 84017152;
      }
    };
    exports2.IntegrityError = IntegrityError;
    var ConstraintViolationError = class extends IntegrityError {
      get code() {
        return 84017153;
      }
    };
    exports2.ConstraintViolationError = ConstraintViolationError;
    var CardinalityViolationError = class extends IntegrityError {
      get code() {
        return 84017154;
      }
    };
    exports2.CardinalityViolationError = CardinalityViolationError;
    var MissingRequiredError = class extends IntegrityError {
      get code() {
        return 84017155;
      }
    };
    exports2.MissingRequiredError = MissingRequiredError;
    var TransactionError = class extends ExecutionError {
      get code() {
        return 84082688;
      }
    };
    exports2.TransactionError = TransactionError;
    var TransactionConflictError = class extends TransactionError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 84082944;
      }
    };
    exports2.TransactionConflictError = TransactionConflictError;
    var TransactionSerializationError = class extends TransactionConflictError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 84082945;
      }
    };
    exports2.TransactionSerializationError = TransactionSerializationError;
    var TransactionDeadlockError = class extends TransactionConflictError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 84082946;
      }
    };
    exports2.TransactionDeadlockError = TransactionDeadlockError;
    var WatchError = class extends ExecutionError {
      get code() {
        return 84148224;
      }
    };
    exports2.WatchError = WatchError;
    var ConfigurationError = class extends base_1.GelError {
      get code() {
        return 100663296;
      }
    };
    exports2.ConfigurationError = ConfigurationError;
    var AccessError = class extends base_1.GelError {
      get code() {
        return 117440512;
      }
    };
    exports2.AccessError = AccessError;
    var AuthenticationError = class extends AccessError {
      get code() {
        return 117506048;
      }
    };
    exports2.AuthenticationError = AuthenticationError;
    var AvailabilityError = class extends base_1.GelError {
      get code() {
        return 134217728;
      }
    };
    exports2.AvailabilityError = AvailabilityError;
    var BackendUnavailableError = class extends AvailabilityError {
      static tags = { [tags.SHOULD_RETRY]: true };
      get code() {
        return 134217729;
      }
    };
    exports2.BackendUnavailableError = BackendUnavailableError;
    var ServerOfflineError = class extends AvailabilityError {
      static tags = {
        [tags.SHOULD_RECONNECT]: true,
        [tags.SHOULD_RETRY]: true
      };
      get code() {
        return 134217730;
      }
    };
    exports2.ServerOfflineError = ServerOfflineError;
    var UnknownTenantError = class extends AvailabilityError {
      static tags = {
        [tags.SHOULD_RECONNECT]: true,
        [tags.SHOULD_RETRY]: true
      };
      get code() {
        return 134217731;
      }
    };
    exports2.UnknownTenantError = UnknownTenantError;
    var ServerBlockedError = class extends AvailabilityError {
      get code() {
        return 134217732;
      }
    };
    exports2.ServerBlockedError = ServerBlockedError;
    var BackendError = class extends base_1.GelError {
      get code() {
        return 150994944;
      }
    };
    exports2.BackendError = BackendError;
    var UnsupportedBackendFeatureError = class extends BackendError {
      get code() {
        return 150995200;
      }
    };
    exports2.UnsupportedBackendFeatureError = UnsupportedBackendFeatureError;
    var LogMessage = class extends base_1.GelError {
      get code() {
        return 4026531840;
      }
    };
    exports2.LogMessage = LogMessage;
    var WarningMessage = class extends LogMessage {
      get code() {
        return 4026597376;
      }
    };
    exports2.WarningMessage = WarningMessage;
    var StatusMessage = class extends LogMessage {
      get code() {
        return 4026662912;
      }
    };
    exports2.StatusMessage = StatusMessage;
    var MigrationStatusMessage = class extends StatusMessage {
      get code() {
        return 4026662913;
      }
    };
    exports2.MigrationStatusMessage = MigrationStatusMessage;
    var ClientError = class extends base_1.GelError {
      get code() {
        return 4278190080;
      }
    };
    exports2.ClientError = ClientError;
    var ClientConnectionError = class extends ClientError {
      get code() {
        return 4278255616;
      }
    };
    exports2.ClientConnectionError = ClientConnectionError;
    var ClientConnectionFailedError = class extends ClientConnectionError {
      get code() {
        return 4278255872;
      }
    };
    exports2.ClientConnectionFailedError = ClientConnectionFailedError;
    var ClientConnectionFailedTemporarilyError = class extends ClientConnectionFailedError {
      static tags = {
        [tags.SHOULD_RECONNECT]: true,
        [tags.SHOULD_RETRY]: true
      };
      get code() {
        return 4278255873;
      }
    };
    exports2.ClientConnectionFailedTemporarilyError = ClientConnectionFailedTemporarilyError;
    var ClientConnectionTimeoutError = class extends ClientConnectionError {
      static tags = {
        [tags.SHOULD_RECONNECT]: true,
        [tags.SHOULD_RETRY]: true
      };
      get code() {
        return 4278256128;
      }
    };
    exports2.ClientConnectionTimeoutError = ClientConnectionTimeoutError;
    var ClientConnectionClosedError = class extends ClientConnectionError {
      static tags = {
        [tags.SHOULD_RECONNECT]: true,
        [tags.SHOULD_RETRY]: true
      };
      get code() {
        return 4278256384;
      }
    };
    exports2.ClientConnectionClosedError = ClientConnectionClosedError;
    var InterfaceError = class extends ClientError {
      get code() {
        return 4278321152;
      }
    };
    exports2.InterfaceError = InterfaceError;
    var QueryArgumentError = class extends InterfaceError {
      get code() {
        return 4278321408;
      }
    };
    exports2.QueryArgumentError = QueryArgumentError;
    var MissingArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321409;
      }
    };
    exports2.MissingArgumentError = MissingArgumentError;
    var UnknownArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321410;
      }
    };
    exports2.UnknownArgumentError = UnknownArgumentError;
    var InvalidArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321411;
      }
    };
    exports2.InvalidArgumentError = InvalidArgumentError;
    var NoDataError = class extends ClientError {
      get code() {
        return 4278386688;
      }
    };
    exports2.NoDataError = NoDataError;
    var InternalClientError = class extends ClientError {
      get code() {
        return 4278452224;
      }
    };
    exports2.InternalClientError = InternalClientError;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js
var require_lru = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var errors_1 = require_errors();
    var Node3 = class {
      key;
      value;
      next;
      prev;
      constructor(key, value) {
        this.key = key;
        this.value = value;
        this.next = null;
        this.prev = null;
      }
    };
    var Deque = class {
      head;
      tail;
      len;
      constructor() {
        this.head = null;
        this.tail = null;
        this.len = 0;
      }
      get length() {
        return this.len;
      }
      push(key, value) {
        const node = new Node3(key, value);
        if (this.head == null) {
          this.head = node;
          this.tail = node;
        } else {
          this.head.prev = node;
          node.next = this.head;
          this.head = node;
        }
        this.len++;
        return node;
      }
      moveToTop(node) {
        if (node.prev == null) {
          return;
        }
        const prev = node.prev;
        const next = node.next;
        prev.next = next;
        if (next != null) {
          next.prev = prev;
        }
        if (this.tail === node) {
          this.tail = prev;
        }
        node.prev = null;
        node.next = this.head;
        this.head.prev = node;
        this.head = node;
      }
      deleteBottom() {
        if (!this.len || !this.tail || !this.head) {
          return null;
        }
        if (this.tail === this.head) {
          this.len = 0;
          const node = this.tail;
          this.tail = null;
          this.head = null;
          return node;
        }
        const tail = this.tail;
        const beforeLast = this.tail.prev;
        beforeLast.next = null;
        this.tail.prev = null;
        this.tail.next = null;
        this.tail = beforeLast;
        this.len--;
        return tail;
      }
    };
    var LRU = class {
      capacity;
      map;
      deque;
      constructor({ capacity }) {
        if (capacity <= 0) {
          throw new TypeError("capacity is expected to be greater than 0");
        }
        this.capacity = capacity;
        this.map = /* @__PURE__ */ new Map();
        this.deque = new Deque();
      }
      get length() {
        const len = this.map.size;
        if (len !== this.deque.length) {
          throw new errors_1.InternalClientError("deque & map disagree on elements count");
        }
        return len;
      }
      has(key) {
        return this.map.has(key);
      }
      get(key) {
        const node = this.map.get(key);
        if (node != null) {
          this.deque.moveToTop(node);
          return node.value;
        }
        return void 0;
      }
      set(key, value) {
        const existingNode = this.map.get(key);
        if (existingNode != null) {
          existingNode.value = value;
          this.deque.moveToTop(existingNode);
        } else {
          const newNode = this.deque.push(key, value);
          this.map.set(key, newNode);
          while (this.deque.length > this.capacity) {
            const bottomNode = this.deque.deleteBottom();
            this.map.delete(bottomNode.key);
          }
        }
      }
      *keys() {
        let node = this.deque.head;
        while (node != null) {
          yield node.key;
          node = node.next;
        }
      }
      *entries() {
        let node = this.deque.head;
        while (node != null) {
          yield [node.key, node.value];
          node = node.next;
        }
      }
      *values() {
        let node = this.deque.head;
        while (node != null) {
          yield node.value;
          node = node.next;
        }
      }
    };
    exports2.default = LRU;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js
var require_consts = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KNOWN_TYPENAMES = exports2.KNOWN_TYPES = exports2.INVALID_CODEC_ID = exports2.NULL_CODEC_ID = void 0;
    exports2.NULL_CODEC_ID = "00000000000000000000000000000000";
    exports2.INVALID_CODEC_ID = "ffffffffffffffffffffffffffffffff";
    exports2.KNOWN_TYPES = /* @__PURE__ */ new Map([
      ["00000000000000000000000000000001", "anytype"],
      ["00000000000000000000000000000002", "anytuple"],
      ["00000000000000000000000000000003", "anyobject"],
      ["000000000000000000000000000000f0", "std"],
      ["000000000000000000000000000000ff", "empty-tuple"],
      ["00000000000000000000000000000100", "std::uuid"],
      ["00000000000000000000000000000101", "std::str"],
      ["00000000000000000000000000000102", "std::bytes"],
      ["00000000000000000000000000000103", "std::int16"],
      ["00000000000000000000000000000104", "std::int32"],
      ["00000000000000000000000000000105", "std::int64"],
      ["00000000000000000000000000000106", "std::float32"],
      ["00000000000000000000000000000107", "std::float64"],
      ["00000000000000000000000000000108", "std::decimal"],
      ["00000000000000000000000000000109", "std::bool"],
      ["0000000000000000000000000000010a", "std::datetime"],
      ["0000000000000000000000000000010b", "cal::local_datetime"],
      ["0000000000000000000000000000010c", "cal::local_date"],
      ["0000000000000000000000000000010d", "cal::local_time"],
      ["0000000000000000000000000000010e", "std::duration"],
      ["0000000000000000000000000000010f", "std::json"],
      ["00000000000000000000000000000110", "std::bigint"],
      ["00000000000000000000000000000111", "cal::relative_duration"],
      ["00000000000000000000000000000112", "cal::date_duration"],
      ["00000000000000000000000000000130", "cfg::memory"],
      ["00000000000000000000000001000001", "std::pg::json"],
      ["00000000000000000000000001000002", "std::pg::timestamptz"],
      ["00000000000000000000000001000003", "std::pg::timestamp"],
      ["00000000000000000000000001000004", "std::pg::date"],
      ["00000000000000000000000001000005", "std::pg::interval"],
      ["9565dd8804f511eea6910b6ebe179825", "ext::pgvector::vector"],
      ["4ba84534188e43b4a7cecea2af0f405b", "ext::pgvector::halfvec"],
      ["003e434dcac2430ab238fb39d73447d2", "ext::pgvector::sparsevec"],
      ["44c901c0d922489483c8061bd05e4840", "ext::postgis::geometry"],
      ["4d7388783a5f4821ab769d8e7d6b32c4", "ext::postgis::geography"],
      ["7fae553663114f608eb9096a5d972f48", "ext::postgis::box2d"],
      ["c1a50ff8fded48b085c24905a8481433", "ext::postgis::box3d"]
    ]);
    exports2.KNOWN_TYPENAMES = (() => {
      const res = /* @__PURE__ */ new Map();
      for (const [id, name] of exports2.KNOWN_TYPES.entries()) {
        res.set(name, id);
      }
      return res;
    })();
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js
var require_ifaces = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ScalarCodec = exports2.Codec = void 0;
    var buffer_1 = require_buffer();
    var consts_1 = require_consts();
    var Codec = class {
      tid;
      tidBuffer;
      constructor(tid) {
        this.tid = tid;
        this.tidBuffer = (0, buffer_1.uuidToBuffer)(tid);
      }
      getKnownTypeName() {
        return "anytype";
      }
    };
    exports2.Codec = Codec;
    var ScalarCodec = class extends Codec {
      typeName;
      ancestors = null;
      constructor(tid, typeName) {
        super(tid);
        this.typeName = typeName;
      }
      derive(tid, typeName, ancestors) {
        const self2 = this.constructor;
        const codec = new self2(tid, typeName);
        codec.ancestors = ancestors;
        return codec;
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "scalar";
      }
      tsType = "unknown";
      tsModule = null;
      getKnownTypeName() {
        if (this.typeName) {
          return this.typeName;
        }
        return consts_1.KNOWN_TYPES.get(this.tid) || "anytype";
      }
    };
    exports2.ScalarCodec = ScalarCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js
var require_boolean = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BoolCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var BoolCodec = class extends ifaces_1.ScalarCodec {
      tsType = "boolean";
      encode(buf, object, ctx) {
        const val2 = ctx.preEncode(this, object);
        const typeOf = typeof val2;
        if (typeOf !== "boolean" && typeOf !== "number") {
          throw new errors_1.InvalidArgumentError(`a boolean or a number was expected, got "${val2}"`);
        }
        buf.writeInt32(1);
        buf.writeChar(val2 ? 1 : 0);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readUInt8() !== 0);
      }
    };
    exports2.BoolCodec = BoolCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js
var require_numbers = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Float64Codec = exports2.Float32Codec = exports2.Int16Codec = exports2.Int32Codec = exports2.Int64Codec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var Int64Codec = class extends ifaces_1.ScalarCodec {
      tsType = "number";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          buf.writeInt32(8);
          buf.writeBigInt64(val2);
          return;
        }
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeInt64(object);
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.readBigInt64());
        }
        return buf.readInt64();
      }
    };
    exports2.Int64Codec = Int64Codec;
    var Int32Codec = class extends ifaces_1.ScalarCodec {
      tsType = "number";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(4);
        buf.writeInt32(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readInt32());
      }
    };
    exports2.Int32Codec = Int32Codec;
    var Int16Codec = class extends ifaces_1.ScalarCodec {
      tsType = "number";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(2);
        buf.writeInt16(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readInt16());
      }
    };
    exports2.Int16Codec = Int16Codec;
    var Float32Codec = class extends ifaces_1.ScalarCodec {
      tsType = "number";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(4);
        buf.writeFloat32(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readFloat32());
      }
    };
    exports2.Float32Codec = Float32Codec;
    var Float64Codec = class extends ifaces_1.ScalarCodec {
      tsType = "number";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeFloat64(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readFloat64());
      }
    };
    exports2.Float64Codec = Float64Codec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js
var require_numerics = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DecimalStringCodec = exports2.BigIntCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var NUMERIC_POS = 0;
    var NUMERIC_NEG = 16384;
    var BigIntCodec = class extends ifaces_1.ScalarCodec {
      tsType = "bigint";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "bigint") {
          throw new errors_1.InvalidArgumentError(`a bigint was expected, got "${object}"`);
        }
        const digits = [];
        let sign = NUMERIC_POS;
        let uval = object;
        if (object === 0n) {
          buf.writeUInt32(8);
          buf.writeUInt32(0);
          buf.writeUInt16(NUMERIC_POS);
          buf.writeUInt16(0);
          return;
        }
        if (object < 0n) {
          sign = NUMERIC_NEG;
          uval = -uval;
        }
        while (uval) {
          const mod = uval % 10000n;
          uval /= 10000n;
          digits.push(mod);
        }
        buf.writeUInt32(8 + digits.length * 2);
        buf.writeUInt16(digits.length);
        buf.writeUInt16(digits.length - 1);
        buf.writeUInt16(sign);
        buf.writeUInt16(0);
        for (let i4 = digits.length - 1; i4 >= 0; i4--) {
          buf.writeUInt16(Number(digits[i4]));
        }
      }
      decode(buf, ctx) {
        const val2 = BigInt(decodeBigIntToString(buf));
        return ctx.postDecode(this, val2);
      }
    };
    exports2.BigIntCodec = BigIntCodec;
    var DecimalStringCodec = class extends ifaces_1.ScalarCodec {
      tsType = "string";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const match2 = object.match(/^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([-+]?[0-9]+))?$/);
        if (!match2) {
          throw new errors_1.InvalidArgumentError(`invalid decimal string "${object}"`);
        }
        const [_3, sign, int, _frac, _exp] = match2;
        const frac = _frac ?? "";
        const exp = _exp ? parseInt(_exp, 10) : 0;
        const sdigits = int.padStart(Math.ceil(int.length / 4) * 4, "0") + frac.padEnd(Math.ceil(frac.length / 4) * 4, "0");
        const digits = [];
        for (let i4 = 0, len = sdigits.length; i4 < len; i4 += 4) {
          digits.push(parseInt(sdigits.slice(i4, i4 + 4), 10));
        }
        buf.writeUInt32(8 + digits.length * 2);
        buf.writeUInt16(digits.length);
        buf.writeInt16(Math.ceil((int.length + exp) / 4) - 1);
        buf.writeUInt16(sign === "-" ? NUMERIC_NEG : NUMERIC_POS);
        buf.writeUInt16(Math.max(frac.length - exp, 0));
        for (let i4 = 0, len = digits.length; i4 < len; i4++) {
          buf.writeUInt16(digits[i4]);
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, decodeDecimalToString(buf));
        }
        return decodeDecimalToString(buf);
      }
    };
    exports2.DecimalStringCodec = DecimalStringCodec;
    function decodeBigIntToString(buf) {
      const ndigits = buf.readUInt16();
      const weight = buf.readInt16();
      const sign = buf.readUInt16();
      const dscale = buf.readUInt16();
      let result = "";
      switch (sign) {
        case NUMERIC_POS:
          break;
        case NUMERIC_NEG:
          result += "-";
          break;
        default:
          throw new errors_1.ProtocolError("bad bigint sign data");
      }
      if (dscale !== 0) {
        throw new errors_1.ProtocolError("bigint data has fractional part");
      }
      if (ndigits === 0) {
        return "0";
      }
      let i4 = weight;
      let d3 = 0;
      while (i4 >= 0) {
        if (i4 <= weight && d3 < ndigits) {
          const digit = buf.readUInt16().toString();
          result += d3 > 0 ? digit.padStart(4, "0") : digit;
          d3++;
        } else {
          result += "0000";
        }
        i4--;
      }
      return result;
    }
    function decodeDecimalToString(buf) {
      const ndigits = buf.readUInt16();
      const weight = buf.readInt16();
      const sign = buf.readUInt16();
      const dscale = buf.readUInt16();
      let result = "";
      switch (sign) {
        case NUMERIC_POS:
          break;
        case NUMERIC_NEG:
          result += "-";
          break;
        default:
          throw new errors_1.ProtocolError("bad decimal sign data");
      }
      let d3 = 0;
      if (weight < 0) {
        d3 = weight + 1;
        result += "0";
      } else {
        for (d3 = 0; d3 <= weight; d3++) {
          const digit = d3 < ndigits ? buf.readUInt16() : 0;
          let sdigit = digit.toString();
          if (d3 > 0) {
            sdigit = sdigit.padStart(4, "0");
          }
          result += sdigit;
        }
      }
      if (dscale > 0) {
        result += ".";
        const end = result.length + dscale;
        for (let i4 = 0; i4 < dscale; d3++, i4 += 4) {
          const digit = d3 >= 0 && d3 < ndigits ? buf.readUInt16() : 0;
          result += digit.toString().padStart(4, "0");
        }
        result = result.slice(0, end);
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js
var require_text = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StrCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var StrCodec = class extends ifaces_1.ScalarCodec {
      tsType = "string";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const val2 = object;
        const strbuf = buffer_1.utf8Encoder.encode(val2);
        buf.writeInt32(strbuf.length);
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsString());
      }
    };
    exports2.StrCodec = StrCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js
var require_uuid = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UUIDCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    function UUIDBufferFromString(uuid) {
      let uuidClean = uuid;
      if (uuidClean.length !== 32) {
        uuidClean = uuidClean.replace(/-/g, "");
        if (uuidClean.length !== 32) {
          throw new TypeError(`invalid UUID "${uuid}"`);
        }
      }
      try {
        return (0, buffer_1.uuidToBuffer)(uuidClean);
      } catch {
        throw new TypeError(`invalid UUID "${uuid}"`);
      }
    }
    var UUIDCodec = class extends ifaces_1.ScalarCodec {
      tsType = "string";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (!(val2 instanceof Uint8Array)) {
            throw new errors_1.InvalidArgumentError(`a Uint8Array was expected from a custom UUID codec`);
          }
          if (val2.length != 16) {
            throw new errors_1.InvalidArgumentError(`a 16-element long Uint8Array was expected from a custom UUID codec`);
          }
          buf.writeInt32(16);
          buf.writeBuffer(val2);
          return;
        }
        if (typeof object === "string") {
          const ubuf = UUIDBufferFromString(object);
          buf.writeInt32(16);
          buf.writeBuffer(ubuf);
        } else {
          throw new errors_1.InvalidArgumentError(`cannot encode UUID "${object}": invalid type`);
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.readUUIDBytes());
        }
        return buf.readUUID("-");
      }
    };
    exports2.UUIDCodec = UUIDCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js
var require_bytes = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BytesCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var BytesCodec = class extends ifaces_1.ScalarCodec {
      tsType = "Uint8Array";
      encode(buf, object, ctx) {
        const val2 = ctx.preEncode(this, object);
        if (!(val2 instanceof Uint8Array)) {
          throw new errors_1.InvalidArgumentError(`a Uint8Array or Buffer was expected, got "${val2}"`);
        }
        buf.writeInt32(val2.length);
        buf.writeBuffer(val2);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsBuffer());
      }
    };
    exports2.BytesCodec = BytesCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js
var require_json = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PgTextJSONStringCodec = exports2.PgTextJSONCodec = exports2.JSONCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var JSONCodec = class extends ifaces_1.ScalarCodec {
      tsType = "unknown";
      jsonFormat = 1;
      encode(buf, object, ctx) {
        let val2;
        if (ctx.hasOverload(this)) {
          val2 = ctx.preEncode(this, object);
        } else {
          try {
            val2 = JSON.stringify(object);
          } catch (_err) {
            throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
          }
        }
        if (typeof val2 !== "string") {
          throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
        }
        const strbuf = buffer_1.utf8Encoder.encode(val2);
        if (this.jsonFormat !== null) {
          buf.writeInt32(strbuf.length + 1);
          buf.writeChar(this.jsonFormat);
        } else {
          buf.writeInt32(strbuf.length);
        }
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        if (this.jsonFormat !== null) {
          const format = buf.readUInt8();
          if (format !== this.jsonFormat) {
            throw new errors_1.ProtocolError(`unexpected JSON format ${format}`);
          }
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.consumeAsString());
        } else {
          return JSON.parse(buf.consumeAsString());
        }
      }
    };
    exports2.JSONCodec = JSONCodec;
    var PgTextJSONCodec = class extends JSONCodec {
      jsonFormat = null;
    };
    exports2.PgTextJSONCodec = PgTextJSONCodec;
    var PgTextJSONStringCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          object = ctx.preEncode(this, object);
        }
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const strbuf = buffer_1.utf8Encoder.encode(object);
        buf.writeInt32(strbuf.length);
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsString());
      }
    };
    exports2.PgTextJSONStringCodec = PgTextJSONStringCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js
var require_dateutil = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isLeapYear = isLeapYear2;
    exports2.daysInMonth = daysInMonth;
    exports2.daysBeforeMonth = daysBeforeMonth;
    exports2.ymd2ord = ymd2ord;
    exports2.ord2ymd = ord2ymd;
    function isLeapYear2(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    function daysInMonth(year, month) {
      if (month === 2 && isLeapYear2(year)) {
        return 29;
      }
      return _DAYS_IN_MONTH[month];
    }
    function daysBeforeYear(year) {
      const y2 = year - 1;
      return y2 * 365 + Math.trunc(y2 / 4) - Math.trunc(y2 / 100) + Math.trunc(y2 / 400);
    }
    function daysBeforeMonth(year, month) {
      return _DAYS_BEFORE_MONTH[month] + (month > 2 && isLeapYear2(year) ? 1 : 0);
    }
    var _DI400Y = daysBeforeYear(401);
    var _DI100Y = daysBeforeYear(101);
    var _DI4Y = daysBeforeYear(5);
    var _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var _DAYS_BEFORE_MONTH = (() => {
      const dbf = [-1];
      let dbm = 0;
      for (let i4 = 1; i4 < _DAYS_IN_MONTH.length; i4++) {
        const dim = _DAYS_IN_MONTH[i4];
        dbf.push(dbm);
        dbm += dim;
      }
      return dbf;
    })();
    function ymd2ord(year, month, day) {
      return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
    }
    function divmod(dividend, divisor) {
      const quotient = Math.floor(dividend / divisor);
      return [quotient, dividend - divisor * quotient];
    }
    function ord2ymd(n3) {
      n3--;
      let n400;
      [n400, n3] = divmod(n3, _DI400Y);
      let year = n400 * 400 + 1;
      let n100;
      [n100, n3] = divmod(n3, _DI100Y);
      let n4;
      [n4, n3] = divmod(n3, _DI4Y);
      let n1;
      [n1, n3] = divmod(n3, 365);
      year += n100 * 100 + n4 * 4 + n1;
      if (n1 === 4 || n100 === 4) {
        return [year - 1, 12, 31];
      }
      const leapyear = n1 === 3 && (n4 !== 24 || n100 === 3);
      let month = n3 + 50 >> 5;
      let preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
      if (preceding > n3) {
        month -= 1;
        preceding -= _DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
      }
      n3 -= preceding;
      return [year, month, n3 + 1];
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js
var require_datetime = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalDateTime = exports2.LocalDate = exports2.localDateInstances = exports2.LocalTime = exports2.localTimeInstances = exports2.DATE_PRIVATE = void 0;
    exports2.LocalDateToOrdinal = LocalDateToOrdinal;
    exports2.LocalDateFromOrdinal = LocalDateFromOrdinal;
    exports2.parseHumanDurationString = parseHumanDurationString;
    var dateutil_1 = require_dateutil();
    exports2.DATE_PRIVATE = Symbol.for("gel.datetime");
    function toNumber(val2) {
      const n3 = Number(val2);
      if (Number.isNaN(n3)) {
        return 0;
      }
      return n3;
    }
    function assertInteger(val2) {
      if (!Number.isInteger(val2)) {
        throw new RangeError(`unsupported fractional value ${val2}`);
      }
      return val2;
    }
    exports2.localTimeInstances = /* @__PURE__ */ new WeakMap();
    var LocalTime = class {
      hour;
      minute;
      second;
      millisecond;
      microsecond;
      nanosecond;
      constructor(isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
        isoHour = Math.floor(toNumber(isoHour));
        isoMinute = Math.floor(toNumber(isoMinute));
        isoSecond = Math.floor(toNumber(isoSecond));
        isoMillisecond = Math.floor(toNumber(isoMillisecond));
        isoMicrosecond = Math.floor(toNumber(isoMicrosecond));
        isoNanosecond = Math.floor(toNumber(isoNanosecond));
        if (isoHour < 0 || isoHour > 23) {
          throw new RangeError(`invalid number of hours ${isoHour}: expected a value in 0-23 range`);
        }
        if (isoMinute < 0 || isoMinute > 59) {
          throw new RangeError(`invalid number of minutes ${isoMinute}: expected a value in 0-59 range`);
        }
        if (isoSecond < 0 || isoSecond > 59) {
          throw new RangeError(`invalid number of seconds ${isoSecond}: expected a value in 0-59 range`);
        }
        if (isoMillisecond < 0 || isoMillisecond > 999) {
          throw new RangeError(`invalid number of milliseconds ${isoMillisecond}: expected a value in 0-999 range`);
        }
        if (isoMicrosecond < 0 || isoMicrosecond > 999) {
          throw new RangeError(`invalid number of microseconds ${isoMicrosecond}: expected a value in 0-999 range`);
        }
        if (isoNanosecond < 0 || isoNanosecond > 999) {
          throw new RangeError(`invalid number of nanoseconds ${isoNanosecond}: expected a value in 0-999 range`);
        }
        this.hour = isoHour;
        this.minute = isoMinute;
        this.second = isoSecond;
        this.millisecond = isoMillisecond;
        this.microsecond = isoMicrosecond;
        this.nanosecond = isoNanosecond;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "LocalTime");
      }
      toString() {
        const hh = this.hour.toString().padStart(2, "0");
        const mm = this.minute.toString().padStart(2, "0");
        const ss = this.second.toString().padStart(2, "0");
        let repr = `${hh}:${mm}:${ss}`;
        if (this.millisecond || this.microsecond || this.nanosecond) {
          repr += `.${this.millisecond.toString().padStart(3, "0")}${this.microsecond.toString().padStart(3, "0")}${this.nanosecond.toString().padStart(3, "0")}`.replace(/(?:0+)$/, "");
        }
        return repr;
      }
    };
    exports2.LocalTime = LocalTime;
    exports2.localDateInstances = /* @__PURE__ */ new WeakMap();
    var LocalDate = class {
      constructor(isoYear, isoMonth, isoDay) {
        isoYear = Math.trunc(toNumber(isoYear));
        isoMonth = Math.floor(toNumber(isoMonth));
        isoDay = Math.floor(toNumber(isoDay));
        if (isoYear < -271820 || isoYear > 275759) {
          throw new RangeError(`invalid year ${isoYear}: expected a value in -271820-275759 range`);
        }
        if (isoMonth < 1 || isoMonth > 12) {
          throw new RangeError(`invalid month ${isoMonth}: expected a value in 1-12 range`);
        }
        const maxDays = (0, dateutil_1.daysInMonth)(isoYear, isoMonth);
        if (isoDay < 1 || isoDay > maxDays) {
          throw new RangeError(`invalid number of days ${isoDay}: expected a value in 1-${maxDays} range`);
        }
        const date = new Date(Date.UTC(isoYear, isoMonth - 1, isoDay));
        if (isoYear >= 0 && isoYear <= 99) {
          date.setUTCFullYear(isoYear);
        }
        exports2.localDateInstances.set(this, date);
        forwardJsonAsToString(this);
        throwOnValueOf(this, "LocalDate");
      }
      get year() {
        return exports2.localDateInstances.get(this).getUTCFullYear();
      }
      get month() {
        return exports2.localDateInstances.get(this).getUTCMonth() + 1;
      }
      get day() {
        return exports2.localDateInstances.get(this).getUTCDate();
      }
      get dayOfWeek() {
        return (exports2.localDateInstances.get(this).getUTCDay() + 6) % 7 + 1;
      }
      get dayOfYear() {
        const date = exports2.localDateInstances.get(this);
        return (0, dateutil_1.daysBeforeMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1) + date.getUTCDate();
      }
      get daysInWeek() {
        return 7;
      }
      get daysInMonth() {
        const date = exports2.localDateInstances.get(this);
        return (0, dateutil_1.daysInMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1);
      }
      get daysInYear() {
        return this.inLeapYear ? 366 : 365;
      }
      get monthsInYear() {
        return 12;
      }
      get inLeapYear() {
        return (0, dateutil_1.isLeapYear)(exports2.localDateInstances.get(this).getUTCFullYear());
      }
      toString() {
        const year = this.year < 0 || this.year > 9999 ? (this.year < 0 ? "-" : "+") + Math.abs(this.year).toString().padStart(6, "0") : this.year.toString().padStart(4, "0");
        const month = this.month.toString().padStart(2, "0");
        const day = this.day.toString().padStart(2, "0");
        return `${year}-${month}-${day}`;
      }
    };
    exports2.LocalDate = LocalDate;
    function LocalDateToOrdinal(localdate) {
      return (0, dateutil_1.ymd2ord)(localdate.year, localdate.month, localdate.day);
    }
    function LocalDateFromOrdinal(ordinal) {
      const [year, month, day] = (0, dateutil_1.ord2ymd)(ordinal);
      return new LocalDate(year, month, day);
    }
    var LocalDateTime = class extends LocalDate {
      constructor(isoYear, isoMonth, isoDay, isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
        super(isoYear, isoMonth, isoDay);
        const time = new LocalTime(isoHour, isoMinute, isoSecond, isoMillisecond, isoMicrosecond, isoNanosecond);
        exports2.localTimeInstances.set(this, time);
        throwOnValueOf(this, "LocalDateTime");
      }
      get hour() {
        return exports2.localTimeInstances.get(this).hour;
      }
      get minute() {
        return exports2.localTimeInstances.get(this).minute;
      }
      get second() {
        return exports2.localTimeInstances.get(this).second;
      }
      get millisecond() {
        return exports2.localTimeInstances.get(this).millisecond;
      }
      get microsecond() {
        return exports2.localTimeInstances.get(this).microsecond;
      }
      get nanosecond() {
        return exports2.localTimeInstances.get(this).nanosecond;
      }
      toString() {
        return `${super.toString()}T${exports2.localTimeInstances.get(this).toString()}`;
      }
    };
    exports2.LocalDateTime = LocalDateTime;
    var durationRegex2 = new RegExp(`^(\\-|\\+)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(T(?:(\\d+)(\\.\\d{1,10})?H)?(?:(\\d+)(\\.\\d{1,10})?M)?(?:(\\d+)(\\.\\d{1,9})?S)?)?$`, "i");
    var Duration = class _Duration {
      years;
      months;
      weeks;
      days;
      hours;
      minutes;
      seconds;
      milliseconds;
      microseconds;
      nanoseconds;
      sign;
      constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0, nanoseconds = 0) {
        years = assertInteger(toNumber(years));
        months = assertInteger(toNumber(months));
        weeks = assertInteger(toNumber(weeks));
        days = assertInteger(toNumber(days));
        hours = assertInteger(toNumber(hours));
        minutes = assertInteger(toNumber(minutes));
        seconds = assertInteger(toNumber(seconds));
        milliseconds = assertInteger(toNumber(milliseconds));
        microseconds = assertInteger(toNumber(microseconds));
        nanoseconds = assertInteger(toNumber(nanoseconds));
        const fields = [
          years,
          months,
          weeks,
          days,
          hours,
          minutes,
          seconds,
          milliseconds,
          microseconds,
          nanoseconds
        ];
        let sign = 0;
        for (const field of fields) {
          if (field === Infinity || field === -Infinity) {
            throw new RangeError("infinite values not allowed as duration fields");
          }
          const fieldSign = Math.sign(field);
          if (sign && fieldSign && fieldSign !== sign) {
            throw new RangeError("mixed-sign values not allowed as duration fields");
          }
          sign = sign || fieldSign;
        }
        this.years = years || 0;
        this.months = months || 0;
        this.weeks = weeks || 0;
        this.days = days || 0;
        this.hours = hours || 0;
        this.minutes = minutes || 0;
        this.seconds = seconds || 0;
        this.milliseconds = milliseconds || 0;
        this.microseconds = microseconds || 0;
        this.nanoseconds = nanoseconds || 0;
        this.sign = sign || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "TemporalDuration");
      }
      get blank() {
        return this.sign === 0;
      }
      toString() {
        let dateParts = "";
        if (this.years) {
          dateParts += BigInt(Math.abs(this.years)) + "Y";
        }
        if (this.months) {
          dateParts += BigInt(Math.abs(this.months)) + "M";
        }
        if (this.weeks) {
          dateParts += BigInt(Math.abs(this.weeks)) + "W";
        }
        if (this.days) {
          dateParts += BigInt(Math.abs(this.days)) + "D";
        }
        let timeParts = "";
        if (this.hours) {
          timeParts += BigInt(Math.abs(this.hours)) + "H";
        }
        if (this.minutes) {
          timeParts += BigInt(Math.abs(this.minutes)) + "M";
        }
        if (!dateParts && !timeParts || this.seconds || this.milliseconds || this.microseconds || this.nanoseconds) {
          const totalNanoseconds = (BigInt(Math.abs(this.seconds)) * BigInt(1e9) + BigInt(Math.abs(this.milliseconds)) * BigInt(1e6) + BigInt(Math.abs(this.microseconds)) * BigInt(1e3) + BigInt(Math.abs(this.nanoseconds))).toString().padStart(10, "0");
          const seconds = totalNanoseconds.slice(0, -9);
          const fracSeconds = totalNanoseconds.slice(-9).replace(/0+$/, "");
          timeParts += seconds + (fracSeconds.length ? "." + fracSeconds : "") + "S";
        }
        return (this.sign === -1 ? "-" : "") + "P" + dateParts + (timeParts ? "T" + timeParts : "");
      }
      static from(item) {
        let result;
        if (item instanceof _Duration) {
          result = item;
        }
        if (typeof item === "object") {
          if (item.years === void 0 && item.months === void 0 && item.weeks === void 0 && item.days === void 0 && item.hours === void 0 && item.minutes === void 0 && item.seconds === void 0 && item.milliseconds === void 0 && item.microseconds === void 0 && item.nanoseconds === void 0) {
            throw new TypeError(`invalid duration-like`);
          }
          result = item;
        } else {
          const str = String(item);
          const matches = str.match(durationRegex2);
          if (!matches) {
            throw new RangeError(`invalid duration: ${str}`);
          }
          const [_duration, _sign, years, months, weeks, days, _time, hours, fHours, minutes, fMinutes, seconds, fSeconds] = matches;
          if (_duration.length < 3 || _time.length === 1) {
            throw new RangeError(`invalid duration: ${str}`);
          }
          const sign = _sign === "-" ? -1 : 1;
          result = {};
          if (years) {
            result.years = sign * Number(years);
          }
          if (months) {
            result.months = sign * Number(months);
          }
          if (weeks) {
            result.weeks = sign * Number(weeks);
          }
          if (days) {
            result.days = sign * Number(days);
          }
          if (hours) {
            result.hours = sign * Number(hours);
          }
          if (fHours) {
            if (minutes || fMinutes || seconds || fSeconds) {
              throw new RangeError("only the smallest unit can be fractional");
            }
            result.minutes = Number(fHours) * 60;
          } else {
            result.minutes = toNumber(minutes);
          }
          if (fMinutes) {
            if (seconds || fSeconds) {
              throw new RangeError("only the smallest unit can be fractional");
            }
            result.seconds = Number(fMinutes) * 60;
          } else if (seconds) {
            result.seconds = Number(seconds);
          } else {
            result.seconds = result.minutes % 1 * 60;
          }
          if (fSeconds) {
            const ns = fSeconds.slice(1).padEnd(9, "0");
            result.milliseconds = Number(ns.slice(0, 3));
            result.microseconds = Number(ns.slice(3, 6));
            result.nanoseconds = sign * Number(ns.slice(6));
          } else {
            result.milliseconds = result.seconds % 1 * 1e3;
            result.microseconds = result.milliseconds % 1 * 1e3;
            result.nanoseconds = sign * Math.floor(result.microseconds % 1 * 1e3);
          }
          result.minutes = sign * Math.floor(result.minutes);
          result.seconds = sign * Math.floor(result.seconds);
          result.milliseconds = sign * Math.floor(result.milliseconds);
          result.microseconds = sign * Math.floor(result.microseconds);
        }
        return new _Duration(result.years, result.months, result.weeks, result.days, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds);
      }
    };
    exports2.Duration = Duration;
    var RelativeDuration = class {
      years;
      months;
      weeks;
      days;
      hours;
      minutes;
      seconds;
      milliseconds;
      microseconds;
      constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0) {
        this.years = Math.trunc(years) || 0;
        this.months = Math.trunc(months) || 0;
        this.weeks = Math.trunc(weeks) || 0;
        this.days = Math.trunc(days) || 0;
        this.hours = Math.trunc(hours) || 0;
        this.minutes = Math.trunc(minutes) || 0;
        this.seconds = Math.trunc(seconds) || 0;
        this.milliseconds = Math.trunc(milliseconds) || 0;
        this.microseconds = Math.trunc(microseconds) || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "RelativeDuration");
      }
      toString() {
        let str = "P";
        if (this.years) {
          str += `${this.years}Y`;
        }
        if (this.months) {
          str += `${this.months}M`;
        }
        const days = this.days + 7 * this.weeks;
        if (days) {
          str += `${days}D`;
        }
        let timeParts = "";
        if (this.hours) {
          timeParts += `${this.hours}H`;
        }
        if (this.minutes) {
          timeParts += `${this.minutes}M`;
        }
        const seconds = this.seconds + this.milliseconds / 1e3 + this.microseconds / 1e6;
        if (seconds !== 0) {
          timeParts += `${seconds}S`;
        }
        if (timeParts) {
          str += `T${timeParts}`;
        }
        if (str === "P") {
          return "PT0S";
        }
        return str;
      }
    };
    exports2.RelativeDuration = RelativeDuration;
    var DateDuration = class {
      years;
      months;
      weeks;
      days;
      constructor(years = 0, months = 0, weeks = 0, days = 0) {
        this.years = Math.trunc(years) || 0;
        this.months = Math.trunc(months) || 0;
        this.weeks = Math.trunc(weeks) || 0;
        this.days = Math.trunc(days) || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "DateDuration");
      }
      toString() {
        let str = "P";
        if (this.years) {
          str += `${this.years}Y`;
        }
        if (this.months) {
          str += `${this.months}M`;
        }
        const days = this.days + 7 * this.weeks;
        if (days) {
          str += `${days}D`;
        }
        if (str === "P") {
          return "PT0S";
        }
        return str;
      }
    };
    exports2.DateDuration = DateDuration;
    var humanDurationPrefixes = {
      h: 36e5,
      hou: 36e5,
      m: 6e4,
      min: 6e4,
      s: 1e3,
      sec: 1e3,
      ms: 1,
      mil: 1
    };
    function parseHumanDurationString(durationStr) {
      const regex = /(\d+|\d+\.\d+|\.\d+)\s*(hours?|minutes?|seconds?|milliseconds?|ms|h|m|s)\s*/g;
      let duration = 0;
      const seen = /* @__PURE__ */ new Set();
      let match2 = regex.exec(durationStr);
      let lastIndex = 0;
      while (match2) {
        if (match2.index !== lastIndex) {
          throw new Error(`invalid duration "${durationStr}"`);
        }
        const mult = humanDurationPrefixes[match2[2].slice(0, 3)];
        if (seen.has(mult)) {
          throw new Error(`invalid duration "${durationStr}"`);
        }
        duration += Number(match2[1]) * mult;
        seen.add(mult);
        lastIndex = regex.lastIndex;
        match2 = regex.exec(durationStr);
      }
      if (lastIndex !== durationStr.length) {
        throw new Error(`invalid duration "${durationStr}"`);
      }
      return duration;
    }
    var forwardJsonAsToString = (obj) => {
      Object.defineProperty(obj, "toJSON", {
        value: () => obj.toString(),
        enumerable: false,
        configurable: true
      });
    };
    var throwOnValueOf = (obj, typename) => {
      Object.defineProperty(obj, "valueOf", {
        value: () => {
          throw new TypeError(`Not possible to compare ${typename}`);
        },
        enumerable: false,
        configurable: true
      });
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js
var require_datetime2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DateDurationCodec = exports2.RelativeDurationCodec = exports2.DurationCodec = exports2.LocalTimeCodec = exports2.LocalDateCodec = exports2.LocalDateTimeCodec = exports2.DateTimeCodec = void 0;
    exports2.checkValidGelDuration = checkValidGelDuration;
    var ifaces_1 = require_ifaces();
    var datetime_1 = require_datetime();
    var dateutil_1 = require_dateutil();
    var errors_1 = require_errors();
    var TIMESHIFT = 9466848e5;
    var BI_TIMESHIFT_US = BigInt(TIMESHIFT) * 1000n;
    var DATESHIFT_ORD = (0, dateutil_1.ymd2ord)(2e3, 1, 1);
    var DateTimeCodec = class extends ifaces_1.ScalarCodec {
      tsType = "Date";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (typeof val2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::datetime codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(val2 - BI_TIMESHIFT_US);
          return;
        }
        if (!(object instanceof Date)) {
          throw new errors_1.InvalidArgumentError(`a Date instance was expected, got "${object}"`);
        }
        const ms = object.getTime() - TIMESHIFT;
        const us = ms * 1e3;
        buf.writeInt32(8);
        buf.writeInt64(us);
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = buf.readBigInt64();
          return ctx.postDecode(this, us2 + BI_TIMESHIFT_US);
        }
        const us = Number(buf.readBigInt64());
        let ms = Math.round(us / 1e3);
        if (Math.abs(us % 1e3) === 500 && Math.abs(ms) % 2 === 1) {
          ms -= 1;
        }
        ms += TIMESHIFT;
        return new Date(ms);
      }
    };
    exports2.DateTimeCodec = DateTimeCodec;
    var LocalDateTimeCodec = class extends ifaces_1.ScalarCodec {
      tsType = "LocalDateTime";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          let us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_datetime codec`);
          }
          us2 -= BI_TIMESHIFT_US;
          buf.writeInt32(8);
          buf.writeBigInt64(us2);
          return;
        }
        if (!(object instanceof datetime_1.LocalDateTime)) {
          throw new errors_1.InvalidArgumentError(`a LocalDateTime instance was expected, got "${object}"`);
        }
        const ms = BigInt(datetime_1.localDateInstances.get(object).getTime() - TIMESHIFT);
        let us = ms * 1000n + BigInt(object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond);
        if (object.nanosecond === 500 && Math.abs(object.microsecond) % 2 === 1 || object.nanosecond > 500) {
          us += 1n;
        }
        buf.writeInt32(8);
        buf.writeBigInt64(us);
      }
      decode(buf, ctx) {
        const bi_us = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, BigInt(bi_us + BI_TIMESHIFT_US));
        }
        const bi_ms = bi_us / 1000n;
        let us = Number(bi_us - bi_ms * 1000n);
        let ms = Number(bi_ms);
        if (us < 0) {
          us += 1e3;
          ms -= 1;
        }
        ms += TIMESHIFT;
        const date = new Date(ms);
        return new datetime_1.LocalDateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), us);
      }
    };
    exports2.LocalDateTimeCodec = LocalDateTimeCodec;
    var LocalDateCodec = class extends ifaces_1.ScalarCodec {
      tsType = "LocalDate";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          const ord2 = (0, dateutil_1.ymd2ord)(...ret);
          buf.writeInt32(4);
          buf.writeInt32(ord2 - DATESHIFT_ORD);
          return;
        }
        if (!(object instanceof datetime_1.LocalDate)) {
          throw new errors_1.InvalidArgumentError(`a LocalDate instance was expected, got "${object}"`);
        }
        const ord = (0, datetime_1.LocalDateToOrdinal)(object);
        buf.writeInt32(4);
        buf.writeInt32(ord - DATESHIFT_ORD);
      }
      decode(buf, ctx) {
        const ord = buf.readInt32() + DATESHIFT_ORD;
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, (0, dateutil_1.ord2ymd)(ord));
        }
        return (0, datetime_1.LocalDateFromOrdinal)(ord);
      }
    };
    exports2.LocalDateCodec = LocalDateCodec;
    var LocalTimeCodec = class extends ifaces_1.ScalarCodec {
      tsType = "LocalTime";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_time codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(us2);
          return;
        }
        if (!(object instanceof datetime_1.LocalTime)) {
          throw new errors_1.InvalidArgumentError(`a LocalTime instance was expected, got "${object}"`);
        }
        let us = object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond;
        if (object.nanosecond === 500 && us % 2 === 1 || object.nanosecond > 500) {
          us += 1;
        }
        buf.writeInt32(8);
        buf.writeInt64(us);
      }
      decode(buf, ctx) {
        const bius = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, bius);
        }
        let us = Number(bius);
        let seconds = Math.floor(us / 1e6);
        const ms = Math.floor(us % 1e6 / 1e3);
        us = us % 1e6 - ms * 1e3;
        let minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        const hours = Math.floor(minutes / 60);
        minutes = Math.floor(minutes % 60);
        return new datetime_1.LocalTime(hours, minutes, seconds, ms, us);
      }
    };
    exports2.LocalTimeCodec = LocalTimeCodec;
    var unencodableDurationFields = [
      "years",
      "months",
      "weeks",
      "days"
    ];
    function checkValidGelDuration(duration) {
      for (const field of unencodableDurationFields) {
        if (duration[field] !== 0) {
          return field;
        }
      }
      return null;
    }
    var DurationCodec = class extends ifaces_1.ScalarCodec {
      tsType = "Duration";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::duration codec`);
          }
          buf.writeInt32(16);
          buf.writeBigInt64(us2);
          buf.writeInt32(0);
          buf.writeInt32(0);
          return;
        }
        if (!(object instanceof datetime_1.Duration)) {
          throw new errors_1.InvalidArgumentError(`a Duration instance was expected, got "${object}"`);
        }
        const invalidField = checkValidGelDuration(object);
        if (invalidField) {
          throw new errors_1.InvalidArgumentError(`Cannot encode a 'Duration' with a non-zero number of ${invalidField}`);
        }
        let us = BigInt(Math.abs(object.microseconds));
        us += BigInt(Math.abs(object.milliseconds)) * BigInt(1e3);
        us += BigInt(Math.abs(object.seconds)) * BigInt(1e6);
        us += BigInt(Math.abs(object.minutes)) * BigInt(6e7);
        us += BigInt(Math.abs(object.hours)) * BigInt(36e8);
        if (Math.abs(object.nanoseconds) === 500 && Math.abs(object.microseconds) % 2 === 1 || Math.abs(object.nanoseconds) > 500) {
          us += 1n;
        }
        if (object.sign < 0) {
          us *= -1n;
        }
        buf.writeInt32(16);
        buf.writeBigInt64(us);
        buf.writeInt32(0);
        buf.writeInt32(0);
      }
      decode(buf, ctx) {
        let bius = buf.readBigInt64();
        const days = buf.readInt32();
        const months = buf.readInt32();
        if (days !== 0) {
          throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
        }
        if (months !== 0) {
          throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, bius);
        }
        let sign = 1;
        if (Number(bius) < 0) {
          sign = -1;
          bius *= -1n;
        }
        const biMillion = 1000000n;
        const biSeconds = bius / biMillion;
        let us = Number(bius - biSeconds * biMillion);
        const ms = Math.floor(us / 1e3);
        us = us % 1e3;
        let seconds = Number(biSeconds);
        let minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        const hours = Math.floor(minutes / 60);
        minutes = Math.floor(minutes % 60);
        return new datetime_1.Duration(0, 0, 0, 0, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
      }
    };
    exports2.DurationCodec = DurationCodec;
    var RelativeDurationCodec = class extends ifaces_1.ScalarCodec {
      tsType = "RelativeDuration";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          buf.writeInt32(16);
          buf.writeBigInt64(ret[2]);
          buf.writeInt32(ret[1]);
          buf.writeInt32(ret[0]);
          return;
        }
        if (!(object instanceof datetime_1.RelativeDuration)) {
          throw new errors_1.InvalidArgumentError(`
        a RelativeDuration instance was expected, got "${object}"
      `);
        }
        const us = BigInt(object.microseconds) + BigInt(object.milliseconds) * BigInt(1e3) + BigInt(object.seconds) * BigInt(1e6) + BigInt(object.minutes) * BigInt(6e7) + BigInt(object.hours) * BigInt(36e8);
        buf.writeInt32(16);
        buf.writeBigInt64(us);
        buf.writeInt32(object.days + 7 * object.weeks);
        buf.writeInt32(object.months + 12 * object.years);
      }
      decode(buf, ctx) {
        let bius = buf.readBigInt64();
        let days = buf.readInt32();
        let months = buf.readInt32();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            months,
            days,
            bius
          ]);
        }
        let sign = 1;
        if (Number(bius) < 0) {
          sign = -1;
          bius *= -1n;
        }
        const million = BigInt(1e6);
        const biSeconds = bius / million;
        let us = Number(bius - biSeconds * million);
        const ms = Math.trunc(us / 1e3);
        us = us % 1e3;
        let seconds = Number(biSeconds);
        let minutes = Math.trunc(seconds / 60);
        seconds = Math.trunc(seconds % 60);
        const hours = Math.trunc(minutes / 60);
        minutes = Math.trunc(minutes % 60);
        const weeks = Math.trunc(days / 7);
        days = Math.trunc(days % 7);
        const years = Math.trunc(months / 12);
        months = Math.trunc(months % 12);
        return new datetime_1.RelativeDuration(years, months, weeks, days, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
      }
    };
    exports2.RelativeDurationCodec = RelativeDurationCodec;
    var DateDurationCodec = class extends ifaces_1.ScalarCodec {
      tsType = "DateDuration";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          buf.writeInt32(16);
          buf.writeInt64(0);
          buf.writeInt32(ret[1]);
          buf.writeInt32(ret[0]);
          return;
        }
        if (!(object instanceof datetime_1.DateDuration)) {
          throw new errors_1.InvalidArgumentError(`
        a DateDuration instance was expected, got "${object}"
      `);
        }
        buf.writeInt32(16);
        buf.writeInt64(0);
        buf.writeInt32(object.days + 7 * object.weeks);
        buf.writeInt32(object.months + 12 * object.years);
      }
      decode(buf, ctx) {
        buf.discard(8);
        let days = buf.readInt32();
        let months = buf.readInt32();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [months, days]);
        }
        const weeks = Math.trunc(days / 7);
        days = Math.trunc(days % 7);
        const years = Math.trunc(months / 12);
        months = Math.trunc(months % 12);
        return new datetime_1.DateDuration(years, months, weeks, days);
      }
    };
    exports2.DateDurationCodec = DateDurationCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js
var require_memory = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConfigMemory = void 0;
    var KiB = 1024;
    var MiB = 1024 * KiB;
    var GiB = 1024 * MiB;
    var TiB = 1024 * GiB;
    var PiB = 1024 * TiB;
    var ConfigMemory = class {
      _bytes;
      constructor(bytes) {
        this._bytes = bytes;
      }
      get bytes() {
        return Number(this._bytes);
      }
      get bytesBigInt() {
        return this._bytes;
      }
      get kibibytes() {
        return Number(this._bytes) / KiB;
      }
      get mebibytes() {
        return Number(this._bytes) / MiB;
      }
      get gibibytes() {
        return Number(this._bytes) / GiB;
      }
      get tebibytes() {
        return Number(this._bytes) / TiB;
      }
      get pebibytes() {
        return Number(this._bytes) / PiB;
      }
      toString() {
        const bytes = this._bytes;
        const bigPiB = BigInt(PiB);
        if (bytes >= bigPiB && Number(bytes % bigPiB) === 0) {
          return `${bytes / bigPiB}PiB`;
        }
        const bigTiB = BigInt(TiB);
        if (bytes >= bigTiB && Number(bytes % bigTiB) === 0) {
          return `${bytes / bigTiB}TiB`;
        }
        const bigGiB = BigInt(GiB);
        if (bytes >= bigGiB && Number(bytes % bigGiB) === 0) {
          return `${bytes / bigGiB}GiB`;
        }
        const bigMiB = BigInt(MiB);
        if (bytes >= bigMiB && Number(bytes % bigMiB) === 0) {
          return `${bytes / bigMiB}MiB`;
        }
        const bigKiB = BigInt(KiB);
        if (bytes >= bigKiB && Number(bytes % bigKiB) === 0) {
          return `${bytes / bigKiB}KiB`;
        }
        return `${bytes}B`;
      }
    };
    exports2.ConfigMemory = ConfigMemory;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js
var require_memory2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConfigMemoryCodec = void 0;
    var ifaces_1 = require_ifaces();
    var memory_1 = require_memory();
    var errors_1 = require_errors();
    var ConfigMemoryCodec = class extends ifaces_1.ScalarCodec {
      tsType = "ConfigMemory";
      tsModule = "gel";
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (typeof val2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cfg::memory codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(val2);
          return;
        }
        if (!(object instanceof memory_1.ConfigMemory)) {
          throw new errors_1.InvalidArgumentError(`a ConfigMemory instance was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeBigInt64(object._bytes);
      }
      decode(buf, ctx) {
        const val2 = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, val2);
        }
        return new memory_1.ConfigMemory(val2);
      }
    };
    exports2.ConfigMemoryCodec = ConfigMemoryCodec;
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs
var require_messages = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var THIS_IS_NOT_AN_OBJECT = exports2.THIS_IS_NOT_AN_OBJECT = "This is not an object";
    var THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = exports2.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
    var THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = exports2.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = "This constructor is not a subclass of Float16Array";
    var THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = exports2.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = "The constructor property value is not an object";
    var SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = exports2.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = "Species constructor didn't return TypedArray object";
    var DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = exports2.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = "Derived constructor created TypedArray object which was too small length";
    var ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = exports2.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = "Attempting to access detached ArrayBuffer";
    var CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = exports2.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = "Cannot convert undefined or null to object";
    var CANNOT_MIX_BIGINT_AND_OTHER_TYPES = exports2.CANNOT_MIX_BIGINT_AND_OTHER_TYPES = "Cannot mix BigInt and other types, use explicit conversions";
    var ITERATOR_PROPERTY_IS_NOT_CALLABLE = exports2.ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
    var REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = exports2.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = "Reduce of empty array with no initial value";
    var THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = exports2.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = "The comparison function must be either a function or undefined";
    var OFFSET_IS_OUT_OF_BOUNDS = exports2.OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs
var require_primordials = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var _messages = require_messages();
    function uncurryThis(target) {
      return (thisArg, ...args) => {
        return ReflectApply(target, thisArg, args);
      };
    }
    function uncurryThisGetter(target, key) {
      return uncurryThis(ReflectGetOwnPropertyDescriptor(target, key).get);
    }
    var {
      apply: ReflectApply,
      construct: ReflectConstruct,
      defineProperty: ReflectDefineProperty,
      get: ReflectGet,
      getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
      getPrototypeOf: ReflectGetPrototypeOf,
      has: ReflectHas,
      ownKeys: ReflectOwnKeys,
      set: ReflectSet,
      setPrototypeOf: ReflectSetPrototypeOf
    } = Reflect;
    exports2.ReflectSetPrototypeOf = ReflectSetPrototypeOf;
    exports2.ReflectSet = ReflectSet;
    exports2.ReflectOwnKeys = ReflectOwnKeys;
    exports2.ReflectHas = ReflectHas;
    exports2.ReflectGetPrototypeOf = ReflectGetPrototypeOf;
    exports2.ReflectGetOwnPropertyDescriptor = ReflectGetOwnPropertyDescriptor;
    exports2.ReflectGet = ReflectGet;
    exports2.ReflectDefineProperty = ReflectDefineProperty;
    exports2.ReflectConstruct = ReflectConstruct;
    exports2.ReflectApply = ReflectApply;
    var NativeProxy = exports2.NativeProxy = Proxy;
    var {
      EPSILON,
      MAX_SAFE_INTEGER,
      isFinite: NumberIsFinite,
      isNaN: NumberIsNaN
    } = Number;
    exports2.NumberIsNaN = NumberIsNaN;
    exports2.NumberIsFinite = NumberIsFinite;
    exports2.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
    exports2.EPSILON = EPSILON;
    var {
      iterator: SymbolIterator,
      species: SymbolSpecies,
      toStringTag: SymbolToStringTag,
      for: SymbolFor
    } = Symbol;
    exports2.SymbolFor = SymbolFor;
    exports2.SymbolToStringTag = SymbolToStringTag;
    exports2.SymbolSpecies = SymbolSpecies;
    exports2.SymbolIterator = SymbolIterator;
    var NativeObject = exports2.NativeObject = Object;
    var {
      create: ObjectCreate,
      defineProperty: ObjectDefineProperty,
      freeze: ObjectFreeze,
      is: ObjectIs
    } = NativeObject;
    exports2.ObjectIs = ObjectIs;
    exports2.ObjectFreeze = ObjectFreeze;
    exports2.ObjectDefineProperty = ObjectDefineProperty;
    exports2.ObjectCreate = ObjectCreate;
    var ObjectPrototype = NativeObject.prototype;
    var ObjectPrototype__lookupGetter__ = exports2.ObjectPrototype__lookupGetter__ = ObjectPrototype.__lookupGetter__ ? uncurryThis(ObjectPrototype.__lookupGetter__) : (object, key) => {
      if (object == null) {
        throw NativeTypeError(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
      }
      let target = NativeObject(object);
      do {
        const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
        if (descriptor !== void 0) {
          if (ObjectHasOwn(descriptor, "get")) {
            return descriptor.get;
          }
          return;
        }
      } while ((target = ReflectGetPrototypeOf(target)) !== null);
    };
    var ObjectHasOwn = exports2.ObjectHasOwn = NativeObject.hasOwn || uncurryThis(ObjectPrototype.hasOwnProperty);
    var NativeArray = Array;
    var ArrayIsArray = exports2.ArrayIsArray = NativeArray.isArray;
    var ArrayPrototype = NativeArray.prototype;
    var ArrayPrototypeJoin = exports2.ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
    var ArrayPrototypePush = exports2.ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
    var ArrayPrototypeToLocaleString = exports2.ArrayPrototypeToLocaleString = uncurryThis(ArrayPrototype.toLocaleString);
    var NativeArrayPrototypeSymbolIterator = exports2.NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
    var ArrayPrototypeSymbolIterator = exports2.ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
    var {
      abs: MathAbs,
      trunc: MathTrunc
    } = Math;
    exports2.MathTrunc = MathTrunc;
    exports2.MathAbs = MathAbs;
    var NativeArrayBuffer = exports2.NativeArrayBuffer = ArrayBuffer;
    var ArrayBufferIsView = exports2.ArrayBufferIsView = NativeArrayBuffer.isView;
    var ArrayBufferPrototype = NativeArrayBuffer.prototype;
    var ArrayBufferPrototypeSlice = exports2.ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
    var ArrayBufferPrototypeGetByteLength = exports2.ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
    var NativeSharedArrayBuffer = exports2.NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
    var SharedArrayBufferPrototypeGetByteLength = exports2.SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
    var TypedArray = exports2.TypedArray = ReflectGetPrototypeOf(Uint8Array);
    var TypedArrayFrom = TypedArray.from;
    var TypedArrayPrototype = exports2.TypedArrayPrototype = TypedArray.prototype;
    var NativeTypedArrayPrototypeSymbolIterator = exports2.NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
    var TypedArrayPrototypeKeys = exports2.TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
    var TypedArrayPrototypeValues = exports2.TypedArrayPrototypeValues = uncurryThis(TypedArrayPrototype.values);
    var TypedArrayPrototypeEntries = exports2.TypedArrayPrototypeEntries = uncurryThis(TypedArrayPrototype.entries);
    var TypedArrayPrototypeSet = exports2.TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
    var TypedArrayPrototypeReverse = exports2.TypedArrayPrototypeReverse = uncurryThis(TypedArrayPrototype.reverse);
    var TypedArrayPrototypeFill = exports2.TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
    var TypedArrayPrototypeCopyWithin = exports2.TypedArrayPrototypeCopyWithin = uncurryThis(TypedArrayPrototype.copyWithin);
    var TypedArrayPrototypeSort = exports2.TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
    var TypedArrayPrototypeSlice = exports2.TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
    var TypedArrayPrototypeSubarray = exports2.TypedArrayPrototypeSubarray = uncurryThis(TypedArrayPrototype.subarray);
    var TypedArrayPrototypeGetBuffer = exports2.TypedArrayPrototypeGetBuffer = uncurryThisGetter(TypedArrayPrototype, "buffer");
    var TypedArrayPrototypeGetByteOffset = exports2.TypedArrayPrototypeGetByteOffset = uncurryThisGetter(TypedArrayPrototype, "byteOffset");
    var TypedArrayPrototypeGetLength = exports2.TypedArrayPrototypeGetLength = uncurryThisGetter(TypedArrayPrototype, "length");
    var TypedArrayPrototypeGetSymbolToStringTag = exports2.TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(TypedArrayPrototype, SymbolToStringTag);
    var NativeUint8Array = exports2.NativeUint8Array = Uint8Array;
    var NativeUint16Array = exports2.NativeUint16Array = Uint16Array;
    var Uint16ArrayFrom = (...args) => {
      return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
    };
    exports2.Uint16ArrayFrom = Uint16ArrayFrom;
    var NativeUint32Array = exports2.NativeUint32Array = Uint32Array;
    var NativeFloat32Array = exports2.NativeFloat32Array = Float32Array;
    var ArrayIteratorPrototype = exports2.ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
    var ArrayIteratorPrototypeNext = exports2.ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
    var GeneratorPrototypeNext = exports2.GeneratorPrototypeNext = uncurryThis(function* () {
    }().next);
    var IteratorPrototype = exports2.IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
    var DataViewPrototype = DataView.prototype;
    var DataViewPrototypeGetUint16 = exports2.DataViewPrototypeGetUint16 = uncurryThis(DataViewPrototype.getUint16);
    var DataViewPrototypeSetUint16 = exports2.DataViewPrototypeSetUint16 = uncurryThis(DataViewPrototype.setUint16);
    var NativeTypeError = exports2.NativeTypeError = TypeError;
    var NativeRangeError = exports2.NativeRangeError = RangeError;
    var NativeWeakSet = exports2.NativeWeakSet = WeakSet;
    var WeakSetPrototype = NativeWeakSet.prototype;
    var WeakSetPrototypeAdd = exports2.WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
    var WeakSetPrototypeHas = exports2.WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
    var NativeWeakMap = exports2.NativeWeakMap = WeakMap;
    var WeakMapPrototype = NativeWeakMap.prototype;
    var WeakMapPrototypeGet = exports2.WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
    var WeakMapPrototypeHas = exports2.WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
    var WeakMapPrototypeSet = exports2.WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs
var require_arrayIterator = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.safeIfNeeded = safeIfNeeded;
    exports2.wrap = wrap;
    var _primordials = require_primordials();
    var arrayIterators = new _primordials.NativeWeakMap();
    var SafeIteratorPrototype = (0, _primordials.ObjectCreate)(null, {
      next: {
        value: function next() {
          const arrayIterator = (0, _primordials.WeakMapPrototypeGet)(arrayIterators, this);
          return (0, _primordials.ArrayIteratorPrototypeNext)(arrayIterator);
        }
      },
      [_primordials.SymbolIterator]: {
        value: function values() {
          return this;
        }
      }
    });
    function safeIfNeeded(array2) {
      if (array2[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext) {
        return array2;
      }
      const safe = (0, _primordials.ObjectCreate)(SafeIteratorPrototype);
      (0, _primordials.WeakMapPrototypeSet)(arrayIterators, safe, (0, _primordials.ArrayPrototypeSymbolIterator)(array2));
      return safe;
    }
    var generators = new _primordials.NativeWeakMap();
    var DummyArrayIteratorPrototype = (0, _primordials.ObjectCreate)(_primordials.IteratorPrototype, {
      next: {
        value: function next() {
          const generator = (0, _primordials.WeakMapPrototypeGet)(generators, this);
          return (0, _primordials.GeneratorPrototypeNext)(generator);
        },
        writable: true,
        configurable: true
      }
    });
    for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.ArrayIteratorPrototype)) {
      if (key === "next") {
        continue;
      }
      (0, _primordials.ObjectDefineProperty)(DummyArrayIteratorPrototype, key, (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.ArrayIteratorPrototype, key));
    }
    function wrap(generator) {
      const dummy = (0, _primordials.ObjectCreate)(DummyArrayIteratorPrototype);
      (0, _primordials.WeakMapPrototypeSet)(generators, dummy, generator);
      return dummy;
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs
var require_is = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isAnyArrayBuffer = isAnyArrayBuffer;
    exports2.isCanonicalIntegerIndexString = isCanonicalIntegerIndexString;
    exports2.isNativeBigIntTypedArray = isNativeBigIntTypedArray;
    exports2.isNativeTypedArray = isNativeTypedArray;
    exports2.isObject = isObject;
    exports2.isObjectLike = isObjectLike;
    exports2.isOrdinaryArray = isOrdinaryArray;
    exports2.isOrdinaryNativeTypedArray = isOrdinaryNativeTypedArray;
    exports2.isSharedArrayBuffer = isSharedArrayBuffer;
    var _primordials = require_primordials();
    function isObject(value) {
      return value !== null && typeof value === "object" || typeof value === "function";
    }
    function isObjectLike(value) {
      return value !== null && typeof value === "object";
    }
    function isNativeTypedArray(value) {
      return (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value) !== void 0;
    }
    function isNativeBigIntTypedArray(value) {
      const typedArrayName = (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value);
      return typedArrayName === "BigInt64Array" || typedArrayName === "BigUint64Array";
    }
    function isArrayBuffer(value) {
      try {
        if ((0, _primordials.ArrayIsArray)(value)) {
          return false;
        }
        (0, _primordials.ArrayBufferPrototypeGetByteLength)(value);
        return true;
      } catch (e4) {
        return false;
      }
    }
    function isSharedArrayBuffer(value) {
      if (_primordials.NativeSharedArrayBuffer === null) {
        return false;
      }
      try {
        (0, _primordials.SharedArrayBufferPrototypeGetByteLength)(value);
        return true;
      } catch (e4) {
        return false;
      }
    }
    function isAnyArrayBuffer(value) {
      return isArrayBuffer(value) || isSharedArrayBuffer(value);
    }
    function isOrdinaryArray(value) {
      if (!(0, _primordials.ArrayIsArray)(value)) {
        return false;
      }
      return value[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
    }
    function isOrdinaryNativeTypedArray(value) {
      if (!isNativeTypedArray(value)) {
        return false;
      }
      return value[_primordials.SymbolIterator] === _primordials.NativeTypedArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
    }
    function isCanonicalIntegerIndexString(value) {
      if (typeof value !== "string") {
        return false;
      }
      const number2 = +value;
      if (value !== number2 + "") {
        return false;
      }
      if (!(0, _primordials.NumberIsFinite)(number2)) {
        return false;
      }
      return number2 === (0, _primordials.MathTrunc)(number2);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs
var require_brand = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.hasFloat16ArrayBrand = hasFloat16ArrayBrand;
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    var brand = exports2.brand = (0, _primordials.SymbolFor)("__Float16Array__");
    function hasFloat16ArrayBrand(target) {
      if (!(0, _is.isObjectLike)(target)) {
        return false;
      }
      const prototype = (0, _primordials.ReflectGetPrototypeOf)(target);
      if (!(0, _is.isObjectLike)(prototype)) {
        return false;
      }
      const constructor = prototype.constructor;
      if (constructor === void 0) {
        return false;
      }
      if (!(0, _is.isObject)(constructor)) {
        throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
      }
      return (0, _primordials.ReflectHas)(constructor, brand);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs
var require_converter = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.convertToNumber = convertToNumber;
    exports2.roundToFloat16 = roundToFloat16;
    exports2.roundToFloat16Bits = roundToFloat16Bits;
    var _primordials = require_primordials();
    var INVERSE_OF_EPSILON = 1 / _primordials.EPSILON;
    function roundTiesToEven(num) {
      return num + INVERSE_OF_EPSILON - INVERSE_OF_EPSILON;
    }
    var FLOAT16_MIN_VALUE = 6103515625e-14;
    var FLOAT16_MAX_VALUE = 65504;
    var FLOAT16_EPSILON = 9765625e-10;
    var FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
    var FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
    function roundToFloat16(num) {
      const number2 = +num;
      if (!(0, _primordials.NumberIsFinite)(number2) || number2 === 0) {
        return number2;
      }
      const sign = number2 > 0 ? 1 : -1;
      const absolute = (0, _primordials.MathAbs)(number2);
      if (absolute < FLOAT16_MIN_VALUE) {
        return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
      }
      const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
      const result = temp - (temp - absolute);
      if (result > FLOAT16_MAX_VALUE || (0, _primordials.NumberIsNaN)(result)) {
        return sign * Infinity;
      }
      return sign * result;
    }
    var buffer = new _primordials.NativeArrayBuffer(4);
    var floatView = new _primordials.NativeFloat32Array(buffer);
    var uint32View = new _primordials.NativeUint32Array(buffer);
    var baseTable = new _primordials.NativeUint16Array(512);
    var shiftTable = new _primordials.NativeUint8Array(512);
    for (let i4 = 0; i4 < 256; ++i4) {
      const e4 = i4 - 127;
      if (e4 < -24) {
        baseTable[i4] = 0;
        baseTable[i4 | 256] = 32768;
        shiftTable[i4] = 24;
        shiftTable[i4 | 256] = 24;
      } else if (e4 < -14) {
        baseTable[i4] = 1024 >> -e4 - 14;
        baseTable[i4 | 256] = 1024 >> -e4 - 14 | 32768;
        shiftTable[i4] = -e4 - 1;
        shiftTable[i4 | 256] = -e4 - 1;
      } else if (e4 <= 15) {
        baseTable[i4] = e4 + 15 << 10;
        baseTable[i4 | 256] = e4 + 15 << 10 | 32768;
        shiftTable[i4] = 13;
        shiftTable[i4 | 256] = 13;
      } else if (e4 < 128) {
        baseTable[i4] = 31744;
        baseTable[i4 | 256] = 64512;
        shiftTable[i4] = 24;
        shiftTable[i4 | 256] = 24;
      } else {
        baseTable[i4] = 31744;
        baseTable[i4 | 256] = 64512;
        shiftTable[i4] = 13;
        shiftTable[i4 | 256] = 13;
      }
    }
    function roundToFloat16Bits(num) {
      floatView[0] = roundToFloat16(num);
      const f5 = uint32View[0];
      const e4 = f5 >> 23 & 511;
      return baseTable[e4] + ((f5 & 8388607) >> shiftTable[e4]);
    }
    var mantissaTable = new _primordials.NativeUint32Array(2048);
    for (let i4 = 1; i4 < 1024; ++i4) {
      let m4 = i4 << 13;
      let e4 = 0;
      while ((m4 & 8388608) === 0) {
        m4 <<= 1;
        e4 -= 8388608;
      }
      m4 &= ~8388608;
      e4 += 947912704;
      mantissaTable[i4] = m4 | e4;
    }
    for (let i4 = 1024; i4 < 2048; ++i4) {
      mantissaTable[i4] = 939524096 + (i4 - 1024 << 13);
    }
    var exponentTable = new _primordials.NativeUint32Array(64);
    for (let i4 = 1; i4 < 31; ++i4) {
      exponentTable[i4] = i4 << 23;
    }
    exponentTable[31] = 1199570944;
    exponentTable[32] = 2147483648;
    for (let i4 = 33; i4 < 63; ++i4) {
      exponentTable[i4] = 2147483648 + (i4 - 32 << 23);
    }
    exponentTable[63] = 3347054592;
    var offsetTable = new _primordials.NativeUint16Array(64);
    for (let i4 = 1; i4 < 64; ++i4) {
      if (i4 !== 32) {
        offsetTable[i4] = 1024;
      }
    }
    function convertToNumber(float16bits) {
      const i4 = float16bits >> 10;
      uint32View[0] = mantissaTable[offsetTable[i4] + (float16bits & 1023)] + exponentTable[i4];
      return floatView[0];
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs
var require_spec = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.IsDetachedBuffer = IsDetachedBuffer;
    exports2.SpeciesConstructor = SpeciesConstructor;
    exports2.ToIntegerOrInfinity = ToIntegerOrInfinity;
    exports2.ToLength = ToLength;
    exports2.defaultCompare = defaultCompare;
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    function ToIntegerOrInfinity(target) {
      const number2 = +target;
      if ((0, _primordials.NumberIsNaN)(number2) || number2 === 0) {
        return 0;
      }
      return (0, _primordials.MathTrunc)(number2);
    }
    function ToLength(target) {
      const length = ToIntegerOrInfinity(target);
      if (length < 0) {
        return 0;
      }
      return length < _primordials.MAX_SAFE_INTEGER ? length : _primordials.MAX_SAFE_INTEGER;
    }
    function SpeciesConstructor(target, defaultConstructor) {
      if (!(0, _is.isObject)(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_AN_OBJECT);
      }
      const constructor = target.constructor;
      if (constructor === void 0) {
        return defaultConstructor;
      }
      if (!(0, _is.isObject)(constructor)) {
        throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
      }
      const species = constructor[_primordials.SymbolSpecies];
      if (species == null) {
        return defaultConstructor;
      }
      return species;
    }
    function IsDetachedBuffer(buffer) {
      if ((0, _is.isSharedArrayBuffer)(buffer)) {
        return false;
      }
      try {
        (0, _primordials.ArrayBufferPrototypeSlice)(buffer, 0, 0);
        return false;
      } catch (e4) {
      }
      return true;
    }
    function defaultCompare(x4, y2) {
      const isXNaN = (0, _primordials.NumberIsNaN)(x4);
      const isYNaN = (0, _primordials.NumberIsNaN)(y2);
      if (isXNaN && isYNaN) {
        return 0;
      }
      if (isXNaN) {
        return 1;
      }
      if (isYNaN) {
        return -1;
      }
      if (x4 < y2) {
        return -1;
      }
      if (x4 > y2) {
        return 1;
      }
      if (x4 === 0 && y2 === 0) {
        const isXPlusZero = (0, _primordials.ObjectIs)(x4, 0);
        const isYPlusZero = (0, _primordials.ObjectIs)(y2, 0);
        if (!isXPlusZero && isYPlusZero) {
          return -1;
        }
        if (isXPlusZero && !isYPlusZero) {
          return 1;
        }
      }
      return 0;
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs
var require_Float16Array = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isFloat16Array = isFloat16Array;
    var _arrayIterator = require_arrayIterator();
    var _brand = require_brand();
    var _converter = require_converter();
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    var _spec = require_spec();
    var BYTES_PER_ELEMENT = 2;
    var float16bitsArrays = new _primordials.NativeWeakMap();
    function isFloat16Array(target) {
      return (0, _primordials.WeakMapPrototypeHas)(float16bitsArrays, target) || !(0, _primordials.ArrayBufferIsView)(target) && (0, _brand.hasFloat16ArrayBrand)(target);
    }
    function assertFloat16Array(target) {
      if (!isFloat16Array(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT);
      }
    }
    function assertSpeciesTypedArray(target, count) {
      const isTargetFloat16Array = isFloat16Array(target);
      const isTargetTypedArray = (0, _is.isNativeTypedArray)(target);
      if (!isTargetFloat16Array && !isTargetTypedArray) {
        throw (0, _primordials.NativeTypeError)(_messages.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT);
      }
      if (typeof count === "number") {
        let length;
        if (isTargetFloat16Array) {
          const float16bitsArray = getFloat16BitsArray(target);
          length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        } else {
          length = (0, _primordials.TypedArrayPrototypeGetLength)(target);
        }
        if (length < count) {
          throw (0, _primordials.NativeTypeError)(_messages.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH);
        }
      }
      if ((0, _is.isNativeBigIntTypedArray)(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
      }
    }
    function getFloat16BitsArray(float16) {
      const float16bitsArray = (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, float16);
      if (float16bitsArray !== void 0) {
        const buffer2 = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
        if ((0, _spec.IsDetachedBuffer)(buffer2)) {
          throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
        }
        return float16bitsArray;
      }
      const buffer = float16.buffer;
      if ((0, _spec.IsDetachedBuffer)(buffer)) {
        throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
      }
      const cloned = (0, _primordials.ReflectConstruct)(Float16Array, [buffer, float16.byteOffset, float16.length], float16.constructor);
      return (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, cloned);
    }
    function copyToArray(float16bitsArray) {
      const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
      const array2 = [];
      for (let i4 = 0; i4 < length; ++i4) {
        array2[i4] = (0, _converter.convertToNumber)(float16bitsArray[i4]);
      }
      return array2;
    }
    var TypedArrayPrototypeGetters = new _primordials.NativeWeakSet();
    for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.TypedArrayPrototype)) {
      if (key === _primordials.SymbolToStringTag) {
        continue;
      }
      const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.TypedArrayPrototype, key);
      if ((0, _primordials.ObjectHasOwn)(descriptor, "get") && typeof descriptor.get === "function") {
        (0, _primordials.WeakSetPrototypeAdd)(TypedArrayPrototypeGetters, descriptor.get);
      }
    }
    var handler = (0, _primordials.ObjectFreeze)({
      get(target, key, receiver) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          return (0, _converter.convertToNumber)((0, _primordials.ReflectGet)(target, key));
        }
        if ((0, _primordials.WeakSetPrototypeHas)(TypedArrayPrototypeGetters, (0, _primordials.ObjectPrototype__lookupGetter__)(target, key))) {
          return (0, _primordials.ReflectGet)(target, key);
        }
        return (0, _primordials.ReflectGet)(target, key, receiver);
      },
      set(target, key, value, receiver) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          return (0, _primordials.ReflectSet)(target, key, (0, _converter.roundToFloat16Bits)(value));
        }
        return (0, _primordials.ReflectSet)(target, key, value, receiver);
      },
      getOwnPropertyDescriptor(target, key) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
          descriptor.value = (0, _converter.convertToNumber)(descriptor.value);
          return descriptor;
        }
        return (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
      },
      defineProperty(target, key, descriptor) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key) && (0, _primordials.ObjectHasOwn)(descriptor, "value")) {
          descriptor.value = (0, _converter.roundToFloat16Bits)(descriptor.value);
          return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
        }
        return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
      }
    });
    var Float16Array = class _Float16Array {
      constructor(input, _byteOffset, _length) {
        let float16bitsArray;
        if (isFloat16Array(input)) {
          float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [getFloat16BitsArray(input)], new.target);
        } else if ((0, _is.isObject)(input) && !(0, _is.isAnyArrayBuffer)(input)) {
          let list;
          let length;
          if ((0, _is.isNativeTypedArray)(input)) {
            list = input;
            length = (0, _primordials.TypedArrayPrototypeGetLength)(input);
            const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
            if ((0, _spec.IsDetachedBuffer)(buffer)) {
              throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
            }
            if ((0, _is.isNativeBigIntTypedArray)(input)) {
              throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
            }
            const data = new _primordials.NativeArrayBuffer(length * BYTES_PER_ELEMENT);
            float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [data], new.target);
          } else {
            const iterator = input[_primordials.SymbolIterator];
            if (iterator != null && typeof iterator !== "function") {
              throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
            }
            if (iterator != null) {
              if ((0, _is.isOrdinaryArray)(input)) {
                list = input;
                length = input.length;
              } else {
                list = [...input];
                length = list.length;
              }
            } else {
              list = input;
              length = (0, _spec.ToLength)(list.length);
            }
            float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [length], new.target);
          }
          for (let i4 = 0; i4 < length; ++i4) {
            float16bitsArray[i4] = (0, _converter.roundToFloat16Bits)(list[i4]);
          }
        } else {
          float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, arguments, new.target);
        }
        const proxy = new _primordials.NativeProxy(float16bitsArray, handler);
        (0, _primordials.WeakMapPrototypeSet)(float16bitsArrays, proxy, float16bitsArray);
        return proxy;
      }
      static from(src, ...opts) {
        const Constructor = this;
        if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
          throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
        }
        if (Constructor === _Float16Array) {
          if (isFloat16Array(src) && opts.length === 0) {
            const float16bitsArray = getFloat16BitsArray(src);
            const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
            return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
          }
          if (opts.length === 0) {
            return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, _converter.roundToFloat16Bits)));
          }
          const mapFunc = opts[0];
          const thisArg = opts[1];
          return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, function(val2, ...args) {
            return (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(mapFunc, this, [val2, ...(0, _arrayIterator.safeIfNeeded)(args)]));
          }, thisArg)));
        }
        let list;
        let length;
        const iterator = src[_primordials.SymbolIterator];
        if (iterator != null && typeof iterator !== "function") {
          throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
        }
        if (iterator != null) {
          if ((0, _is.isOrdinaryArray)(src)) {
            list = src;
            length = src.length;
          } else if ((0, _is.isOrdinaryNativeTypedArray)(src)) {
            list = src;
            length = (0, _primordials.TypedArrayPrototypeGetLength)(src);
          } else {
            list = [...src];
            length = list.length;
          }
        } else {
          if (src == null) {
            throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
          }
          list = (0, _primordials.NativeObject)(src);
          length = (0, _spec.ToLength)(list.length);
        }
        const array2 = new Constructor(length);
        if (opts.length === 0) {
          for (let i4 = 0; i4 < length; ++i4) {
            array2[i4] = list[i4];
          }
        } else {
          const mapFunc = opts[0];
          const thisArg = opts[1];
          for (let i4 = 0; i4 < length; ++i4) {
            array2[i4] = (0, _primordials.ReflectApply)(mapFunc, thisArg, [list[i4], i4]);
          }
        }
        return array2;
      }
      static of(...items) {
        const Constructor = this;
        if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
          throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
        }
        const length = items.length;
        if (Constructor === _Float16Array) {
          const proxy = new _Float16Array(length);
          const float16bitsArray = getFloat16BitsArray(proxy);
          for (let i4 = 0; i4 < length; ++i4) {
            float16bitsArray[i4] = (0, _converter.roundToFloat16Bits)(items[i4]);
          }
          return proxy;
        }
        const array2 = new Constructor(length);
        for (let i4 = 0; i4 < length; ++i4) {
          array2[i4] = items[i4];
        }
        return array2;
      }
      keys() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _primordials.TypedArrayPrototypeKeys)(float16bitsArray);
      }
      values() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _arrayIterator.wrap)(function* () {
          for (const val2 of (0, _primordials.TypedArrayPrototypeValues)(float16bitsArray)) {
            yield (0, _converter.convertToNumber)(val2);
          }
        }());
      }
      entries() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _arrayIterator.wrap)(function* () {
          for (const [i4, val2] of (0, _primordials.TypedArrayPrototypeEntries)(float16bitsArray)) {
            yield [i4, (0, _converter.convertToNumber)(val2)];
          }
        }());
      }
      at(index6) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
        const k3 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
        if (k3 < 0 || k3 >= length) {
          return;
        }
        return (0, _converter.convertToNumber)(float16bitsArray[k3]);
      }
      with(index6, value) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
        const k3 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
        const number2 = +value;
        if (k3 < 0 || k3 >= length) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const array2 = getFloat16BitsArray(cloned);
        array2[k3] = (0, _converter.roundToFloat16Bits)(number2);
        return cloned;
      }
      map(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        if (Constructor === _Float16Array) {
          const proxy = new _Float16Array(length);
          const array3 = getFloat16BitsArray(proxy);
          for (let i4 = 0; i4 < length; ++i4) {
            const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
            array3[i4] = (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this]));
          }
          return proxy;
        }
        const array2 = new Constructor(length);
        assertSpeciesTypedArray(array2, length);
        for (let i4 = 0; i4 < length; ++i4) {
          const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          array2[i4] = (0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this]);
        }
        return array2;
      }
      filter(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        const kept = [];
        for (let i4 = 0; i4 < length; ++i4) {
          const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this])) {
            (0, _primordials.ArrayPrototypePush)(kept, val2);
          }
        }
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        const array2 = new Constructor(kept);
        assertSpeciesTypedArray(array2);
        return array2;
      }
      reduce(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        if (length === 0 && opts.length === 0) {
          throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
        }
        let accumulator, start;
        if (opts.length === 0) {
          accumulator = (0, _converter.convertToNumber)(float16bitsArray[0]);
          start = 1;
        } else {
          accumulator = opts[0];
          start = 0;
        }
        for (let i4 = start; i4 < length; ++i4) {
          accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this);
        }
        return accumulator;
      }
      reduceRight(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        if (length === 0 && opts.length === 0) {
          throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
        }
        let accumulator, start;
        if (opts.length === 0) {
          accumulator = (0, _converter.convertToNumber)(float16bitsArray[length - 1]);
          start = length - 2;
        } else {
          accumulator = opts[0];
          start = length - 1;
        }
        for (let i4 = start; i4 >= 0; --i4) {
          accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this);
        }
        return accumulator;
      }
      forEach(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = 0; i4 < length; ++i4) {
          (0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this]);
        }
      }
      find(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = 0; i4 < length; ++i4) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
            return value;
          }
        }
      }
      findIndex(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = 0; i4 < length; ++i4) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
            return i4;
          }
        }
        return -1;
      }
      findLast(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = length - 1; i4 >= 0; --i4) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
            return value;
          }
        }
      }
      findLastIndex(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = length - 1; i4 >= 0; --i4) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
            return i4;
          }
        }
        return -1;
      }
      every(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = 0; i4 < length; ++i4) {
          if (!(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this])) {
            return false;
          }
        }
        return true;
      }
      some(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i4 = 0; i4 < length; ++i4) {
          if ((0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this])) {
            return true;
          }
        }
        return false;
      }
      set(input, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const targetOffset = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (targetOffset < 0) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        if (input == null) {
          throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
        }
        if ((0, _is.isNativeBigIntTypedArray)(input)) {
          throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
        }
        if (isFloat16Array(input)) {
          return (0, _primordials.TypedArrayPrototypeSet)(getFloat16BitsArray(this), getFloat16BitsArray(input), targetOffset);
        }
        if ((0, _is.isNativeTypedArray)(input)) {
          const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
          if ((0, _spec.IsDetachedBuffer)(buffer)) {
            throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
          }
        }
        const targetLength = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const src = (0, _primordials.NativeObject)(input);
        const srcLength = (0, _spec.ToLength)(src.length);
        if (targetOffset === Infinity || srcLength + targetOffset > targetLength) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        for (let i4 = 0; i4 < srcLength; ++i4) {
          float16bitsArray[i4 + targetOffset] = (0, _converter.roundToFloat16Bits)(src[i4]);
        }
      }
      reverse() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeReverse)(float16bitsArray);
        return this;
      }
      toReversed() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
        (0, _primordials.TypedArrayPrototypeReverse)(clonedFloat16bitsArray);
        return cloned;
      }
      fill(value, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeFill)(float16bitsArray, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
        return this;
      }
      copyWithin(target, start, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeCopyWithin)(float16bitsArray, target, start, ...(0, _arrayIterator.safeIfNeeded)(opts));
        return this;
      }
      sort(compareFn) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
        (0, _primordials.TypedArrayPrototypeSort)(float16bitsArray, (x4, y2) => {
          return sortCompare((0, _converter.convertToNumber)(x4), (0, _converter.convertToNumber)(y2));
        });
        return this;
      }
      toSorted(compareFn) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        if (compareFn !== void 0 && typeof compareFn !== "function") {
          throw new _primordials.NativeTypeError(_messages.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED);
        }
        const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
        (0, _primordials.TypedArrayPrototypeSort)(clonedFloat16bitsArray, (x4, y2) => {
          return sortCompare((0, _converter.convertToNumber)(x4), (0, _converter.convertToNumber)(y2));
        });
        return cloned;
      }
      slice(start, end) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        if (Constructor === _Float16Array) {
          const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
          return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16, start, end)));
        }
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeStart = (0, _spec.ToIntegerOrInfinity)(start);
        const relativeEnd = end === void 0 ? length : (0, _spec.ToIntegerOrInfinity)(end);
        let k3;
        if (relativeStart === -Infinity) {
          k3 = 0;
        } else if (relativeStart < 0) {
          k3 = length + relativeStart > 0 ? length + relativeStart : 0;
        } else {
          k3 = length < relativeStart ? length : relativeStart;
        }
        let final;
        if (relativeEnd === -Infinity) {
          final = 0;
        } else if (relativeEnd < 0) {
          final = length + relativeEnd > 0 ? length + relativeEnd : 0;
        } else {
          final = length < relativeEnd ? length : relativeEnd;
        }
        const count = final - k3 > 0 ? final - k3 : 0;
        const array2 = new Constructor(count);
        assertSpeciesTypedArray(array2, count);
        if (count === 0) {
          return array2;
        }
        const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
        if ((0, _spec.IsDetachedBuffer)(buffer)) {
          throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
        }
        let n3 = 0;
        while (k3 < final) {
          array2[n3] = (0, _converter.convertToNumber)(float16bitsArray[k3]);
          ++k3;
          ++n3;
        }
        return array2;
      }
      subarray(begin, end) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const uint16Subarray = (0, _primordials.TypedArrayPrototypeSubarray)(uint16, begin, end);
        const array2 = new Constructor((0, _primordials.TypedArrayPrototypeGetBuffer)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetLength)(uint16Subarray));
        assertSpeciesTypedArray(array2);
        return array2;
      }
      indexOf(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (from === Infinity) {
          return -1;
        }
        if (from < 0) {
          from += length;
          if (from < 0) {
            from = 0;
          }
        }
        for (let i4 = from; i4 < length; ++i4) {
          if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i4) && (0, _converter.convertToNumber)(float16bitsArray[i4]) === element) {
            return i4;
          }
        }
        return -1;
      }
      lastIndexOf(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = opts.length >= 1 ? (0, _spec.ToIntegerOrInfinity)(opts[0]) : length - 1;
        if (from === -Infinity) {
          return -1;
        }
        if (from >= 0) {
          from = from < length - 1 ? from : length - 1;
        } else {
          from += length;
        }
        for (let i4 = from; i4 >= 0; --i4) {
          if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i4) && (0, _converter.convertToNumber)(float16bitsArray[i4]) === element) {
            return i4;
          }
        }
        return -1;
      }
      includes(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (from === Infinity) {
          return false;
        }
        if (from < 0) {
          from += length;
          if (from < 0) {
            from = 0;
          }
        }
        const isNaN2 = (0, _primordials.NumberIsNaN)(element);
        for (let i4 = from; i4 < length; ++i4) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
          if (isNaN2 && (0, _primordials.NumberIsNaN)(value)) {
            return true;
          }
          if (value === element) {
            return true;
          }
        }
        return false;
      }
      join(separator) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const array2 = copyToArray(float16bitsArray);
        return (0, _primordials.ArrayPrototypeJoin)(array2, separator);
      }
      toLocaleString(...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const array2 = copyToArray(float16bitsArray);
        return (0, _primordials.ArrayPrototypeToLocaleString)(array2, ...(0, _arrayIterator.safeIfNeeded)(opts));
      }
      get [_primordials.SymbolToStringTag]() {
        if (isFloat16Array(this)) {
          return "Float16Array";
        }
      }
    };
    exports2.Float16Array = Float16Array;
    (0, _primordials.ObjectDefineProperty)(Float16Array, "BYTES_PER_ELEMENT", {
      value: BYTES_PER_ELEMENT
    });
    (0, _primordials.ObjectDefineProperty)(Float16Array, _brand.brand, {});
    (0, _primordials.ReflectSetPrototypeOf)(Float16Array, _primordials.TypedArray);
    var Float16ArrayPrototype = Float16Array.prototype;
    (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, "BYTES_PER_ELEMENT", {
      value: BYTES_PER_ELEMENT
    });
    (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, _primordials.SymbolIterator, {
      value: Float16ArrayPrototype.values,
      writable: true,
      configurable: true
    });
    (0, _primordials.ReflectSetPrototypeOf)(Float16ArrayPrototype, _primordials.TypedArrayPrototype);
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs
var require_isTypedArray = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isTypedArray = isTypedArray;
    var _Float16Array = require_Float16Array();
    var _is = require_is();
    function isTypedArray(target) {
      return (0, _is.isNativeTypedArray)(target) || (0, _Float16Array.isFloat16Array)(target);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs
var require_DataView = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.getFloat16 = getFloat16;
    exports2.setFloat16 = setFloat16;
    var _arrayIterator = require_arrayIterator();
    var _converter = require_converter();
    var _primordials = require_primordials();
    function getFloat16(dataView, byteOffset, ...opts) {
      return (0, _converter.convertToNumber)((0, _primordials.DataViewPrototypeGetUint16)(dataView, byteOffset, ...(0, _arrayIterator.safeIfNeeded)(opts)));
    }
    function setFloat16(dataView, byteOffset, value, ...opts) {
      return (0, _primordials.DataViewPrototypeSetUint16)(dataView, byteOffset, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs
var require_f16round = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.f16round = f16round;
    var _converter = require_converter();
    function f16round(x4) {
      return (0, _converter.roundToFloat16)(x4);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs
var require_lib2 = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var _Float16Array = require_Float16Array();
    exports2.Float16Array = _Float16Array.Float16Array;
    exports2.isFloat16Array = _Float16Array.isFloat16Array;
    var _isTypedArray = require_isTypedArray();
    exports2.isTypedArray = _isTypedArray.isTypedArray;
    var _DataView = require_DataView();
    exports2.getFloat16 = _DataView.getFloat16;
    exports2.setFloat16 = _DataView.setFloat16;
    var _f16round = require_f16round();
    exports2.f16round = _f16round.f16round;
    exports2.hfround = _f16round.f16round;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js
var require_utils2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.setFloat16 = exports2.isFloat16Array = exports2.getFloat16 = exports2.Float16Array = void 0;
    exports2.getUniqueId = getUniqueId;
    exports2.sleep = sleep;
    exports2.versionEqual = versionEqual;
    exports2.versionGreaterThan = versionGreaterThan;
    exports2.versionGreaterThanOrEqual = versionGreaterThanOrEqual;
    exports2.getAuthenticatedFetch = getAuthenticatedFetch;
    var float16_1 = require_lib2();
    Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
      return float16_1.Float16Array;
    } });
    Object.defineProperty(exports2, "getFloat16", { enumerable: true, get: function() {
      return float16_1.getFloat16;
    } });
    Object.defineProperty(exports2, "isFloat16Array", { enumerable: true, get: function() {
      return float16_1.isFloat16Array;
    } });
    Object.defineProperty(exports2, "setFloat16", { enumerable: true, get: function() {
      return float16_1.setFloat16;
    } });
    var idCounter = {};
    function getUniqueId(prefix2 = "") {
      if (!idCounter[prefix2]) {
        idCounter[prefix2] = 0;
      }
      const id = ++idCounter[prefix2];
      return `_gel_${prefix2}_${id.toString(16)}_`;
    }
    function sleep(durationMillis) {
      return new Promise((accept) => {
        setTimeout(() => accept(), durationMillis);
      });
    }
    function versionEqual(left, right) {
      return left[0] === right[0] && left[1] === right[1];
    }
    function versionGreaterThan(left, right) {
      if (left[0] > right[0]) {
        return true;
      }
      if (left[0] < right[0]) {
        return false;
      }
      return left[1] > right[1];
    }
    function versionGreaterThanOrEqual(left, right) {
      if (left[0] === right[0] && left[1] === right[1]) {
        return true;
      }
      return versionGreaterThan(left, right);
    }
    var _tokens = /* @__PURE__ */ new WeakMap();
    async function getAuthenticatedFetch(config, httpSCRAMAuth, basePath) {
      let token = config.secretKey ?? _tokens.get(config);
      const { address, tlsSecurity, database } = config;
      const protocol = tlsSecurity === "insecure" ? "http" : "https";
      const baseUrl = `${protocol}://${address[0]}:${address[1]}`;
      const databaseUrl = `${baseUrl}/db/${database}/${basePath ?? ""}`;
      if (!token && config.password != null) {
        token = await httpSCRAMAuth(baseUrl, config.user, config.password);
        _tokens.set(config, token);
      }
      return (input, init2) => {
        let path4;
        if (typeof input === "string") {
          path4 = input;
        } else if (input instanceof Request) {
          path4 = input.url;
        } else
          path4 = input.toString();
        const url = new URL(path4, databaseUrl);
        const headers = new Headers(init2 == null ? void 0 : init2.headers);
        if (config.user !== void 0) {
          headers.append("X-EdgeDB-User", config.user);
        }
        if (token !== void 0) {
          headers.append("Authorization", `Bearer ${token}`);
        }
        return fetch(url, {
          ...init2,
          headers
        });
      };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js
var require_pgvector = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SparseVector = void 0;
    var SparseVector = class {
      length;
      indexes;
      values;
      constructor(length, indexesOrMap, values) {
        this.length = length;
        if (indexesOrMap instanceof Uint32Array) {
          if (indexesOrMap.length !== (values == null ? void 0 : values.length)) {
            throw new Error("indexes array must be the same length as the data array");
          }
          if (indexesOrMap.length > length) {
            throw new Error("length of data cannot be larger than length of sparse vector");
          }
          this.values = values;
          this.indexes = indexesOrMap;
        } else {
          const entries = Object.entries(indexesOrMap);
          if (entries.length > length) {
            throw new Error("length of data cannot be larger than length of sparse vector");
          }
          this.indexes = new Uint32Array(entries.length);
          this.values = new Float32Array(entries.length);
          for (let i4 = 0; i4 < entries.length; i4++) {
            const index6 = parseInt(entries[i4][0], 10);
            const val2 = entries[i4][1];
            if (Number.isNaN(index6)) {
              throw new Error(`key ${entries[i4][0]} in data map is not an integer`);
            }
            if (index6 < 0 || index6 >= length) {
              throw new Error(`index ${index6} is out of range of sparse vector length`);
            }
            this.indexes[i4] = index6;
            if (typeof val2 !== "number") {
              throw new Error(`expected value at index ${index6} to be number, got ${typeof val2} ${val2}`);
            }
            if (val2 === 0) {
              throw new Error("elements in sparse vector cannot be 0");
            }
            this.values[i4] = val2;
          }
        }
        return new Proxy(this, {
          get(target, p3) {
            const index6 = typeof p3 === "string" ? parseInt(p3, 10) : NaN;
            if (!Number.isNaN(index6)) {
              if (index6 < 0 || index6 >= target.length)
                return void 0;
              const dataIndex = target.indexes.indexOf(index6);
              return dataIndex === -1 ? 0 : target.values[dataIndex];
            }
            return target[p3];
          }
        });
      }
      *[Symbol.iterator]() {
        let nextIndex = 0;
        for (let i4 = 0; i4 < this.length; i4++) {
          yield this.indexes[nextIndex] === i4 ? this.values[nextIndex++] : 0;
        }
      }
    };
    exports2.SparseVector = SparseVector;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js
var require_pgvector2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PgVectorSparseVecCodec = exports2.PgVectorHalfVecCodec = exports2.PgVectorCodec = exports2.PG_VECTOR_MAX_DIM = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var utils_1 = require_utils2();
    var pgvector_1 = require_pgvector();
    exports2.PG_VECTOR_MAX_DIM = (1 << 16) - 1;
    var PgVectorCodec = class extends ifaces_1.ScalarCodec {
      tsType = "Float32Array";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (!(object instanceof Float32Array || Array.isArray(object))) {
          throw new errors_1.InvalidArgumentError(`a Float32Array or array of numbers was expected, got "${object}"`);
        }
        if (object.length > exports2.PG_VECTOR_MAX_DIM) {
          throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
        }
        buf.writeInt32(4 + object.length * 4).writeUInt16(object.length).writeUInt16(0);
        if (object instanceof Float32Array) {
          for (const el of object) {
            buf.writeFloat32(el);
          }
        } else {
          for (const el of object) {
            if (typeof el !== "number") {
              throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${el}"`);
            }
            buf.writeFloat32(el);
          }
        }
      }
      decode(buf, ctx) {
        const dim = buf.readUInt16();
        buf.discard(2);
        const vecBuf = buf.readBuffer(dim * 4);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const vec = new Float32Array(dim);
        for (let i4 = 0; i4 < dim; i4++) {
          vec[i4] = data.getFloat32(i4 * 4);
        }
        return ctx.postDecode(this, vec);
      }
    };
    exports2.PgVectorCodec = PgVectorCodec;
    var PgVectorHalfVecCodec = class extends ifaces_1.ScalarCodec {
      tsType = "Float16Array";
      tsModule = "gel";
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (!((0, utils_1.isFloat16Array)(object) || Array.isArray(object))) {
          throw new errors_1.InvalidArgumentError(`a Float16Array or array of numbers was expected, got "${object}"`);
        }
        if (object.length > exports2.PG_VECTOR_MAX_DIM) {
          throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
        }
        buf.writeInt32(4 + object.length * 2).writeUInt16(object.length).writeUInt16(0);
        const vecBuf = new Uint8Array(object.length * 2);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        if ((0, utils_1.isFloat16Array)(object)) {
          for (let i4 = 0; i4 < object.length; i4++) {
            (0, utils_1.setFloat16)(data, i4 * 2, object[i4]);
          }
        } else {
          for (let i4 = 0; i4 < object.length; i4++) {
            if (typeof object[i4] !== "number") {
              throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${object[i4]}"`);
            }
            (0, utils_1.setFloat16)(data, i4 * 2, object[i4]);
          }
        }
        buf.writeBuffer(vecBuf);
      }
      decode(buf, ctx) {
        const dim = buf.readUInt16();
        buf.discard(2);
        const vecBuf = buf.readBuffer(dim * 2);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const vec = new utils_1.Float16Array(dim);
        for (let i4 = 0; i4 < dim; i4++) {
          vec[i4] = (0, utils_1.getFloat16)(data, i4 * 2);
        }
        return ctx.postDecode(this, vec);
      }
    };
    exports2.PgVectorHalfVecCodec = PgVectorHalfVecCodec;
    var PgVectorSparseVecCodec = class extends ifaces_1.ScalarCodec {
      tsType = "SparseVector";
      tsModule = "gel";
      encode(buf, object, ctx) {
        let dims;
        let indexes;
        let values;
        if (ctx.hasOverload(this)) {
          [dims, indexes, values] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof pgvector_1.SparseVector)) {
            throw new errors_1.InvalidArgumentError(`a SparseVector was expected, got "${object}"`);
          }
          dims = object.length;
          indexes = object.indexes;
          values = object.values;
        }
        const indexesLength = indexes.length;
        if (indexesLength > exports2.PG_VECTOR_MAX_DIM || indexesLength > dims) {
          throw new errors_1.InvalidArgumentError("too many elements in sparse vector value");
        }
        buf.writeUInt32(4 * (3 + indexesLength * 2)).writeUInt32(dims).writeUInt32(indexesLength).writeUInt32(0);
        const vecBuf = new Uint8Array(indexesLength * 8);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        for (let i4 = 0; i4 < indexesLength; i4++) {
          data.setUint32(i4 * 4, indexes[i4]);
        }
        for (let i4 = 0; i4 < indexesLength; i4++) {
          data.setFloat32((indexesLength + i4) * 4, values[i4]);
        }
        buf.writeBuffer(vecBuf);
      }
      decode(buf, ctx) {
        const dim = buf.readUInt32();
        const nnz = buf.readUInt32();
        buf.discard(4);
        const vecBuf = buf.readBuffer(nnz * 8);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const indexes = new Uint32Array(nnz);
        for (let i4 = 0; i4 < nnz; i4++) {
          indexes[i4] = data.getUint32(i4 * 4);
        }
        const vecData = new Float32Array(nnz);
        for (let i4 = 0; i4 < nnz; i4++) {
          vecData[i4] = data.getFloat32((i4 + nnz) * 4);
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            dim,
            indexes,
            vecData
          ]);
        }
        return new pgvector_1.SparseVector(dim, indexes, vecData);
      }
    };
    exports2.PgVectorSparseVecCodec = PgVectorSparseVecCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js
var require_postgis = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Box3D = exports2.Box2D = exports2.GeometryCollection = exports2.MultiSurface = exports2.TriangulatedIrregularNetwork = exports2.PolyhedralSurface = exports2.MultiPolygon = exports2.CurvePolygon = exports2.Triangle = exports2.Polygon = exports2.MultiCurve = exports2.CompoundCurve = exports2.MultiLineString = exports2.CircularString = exports2.LineString = exports2.MultiPoint = exports2.Point = exports2.Geometry = void 0;
    var Geometry = class {
    };
    exports2.Geometry = Geometry;
    function _pointToWKT(p3) {
      return `${p3.x} ${p3.y}${p3.z !== null ? ` ${p3.z}` : ""}${p3.m !== null ? ` ${p3.m}` : ""}`;
    }
    function _flagsToWKT(z2, m4) {
      return (z2 || m4 ? " " : "") + (z2 ? "Z" : "") + (m4 ? "M" : "");
    }
    function _sridWKTPrefix(srid, depth) {
      return srid !== null && depth === 0 ? `SRID=${srid}; ` : "";
    }
    function _indent(indent, depth) {
      if (!indent)
        return "";
      return "\n" + " ".repeat(indent * depth);
    }
    var Point = class extends Geometry {
      x;
      y;
      z;
      m;
      srid;
      constructor(x4, y2, z2 = null, m4 = null, srid = null) {
        super();
        this.x = x4;
        this.y = y2;
        this.z = z2;
        this.m = m4;
        this.srid = srid;
      }
      get hasZ() {
        return this.z !== null;
      }
      get hasM() {
        return this.m !== null;
      }
      toWKT(_indent2, _truncate = Infinity, depth = 0) {
        return `${_sridWKTPrefix(this.srid, depth)}POINT${_flagsToWKT(this.z !== null, this.m !== null)} ${Number.isNaN(this.x) ? "EMPTY" : "(" + _pointToWKT(this) + ")"}`;
      }
      equals(other) {
        return this.srid === other.srid && (Number.isNaN(this.x) ? this.hasZ === other.hasZ && this.hasM === other.hasM : this.x === other.x && this.y === other.y && this.z === other.z && this.m === other.m);
      }
    };
    exports2.Point = Point;
    var MultiPoint = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTIPOINT${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + "(" + _pointToWKT(this.geometries[i4++]) + (i4 < this.geometries.length ? "), " : ")");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiPoint = MultiPoint;
    function _linestringToWKT(points, indent, truncate = Infinity, depth = 0) {
      let wkt = `(`;
      let i4 = 0;
      while (i4 < points.length && wkt.length < truncate) {
        wkt += _indent(indent, depth + 1) + _pointToWKT(points[i4++]) + (i4 < points.length ? ", " : "");
      }
      return wkt + _indent(indent, depth) + ")";
    }
    var LineString = class extends Geometry {
      points;
      hasZ;
      hasM;
      srid;
      constructor(points, hasZ, hasM, srid) {
        super();
        this.points = points;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        this._validate();
      }
      _validate() {
        if (this.points.length === 1) {
          throw new Error(`expected zero, or 2 or more points in LineString`);
        }
      }
      static _wktName = "LINESTRING";
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.points.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _linestringToWKT(this.points, indent, truncate - wkt.length, depth);
      }
    };
    exports2.LineString = LineString;
    var CircularString = class extends LineString {
      static _wktName = "CIRCULARSTRING";
      _validate() {
        if (this.points.length !== 0 && (this.points.length <= 1 || this.points.length % 2 !== 1)) {
          throw new Error(`expected zero points, or odd number of points greater than 1 in CircularString`);
        }
      }
    };
    exports2.CircularString = CircularString;
    function _multilinestringToWKT(lineStrings, indent, truncate = Infinity, depth = 0) {
      let wkt = `(`;
      let i4 = 0;
      while (i4 < lineStrings.length && wkt.length < truncate) {
        wkt += _indent(indent, depth + 1) + _linestringToWKT(lineStrings[i4++].points, indent, truncate - wkt.length, depth + 1) + (i4 < lineStrings.length ? ", " : "");
      }
      return wkt + _indent(indent, depth) + ")";
    }
    var MultiLineString = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}MULTILINESTRING${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _multilinestringToWKT(this.geometries, indent, truncate - wkt.length, depth);
      }
    };
    exports2.MultiLineString = MultiLineString;
    var CompoundCurve = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        let lastPoint = null;
        for (const segment of geometries) {
          if (lastPoint && !segment.points[0].equals(lastPoint)) {
            throw new Error("segments in CompoundCurve do not join");
          }
          lastPoint = segment.points[segment.points.length - 1];
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}COMPOUNDCURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += "(";
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + (this.geometries[i4] instanceof CircularString ? "CIRCULARSTRING " : "LINESTRING ") + _linestringToWKT(this.geometries[i4++].points, indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.CompoundCurve = CompoundCurve;
    var MultiCurve = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTICURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiCurve = MultiCurve;
    var Polygon = class extends Geometry {
      rings;
      hasZ;
      hasM;
      srid;
      constructor(rings, hasZ, hasM, srid) {
        super();
        this.rings = rings;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        this._validate();
      }
      _validate() {
        if (this.rings.some((ring) => ring.points.length < 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
          throw new Error("expected rings in Polygon to be closed and to have at least 4 points");
        }
      }
      static _wktName = "POLYGON";
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.rings.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _multilinestringToWKT(this.rings, indent, truncate - wkt.length, depth);
      }
    };
    exports2.Polygon = Polygon;
    var Triangle = class extends Polygon {
      static _wktName = "TRIANGLE";
      _validate() {
        if (this.rings.length > 1) {
          throw new Error("Triangle can only contain a single ring");
        }
        if (this.rings.some((ring) => ring.points.length !== 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
          throw new Error("expected Triangle to be closed and to have exactly 4 points");
        }
      }
    };
    exports2.Triangle = Triangle;
    var CurvePolygon = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        if (this.geometries.some((ring) => ring instanceof LineString && ring.points.length < 4 || (ring instanceof CompoundCurve ? !ring.geometries[0].points[0].equals(ring.geometries[ring.geometries.length - 1].points[ring.geometries[ring.geometries.length - 1].points.length - 1]) : !ring.points[0].equals(ring.points[ring.points.length - 1])))) {
          throw new Error("expected rings in CurvePolygon to be closed and LinearRings to have at least 4 points");
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}CURVEPOLYGON${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.CurvePolygon = CurvePolygon;
    var MultiPolygon = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      static _wktName = "MULTIPOLYGON";
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + _multilinestringToWKT(this.geometries[i4++].rings, indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiPolygon = MultiPolygon;
    var PolyhedralSurface = class extends MultiPolygon {
      static _wktName = "POLYHEDRALSURFACE";
    };
    exports2.PolyhedralSurface = PolyhedralSurface;
    var TriangulatedIrregularNetwork = class extends MultiPolygon {
      static _wktName = "TIN";
    };
    exports2.TriangulatedIrregularNetwork = TriangulatedIrregularNetwork;
    var MultiSurface = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTISURFACE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiSurface = MultiSurface;
    var GeometryCollection = class extends Geometry {
      geometries;
      hasZ;
      hasM;
      srid;
      constructor(geometries, hasZ, hasM, srid) {
        super();
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}GEOMETRYCOLLECTION${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i4 = 0;
        while (i4 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.GeometryCollection = GeometryCollection;
    var Box2D = class {
      min;
      max;
      constructor(min, max) {
        this.min = min;
        this.max = max;
      }
      toString() {
        return `BOX(${this.min[0]} ${this.min[1]}, ${this.max[0]} ${this.max[1]})`;
      }
    };
    exports2.Box2D = Box2D;
    var Box3D = class {
      min;
      max;
      constructor(min, max) {
        this.min = min;
        this.max = max;
      }
      toString() {
        return `BOX3D(${this.min[0]} ${this.min[1]} ${this.min[2]}, ${this.max[0]} ${this.max[1]} ${this.max[2]})`;
      }
    };
    exports2.Box3D = Box3D;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js
var require_postgis2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PostgisBox3dCodec = exports2.PostgisBox2dCodec = exports2.PostgisGeometryCodec = void 0;
    var postgis_1 = require_postgis();
    var errors_1 = require_errors();
    var ifaces_1 = require_ifaces();
    var PostgisGeometryCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const geomBuf = ctx.preEncode(this, object);
          buf.writeBytes(geomBuf);
        } else {
          if (!(object instanceof postgis_1.Geometry)) {
            throw new errors_1.InvalidArgumentError(`a Geometry object was expected, got "${object}"`);
          }
          const finalise = buf.writeDeferredSize();
          _encodeGeometry(buf, object);
          finalise();
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.consumeAsBuffer());
        }
        return _parseGeometry(buf);
      }
    };
    exports2.PostgisGeometryCodec = PostgisGeometryCodec;
    var PostgisBox2dCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        let min;
        let max;
        if (ctx.hasOverload(this)) {
          [min, max] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof postgis_1.Box2D)) {
            throw new errors_1.InvalidArgumentError(`a Box2D object was expected, got "${object}"`);
          }
          min = object.min;
          max = object.max;
        }
        const finalise = buf.writeDeferredSize();
        _encodeGeometry(buf, new postgis_1.Polygon([
          new postgis_1.LineString([
            new postgis_1.Point(min[0], min[1]),
            new postgis_1.Point(min[0], max[1]),
            new postgis_1.Point(max[0], max[1]),
            new postgis_1.Point(min[0], min[1])
          ], false, false, null)
        ], false, false, null));
        finalise();
      }
      decode(buf, ctx) {
        const poly = _parseGeometry(buf);
        if (poly.constructor !== postgis_1.Polygon || poly.hasZ || poly.rings.length !== 1 || poly.rings[0].points.length !== 5) {
          throw new errors_1.InternalClientError(`failed to decode ext::postgis::box2d type`);
        }
        const points = poly.rings[0].points;
        const min = [points[0].x, points[0].y];
        const max = [points[2].x, points[2].y];
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [min, max]);
        }
        return new postgis_1.Box2D(min, max);
      }
    };
    exports2.PostgisBox2dCodec = PostgisBox2dCodec;
    var PostgisBox3dCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        let min;
        let max;
        if (ctx.hasOverload(this)) {
          [min, max] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof postgis_1.Box3D)) {
            throw new errors_1.InvalidArgumentError(`a Box3D object was expected, got "${object}"`);
          }
          min = object.min;
          max = object.max;
        }
        const finalise = buf.writeDeferredSize();
        _encodeGeometry(buf, new postgis_1.Polygon([
          new postgis_1.LineString([
            new postgis_1.Point(min[0], min[1], min[2]),
            new postgis_1.Point(min[0], max[1], max[2]),
            new postgis_1.Point(max[0], max[1], max[2]),
            new postgis_1.Point(min[0], min[1], min[2])
          ], true, false, null)
        ], true, false, null));
        finalise();
      }
      decode(buf, ctx) {
        const poly = _parseGeometry(buf);
        let min;
        let max;
        if (poly.constructor === postgis_1.Polygon && poly.rings.length === 1 && poly.rings[0].points.length === 5) {
          const points = poly.rings[0].points;
          min = points[0];
          max = points[2];
        } else if (poly.constructor === postgis_1.PolyhedralSurface && poly.geometries.length === 6 && poly.geometries[0].rings.length === 1 && poly.geometries[0].rings[0].points.length === 5) {
          min = poly.geometries[0].rings[0].points[0];
          max = poly.geometries[5].rings[0].points[2];
        } else {
          throw new errors_1.InternalClientError(`failed to decode ext::postgis::box3d type`);
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            [min.x, min.y, min.z ?? 0],
            [max.x, max.y, max.z ?? 0]
          ]);
        }
        return new postgis_1.Box3D([min.x, min.y, min.z ?? 0], [max.x, max.y, max.z ?? 0]);
      }
    };
    exports2.PostgisBox3dCodec = PostgisBox3dCodec;
    var zFlag = 2147483648;
    var mFlag = 1073741824;
    var sridFlag = 536870912;
    var allFlags = zFlag | mFlag | sridFlag;
    function _parseGeometry(buf, srid = null) {
      const le = buf.readUInt8() === 1;
      let type = buf.readUInt32(le);
      const z2 = (type & zFlag) !== 0;
      const m4 = (type & mFlag) !== 0;
      if ((type & sridFlag) !== 0) {
        srid = buf.readUInt32(le);
      }
      type = type & ~allFlags;
      switch (type) {
        case 1:
          return _parsePoint(buf, le, z2, m4, srid);
        case 2:
          return _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
        case 3:
          return _parsePolygon(buf, postgis_1.Polygon, le, z2, m4, srid);
        case 4:
          return _parseMultiPoint(buf, le, z2, m4, srid);
        case 5:
          return _parseMultiLineString(buf, le, z2, m4, srid);
        case 6:
          return _parseMultiPolygon(buf, postgis_1.MultiPolygon, le, z2, m4, srid);
        case 7:
          return _parseGeometryCollection(buf, le, z2, m4, srid);
        case 8:
          return _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
        case 9:
          return _parseCompoundCurve(buf, le, z2, m4, srid);
        case 10:
          return _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m4, srid);
        case 11:
          return _parseMultiCurve(buf, postgis_1.MultiCurve, le, z2, m4, srid);
        case 12:
          return _parseMultiSurface(buf, le, z2, m4, srid);
        case 15:
          return _parseMultiPolygon(buf, postgis_1.PolyhedralSurface, le, z2, m4, srid);
        case 16:
          return _parseMultiPolygon(buf, postgis_1.TriangulatedIrregularNetwork, le, z2, m4, srid);
        case 17:
          return _parsePolygon(buf, postgis_1.Triangle, le, z2, m4, srid);
        default:
          throw new Error(`unsupported wkb type: ${type}`);
      }
    }
    function _parsePoint(buf, le, z2, m4, srid) {
      return new postgis_1.Point(buf.readFloat64(le), buf.readFloat64(le), z2 ? buf.readFloat64(le) : null, m4 ? buf.readFloat64(le) : null, srid);
    }
    function _parseLineString(buf, cls, le, z2, m4, srid) {
      const pointCount = buf.readUInt32(le);
      const points = new Array(pointCount);
      for (let i4 = 0; i4 < pointCount; i4++) {
        points[i4] = _parsePoint(buf, le, z2, m4, srid);
      }
      return new cls(points, z2, m4, srid);
    }
    function _parsePolygon(buf, cls, le, z2, m4, srid) {
      const ringCount = buf.readUInt32(le);
      const rings = new Array(ringCount);
      for (let i4 = 0; i4 < ringCount; i4++) {
        rings[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
      }
      return new cls(rings, z2, m4, srid);
    }
    function _parseMultiPoint(buf, le, z2, m4, srid) {
      const pointCount = buf.readUInt32(le);
      const points = new Array(pointCount);
      for (let i4 = 0; i4 < pointCount; i4++) {
        buf.discard(5);
        points[i4] = _parsePoint(buf, le, z2, m4, srid);
      }
      return new postgis_1.MultiPoint(points, z2, m4, srid);
    }
    function _parseMultiLineString(buf, le, z2, m4, srid) {
      const lineStringCount = buf.readUInt32(le);
      const lineStrings = new Array(lineStringCount);
      for (let i4 = 0; i4 < lineStringCount; i4++) {
        buf.discard(5);
        lineStrings[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
      }
      return new postgis_1.MultiLineString(lineStrings, z2, m4, srid);
    }
    function _parseCompoundCurve(buf, le, z2, m4, srid) {
      const curveCount = buf.readUInt32(le);
      const curves = new Array(curveCount);
      for (let i4 = 0; i4 < curveCount; i4++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 2:
            curves[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
            break;
          case 8:
            curves[i4] = _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in CompoundCurve`);
        }
      }
      return new postgis_1.CompoundCurve(curves, z2, m4, srid);
    }
    function _parseMultiCurve(buf, cls, le, z2, m4, srid) {
      const curveCount = buf.readUInt32(le);
      const curves = new Array(curveCount);
      for (let i4 = 0; i4 < curveCount; i4++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 2:
            curves[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
            break;
          case 8:
            curves[i4] = _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
            break;
          case 9:
            curves[i4] = _parseCompoundCurve(buf, le, z2, m4, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in MultiCurve/CurvePolygon`);
        }
      }
      return new cls(curves, z2, m4, srid);
    }
    function _parseMultiPolygon(buf, cls, le, z2, m4, srid) {
      const polyCls = cls === postgis_1.TriangulatedIrregularNetwork ? postgis_1.Triangle : postgis_1.Polygon;
      const polyCount = buf.readUInt32(le);
      const polys = new Array(polyCount);
      for (let i4 = 0; i4 < polyCount; i4++) {
        buf.discard(5);
        polys[i4] = _parsePolygon(buf, polyCls, le, z2, m4, srid);
      }
      return new cls(polys, z2, m4, srid);
    }
    function _parseMultiSurface(buf, le, z2, m4, srid) {
      const surfaceCount = buf.readUInt32(le);
      const surfaces = new Array(surfaceCount);
      for (let i4 = 0; i4 < surfaceCount; i4++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 3:
            surfaces[i4] = _parsePolygon(buf, postgis_1.Polygon, le, z2, m4, srid);
            break;
          case 10:
            surfaces[i4] = _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m4, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in MultiSurface`);
        }
      }
      return new postgis_1.MultiSurface(surfaces, z2, m4, srid);
    }
    function _parseGeometryCollection(buf, le, z2, m4, srid) {
      const geometryCount = buf.readUInt32(le);
      const geometries = new Array(geometryCount);
      for (let i4 = 0; i4 < geometryCount; i4++) {
        geometries[i4] = _parseGeometry(buf, srid);
      }
      return new postgis_1.GeometryCollection(geometries, z2, m4, srid);
    }
    var geomTypes = /* @__PURE__ */ new Map([
      [postgis_1.Point, 1],
      [postgis_1.LineString, 2],
      [postgis_1.Polygon, 3],
      [postgis_1.MultiPoint, 4],
      [postgis_1.MultiLineString, 5],
      [postgis_1.MultiPolygon, 6],
      [postgis_1.GeometryCollection, 7],
      [postgis_1.CircularString, 8],
      [postgis_1.CompoundCurve, 9],
      [postgis_1.CurvePolygon, 10],
      [postgis_1.MultiCurve, 11],
      [postgis_1.MultiSurface, 12],
      [postgis_1.PolyhedralSurface, 15],
      [postgis_1.TriangulatedIrregularNetwork, 16],
      [postgis_1.Triangle, 17]
    ]);
    function _encodeGeometry(buf, geom) {
      buf.writeUInt8(0);
      const type = geomTypes.get(geom.constructor);
      if (!type) {
        throw new Error(`unknown geometry type ${geom}`);
      }
      buf.writeUInt32(type | (geom.hasZ ? zFlag : 0) | (geom.hasM ? mFlag : 0) | (geom.srid !== null ? sridFlag : 0));
      if (geom.srid !== null) {
        buf.writeUInt32(geom.srid);
      }
      if (geom instanceof postgis_1.Point) {
        _encodePoint(buf, geom);
        return;
      }
      if (geom instanceof postgis_1.LineString) {
        _encodeLineString(buf, geom);
        return;
      }
      if (geom instanceof postgis_1.Polygon) {
        buf.writeUInt32(geom.rings.length);
        for (const ring of geom.rings) {
          _encodeLineString(buf, ring);
        }
        return;
      }
      buf.writeUInt32(geom.geometries.length);
      for (const point of geom.geometries) {
        _encodeGeometry(buf, point);
      }
    }
    function _encodePoint(buf, point) {
      buf.writeFloat64(point.x);
      buf.writeFloat64(point.y);
      if (point.z !== null)
        buf.writeFloat64(point.z);
      if (point.m !== null)
        buf.writeFloat64(point.m);
    }
    function _encodeLineString(buf, linestring) {
      buf.writeUInt32(linestring.points.length);
      for (const point of linestring.points) {
        _encodePoint(buf, point);
      }
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js
var require_codecs = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.INVALID_CODEC = exports2.NULL_CODEC = exports2.SCALAR_CODECS = exports2.NullCodec = void 0;
    var buffer_1 = require_buffer();
    var boolean_1 = require_boolean();
    var ifaces_1 = require_ifaces();
    var numbers_1 = require_numbers();
    var numerics_1 = require_numerics();
    var text_1 = require_text();
    var uuid_1 = require_uuid();
    var bytes_1 = require_bytes();
    var json_1 = require_json();
    var datetime_1 = require_datetime2();
    var memory_1 = require_memory2();
    var pgvector_1 = require_pgvector2();
    var postgis_1 = require_postgis2();
    var errors_1 = require_errors();
    var consts_1 = require_consts();
    var NullCodec = class extends ifaces_1.Codec {
      static BUFFER = new buffer_1.WriteBuffer().writeInt32(0).unwrap();
      encode(_buf, _object) {
        throw new errors_1.InternalClientError("null codec cannot used to encode data");
      }
      decode(_buf, _ctx) {
        throw new errors_1.InternalClientError("null codec cannot used to decode data");
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "scalar";
      }
    };
    exports2.NullCodec = NullCodec;
    exports2.SCALAR_CODECS = /* @__PURE__ */ new Map();
    exports2.NULL_CODEC = new NullCodec(consts_1.NULL_CODEC_ID);
    exports2.INVALID_CODEC = new NullCodec(consts_1.INVALID_CODEC_ID);
    function registerScalarCodecs(codecs) {
      for (const [typename, type] of Object.entries(codecs)) {
        const id = consts_1.KNOWN_TYPENAMES.get(typename);
        if (id == null) {
          throw new errors_1.InternalClientError("unknown type name");
        }
        exports2.SCALAR_CODECS.set(id, new type(id, typename));
      }
    }
    registerScalarCodecs({
      "std::int16": numbers_1.Int16Codec,
      "std::int32": numbers_1.Int32Codec,
      "std::int64": numbers_1.Int64Codec,
      "std::float32": numbers_1.Float32Codec,
      "std::float64": numbers_1.Float64Codec,
      "std::bigint": numerics_1.BigIntCodec,
      "std::decimal": numerics_1.DecimalStringCodec,
      "std::bool": boolean_1.BoolCodec,
      "std::json": json_1.JSONCodec,
      "std::str": text_1.StrCodec,
      "std::bytes": bytes_1.BytesCodec,
      "std::uuid": uuid_1.UUIDCodec,
      "cal::local_date": datetime_1.LocalDateCodec,
      "cal::local_time": datetime_1.LocalTimeCodec,
      "cal::local_datetime": datetime_1.LocalDateTimeCodec,
      "std::datetime": datetime_1.DateTimeCodec,
      "std::duration": datetime_1.DurationCodec,
      "cal::relative_duration": datetime_1.RelativeDurationCodec,
      "cal::date_duration": datetime_1.DateDurationCodec,
      "cfg::memory": memory_1.ConfigMemoryCodec,
      "std::pg::json": json_1.PgTextJSONCodec,
      "std::pg::timestamptz": datetime_1.DateTimeCodec,
      "std::pg::timestamp": datetime_1.LocalDateTimeCodec,
      "std::pg::date": datetime_1.LocalDateCodec,
      "std::pg::interval": datetime_1.RelativeDurationCodec,
      "ext::pgvector::vector": pgvector_1.PgVectorCodec,
      "ext::pgvector::halfvec": pgvector_1.PgVectorHalfVecCodec,
      "ext::pgvector::sparsevec": pgvector_1.PgVectorSparseVecCodec,
      "ext::postgis::geometry": postgis_1.PostgisGeometryCodec,
      "ext::postgis::geography": postgis_1.PostgisGeometryCodec,
      "ext::postgis::box2d": postgis_1.PostgisBox2dCodec,
      "ext::postgis::box3d": postgis_1.PostgisBox3dCodec
    });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js
var require_tuple = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EMPTY_TUPLE_CODEC = exports2.EMPTY_TUPLE_CODEC_ID = exports2.EmptyTupleCodec = exports2.TupleCodec = void 0;
    var consts_1 = require_consts();
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var TupleCodec = class extends ifaces_1.Codec {
      subCodecs;
      typeName;
      constructor(tid, typeName, codecs) {
        super(tid);
        this.subCodecs = codecs;
        this.typeName = typeName;
      }
      encode(buf, object, ctx) {
        if (!Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError(`an array was expected, got "${object}"`);
        }
        const codecs = this.subCodecs;
        const codecsLen = codecs.length;
        if (object.length !== codecsLen) {
          throw new errors_1.InvalidArgumentError(`expected ${codecsLen} tuple item${codecsLen === 1 ? "" : "s"}, got ${object.length}`);
        }
        if (!codecsLen) {
          buf.writeBuffer(EmptyTupleCodec.BUFFER);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i4 = 0; i4 < codecsLen; i4++) {
          const elem = object[i4];
          elemData.writeInt32(0);
          if (elem == null) {
            throw new errors_1.MissingArgumentError(`element at index ${i4} in tuple cannot be 'null'`);
          } else {
            try {
              codecs[i4].encode(elemData, elem, ctx);
            } catch (e4) {
              if (e4 instanceof errors_1.QueryArgumentError) {
                throw new errors_1.InvalidArgumentError(`invalid element at index ${i4} in tuple: ${e4.message}`);
              } else {
                throw e4;
              }
            }
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Tuple: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = new Array(els);
        for (let i4 = 0; i4 < els; i4++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i4] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i4] = subCodecs[i4].decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getKind() {
        return "tuple";
      }
    };
    exports2.TupleCodec = TupleCodec;
    var EmptyTupleCodec = class extends ifaces_1.Codec {
      static BUFFER = new buffer_1.WriteBuffer().writeInt32(4).writeInt32(0).unwrap();
      encode(buf, object, _ctx) {
        if (!Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError("cannot encode empty Tuple: expected an array");
        }
        if (object.length) {
          throw new errors_1.InvalidArgumentError(`cannot encode empty Tuple: expected 0 elements got ${object.length}`);
        }
        buf.writeInt32(4);
        buf.writeInt32(0);
      }
      decode(buf) {
        const els = buf.readInt32();
        if (els !== 0) {
          throw new errors_1.ProtocolError(`cannot decode empty Tuple: expected 0 elements, received ${els}`);
        }
        return [];
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "tuple";
      }
    };
    exports2.EmptyTupleCodec = EmptyTupleCodec;
    exports2.EMPTY_TUPLE_CODEC_ID = consts_1.KNOWN_TYPENAMES.get("empty-tuple");
    exports2.EMPTY_TUPLE_CODEC = new EmptyTupleCodec(exports2.EMPTY_TUPLE_CODEC_ID);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js
var require_range2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiRange = exports2.Range = void 0;
    var Range = class _Range {
      _lower;
      _upper;
      _incLower;
      _incUpper;
      _isEmpty = false;
      constructor(_lower, _upper, _incLower = _lower != null, _incUpper = false) {
        this._lower = _lower;
        this._upper = _upper;
        this._incLower = _incLower;
        this._incUpper = _incUpper;
      }
      get lower() {
        return this._lower;
      }
      get upper() {
        return this._upper;
      }
      get incLower() {
        return this._incLower;
      }
      get incUpper() {
        return this._incUpper;
      }
      get isEmpty() {
        return this._isEmpty;
      }
      static empty() {
        const range = new _Range(null, null);
        range._isEmpty = true;
        return range;
      }
      toJSON() {
        return this.isEmpty ? { empty: true } : {
          lower: this._lower,
          upper: this._upper,
          inc_lower: this._incLower,
          inc_upper: this._incUpper
        };
      }
    };
    exports2.Range = Range;
    var MultiRange = class {
      _ranges;
      constructor(ranges = []) {
        this._ranges = [...ranges];
      }
      get length() {
        return this._ranges.length;
      }
      *[Symbol.iterator]() {
        for (const range of this._ranges) {
          yield range;
        }
      }
      toJSON() {
        return [...this._ranges];
      }
    };
    exports2.MultiRange = MultiRange;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js
var require_range3 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiRangeCodec = exports2.RangeCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var range_1 = require_range2();
    var errors_1 = require_errors();
    var RangeFlags;
    (function(RangeFlags2) {
      RangeFlags2[RangeFlags2["EMPTY"] = 1] = "EMPTY";
      RangeFlags2[RangeFlags2["INC_LOWER"] = 2] = "INC_LOWER";
      RangeFlags2[RangeFlags2["INC_UPPER"] = 4] = "INC_UPPER";
      RangeFlags2[RangeFlags2["EMPTY_LOWER"] = 8] = "EMPTY_LOWER";
      RangeFlags2[RangeFlags2["EMPTY_UPPER"] = 16] = "EMPTY_UPPER";
    })(RangeFlags || (RangeFlags = {}));
    var MAXINT32 = 2147483647;
    function encodeRange(buf, obj, subCodec, ctx) {
      if (!(obj instanceof range_1.Range)) {
        throw new errors_1.InvalidArgumentError("a Range was expected");
      }
      const elemData = new buffer_1.WriteBuffer();
      if (obj.lower !== null) {
        subCodec.encode(elemData, obj.lower, ctx);
      }
      if (obj.upper !== null) {
        subCodec.encode(elemData, obj.upper, ctx);
      }
      const elemBuf = elemData.unwrap();
      buf.writeInt32(1 + elemBuf.length);
      buf.writeUInt8(obj.isEmpty ? RangeFlags.EMPTY : (obj.incLower ? RangeFlags.INC_LOWER : 0) | (obj.incUpper ? RangeFlags.INC_UPPER : 0) | (obj.lower === null ? RangeFlags.EMPTY_LOWER : 0) | (obj.upper === null ? RangeFlags.EMPTY_UPPER : 0));
      buf.writeBuffer(elemBuf);
    }
    function decodeRange(buf, subCodec, ctx) {
      const flags = buf.readUInt8();
      if (flags & RangeFlags.EMPTY) {
        return range_1.Range.empty();
      }
      const elemBuf = buffer_1.ReadBuffer.alloc();
      let lower2 = null;
      let upper = null;
      if (!(flags & RangeFlags.EMPTY_LOWER)) {
        buf.sliceInto(elemBuf, buf.readInt32());
        lower2 = subCodec.decode(elemBuf, ctx);
        elemBuf.finish();
      }
      if (!(flags & RangeFlags.EMPTY_UPPER)) {
        buf.sliceInto(elemBuf, buf.readInt32());
        upper = subCodec.decode(elemBuf, ctx);
        elemBuf.finish();
      }
      return new range_1.Range(lower2, upper, !!(flags & RangeFlags.INC_LOWER), !!(flags & RangeFlags.INC_UPPER));
    }
    var RangeCodec = class extends ifaces_1.Codec {
      tsType = "Range";
      tsModule = "gel";
      subCodec;
      typeName;
      constructor(tid, typeName, subCodec) {
        super(tid);
        this.subCodec = subCodec;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        return encodeRange(buf, obj, this.subCodec, ctx);
      }
      decode(buf, ctx) {
        return decodeRange(buf, this.subCodec, ctx);
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "range";
      }
    };
    exports2.RangeCodec = RangeCodec;
    var MultiRangeCodec = class extends ifaces_1.Codec {
      tsType = "MultiRange";
      tsModule = "gel";
      subCodec;
      typeName;
      constructor(tid, typeName, subCodec) {
        super(tid);
        this.subCodec = subCodec;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        if (!(obj instanceof range_1.MultiRange)) {
          throw new TypeError(`a MultiRange expected (got type ${obj.constructor.name})`);
        }
        const objLen = obj.length;
        if (objLen > MAXINT32) {
          throw new errors_1.InvalidArgumentError("too many elements in array");
        }
        const elemData = new buffer_1.WriteBuffer();
        for (const item of obj) {
          try {
            encodeRange(elemData, item, this.subCodec, ctx);
          } catch (e4) {
            if (e4 instanceof errors_1.InvalidArgumentError) {
              throw new errors_1.InvalidArgumentError(`invalid multirange element: ${e4.message}`);
            } else {
              throw e4;
            }
          }
        }
        const elemBuf = elemData.unwrap();
        const elemDataLen = elemBuf.length;
        if (elemDataLen > MAXINT32 - 4) {
          throw new errors_1.InvalidArgumentError(`size of encoded multirange datum exceeds the maximum allowed ${MAXINT32 - 4} bytes`);
        }
        buf.writeInt32(4 + elemDataLen);
        buf.writeInt32(objLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const elemCount = buf.readInt32();
        const result = new Array(elemCount);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i4 = 0; i4 < elemCount; i4++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            throw new errors_1.ProtocolError("unexpected NULL element in multirange value");
          } else {
            buf.sliceInto(elemBuf, elemLen);
            const elem = decodeRange(elemBuf, subCodec, ctx);
            if (elemBuf.length) {
              throw new errors_1.ProtocolError(`unexpected trailing data in buffer after multirange element decoding: ${elemBuf.length}`);
            }
            result[i4] = elem;
            elemBuf.finish();
          }
        }
        return new range_1.MultiRange(result);
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "multirange";
      }
    };
    exports2.MultiRangeCodec = MultiRangeCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js
var require_namedtuple = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NamedTupleCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var NamedTupleCodec = class extends ifaces_1.Codec {
      subCodecs;
      names;
      typeName;
      constructor(tid, typeName, codecs, names) {
        super(tid);
        this.subCodecs = codecs;
        this.names = names;
        this.typeName = typeName;
      }
      encode(buf, object, ctx) {
        if (typeof object !== "object" || Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError(`an object was expected, got "${object}"`);
        }
        const codecsLen = this.subCodecs.length;
        if (Object.keys(object).length !== codecsLen) {
          throw new errors_1.QueryArgumentError(`expected ${codecsLen} element${codecsLen === 1 ? "" : "s"} in named tuple, got ${Object.keys(object).length}`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i4 = 0; i4 < codecsLen; i4++) {
          const key = this.names[i4];
          const val2 = object[key];
          if (val2 == null) {
            throw new errors_1.MissingArgumentError(`element '${key}' in named tuple cannot be 'null'`);
          } else {
            elemData.writeInt32(0);
            try {
              this.subCodecs[i4].encode(elemData, val2, ctx);
            } catch (e4) {
              if (e4 instanceof errors_1.QueryArgumentError) {
                throw new errors_1.InvalidArgumentError(`invalid element '${key}' in named tuple: ${e4.message}`);
              } else {
                throw e4;
              }
            }
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode NamedTuple: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const names = this.names;
        const result = {};
        for (let i4 = 0; i4 < els; i4++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = subCodecs[i4].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[names[i4]] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getNames() {
        return Array.from(this.names);
      }
      getKind() {
        return "namedtuple";
      }
    };
    exports2.NamedTupleCodec = NamedTupleCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js
var require_array = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ArrayCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var tuple_1 = require_tuple();
    var range_1 = require_range3();
    var errors_1 = require_errors();
    var namedtuple_1 = require_namedtuple();
    var ArrayCodec = class extends ifaces_1.Codec {
      subCodec;
      len;
      typeName;
      constructor(tid, typeName, subCodec, len) {
        super(tid);
        this.subCodec = subCodec;
        this.len = len;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        if (!(this.subCodec instanceof ifaces_1.ScalarCodec || this.subCodec instanceof tuple_1.TupleCodec || this.subCodec instanceof namedtuple_1.NamedTupleCodec || this.subCodec instanceof range_1.RangeCodec || this.subCodec instanceof range_1.MultiRangeCodec)) {
          throw new errors_1.InvalidArgumentError("only arrays of scalars or tuples are supported");
        }
        if (!Array.isArray(obj) && !isTypedArray(obj)) {
          throw new errors_1.InvalidArgumentError(`an array was expected (got type ${obj.constructor.name})`);
        }
        const subCodec = this.subCodec;
        const elemData = new buffer_1.WriteBuffer();
        const objLen = obj.length;
        if (objLen > 2147483647) {
          throw new errors_1.InvalidArgumentError("too many elements in array");
        }
        for (let i4 = 0; i4 < objLen; i4++) {
          const item = obj[i4];
          if (item == null) {
            elemData.writeInt32(-1);
          } else {
            subCodec.encode(elemData, item, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(12 + 8 + elemBuf.length);
        buf.writeInt32(1);
        buf.writeInt32(0);
        buf.writeInt32(0);
        buf.writeInt32(objLen);
        buf.writeInt32(1);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError("only 1-dimensional arrays are supported");
        }
        const len = buf.readUInt32();
        if (this.len !== -1 && len !== this.len) {
          throw new errors_1.ProtocolError(`invalid array size: received ${len}, expected ${this.len}`);
        }
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i4 = 0; i4 < len; i4++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i4] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i4] = subCodec.decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "array";
      }
    };
    exports2.ArrayCodec = ArrayCodec;
    function isTypedArray(obj) {
      return !!(obj.buffer instanceof ArrayBuffer && obj.BYTES_PER_ELEMENT);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js
var require_enum = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EnumCodec = void 0;
    var text_1 = require_text();
    var EnumCodec = class extends text_1.StrCodec {
      values;
      constructor(tid, typeName, values) {
        super(tid, typeName);
        this.values = values;
      }
    };
    exports2.EnumCodec = EnumCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js
var require_ifaces2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Language = exports2.Cardinality = exports2.OutputFormat = void 0;
    var chars = __importStar2(require_chars());
    var OutputFormat;
    (function(OutputFormat2) {
      OutputFormat2[OutputFormat2["BINARY"] = chars.$b] = "BINARY";
      OutputFormat2[OutputFormat2["JSON"] = chars.$j] = "JSON";
      OutputFormat2[OutputFormat2["NONE"] = chars.$n] = "NONE";
    })(OutputFormat || (exports2.OutputFormat = OutputFormat = {}));
    var Cardinality;
    (function(Cardinality2) {
      Cardinality2[Cardinality2["NO_RESULT"] = chars.$n] = "NO_RESULT";
      Cardinality2[Cardinality2["AT_MOST_ONE"] = chars.$o] = "AT_MOST_ONE";
      Cardinality2[Cardinality2["ONE"] = chars.$A] = "ONE";
      Cardinality2[Cardinality2["MANY"] = chars.$m] = "MANY";
      Cardinality2[Cardinality2["AT_LEAST_ONE"] = chars.$M] = "AT_LEAST_ONE";
    })(Cardinality || (exports2.Cardinality = Cardinality = {}));
    var Language;
    (function(Language2) {
      Language2[Language2["EDGEQL"] = chars.$E] = "EDGEQL";
      Language2[Language2["SQL"] = chars.$S] = "SQL";
    })(Language || (exports2.Language = Language = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js
var require_object = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ObjectCodec = void 0;
    var ifaces_1 = require_ifaces2();
    var ifaces_2 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var EDGE_POINTER_IS_IMPLICIT = 1 << 0;
    var EDGE_POINTER_IS_LINKPROP = 1 << 1;
    var ObjectCodec = class extends ifaces_2.Codec {
      codecs;
      fields;
      namesSet;
      cardinalities;
      constructor(tid, codecs, names, flags, cards) {
        super(tid);
        this.codecs = codecs;
        this.fields = new Array(names.length);
        this.namesSet = /* @__PURE__ */ new Set();
        this.cardinalities = cards;
        for (let i4 = 0; i4 < names.length; i4++) {
          const isLinkprop = !!(flags[i4] & EDGE_POINTER_IS_LINKPROP);
          const name = isLinkprop ? `@${names[i4]}` : names[i4];
          this.fields[i4] = {
            name,
            implicit: !!(flags[i4] & EDGE_POINTER_IS_IMPLICIT),
            linkprop: isLinkprop,
            cardinality: cards[i4]
          };
          this.namesSet.add(name);
        }
      }
      encode(_buf, _object) {
        throw new errors_1.InvalidArgumentError("Objects cannot be passed as arguments");
      }
      encodeArgs(args, ctx) {
        if (this.fields[0].name === "0" || this.fields[0].name === "1") {
          return this._encodePositionalArgs(args, ctx);
        }
        return this._encodeNamedArgs(args, ctx);
      }
      _encodePositionalArgs(args, ctx) {
        if (!Array.isArray(args)) {
          throw new errors_1.InvalidArgumentError("an array of arguments was expected");
        }
        const codecs = this.codecs;
        const codecsLen = codecs.length;
        if (args.length !== codecsLen) {
          throw new errors_1.QueryArgumentError(`expected ${codecsLen} argument${codecsLen === 1 ? "" : "s"}, got ${args.length}`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i4 = 0; i4 < codecsLen; i4++) {
          elemData.writeInt32(0);
          const arg = args[i4];
          if (arg == null) {
            const card = this.cardinalities[i4];
            if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
              throw new errors_1.MissingArgumentError(`argument ${this.fields[i4].name} is required, but received ${arg}`);
            }
            elemData.writeInt32(-1);
          } else {
            const codec = codecs[i4];
            codec.encode(elemData, arg, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        const buf = new buffer_1.WriteBuffer();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
        return buf.unwrap();
      }
      _encodeNamedArgs(args, ctx) {
        if (args == null) {
          throw new errors_1.MissingArgumentError("One or more named arguments expected, received null");
        }
        const keys = Object.keys(args);
        const fields = this.fields;
        const namesSet = this.namesSet;
        const codecs = this.codecs;
        const codecsLen = codecs.length;
        if (keys.length > codecsLen) {
          const extraKeys = keys.filter((key) => !namesSet.has(key));
          throw new errors_1.UnknownArgumentError(`Unused named argument${extraKeys.length === 1 ? "" : "s"}: "${extraKeys.join('", "')}"`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i4 = 0; i4 < codecsLen; i4++) {
          const key = fields[i4].name;
          const val2 = args[key];
          elemData.writeInt32(0);
          if (val2 == null) {
            const card = this.cardinalities[i4];
            if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
              throw new errors_1.MissingArgumentError(`argument ${this.fields[i4].name} is required, but received ${val2}`);
            }
            elemData.writeInt32(-1);
          } else {
            const codec = codecs[i4];
            codec.encode(elemData, val2, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        const buf = new buffer_1.WriteBuffer();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
        return buf.unwrap();
      }
      decode(buf, ctx) {
        const codecs = this.codecs;
        const fields = this.fields;
        const els = buf.readUInt32();
        if (els !== codecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Object: expected ${codecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = {};
        for (let i4 = 0; i4 < els; i4++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          const name = fields[i4].name;
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = codecs[i4].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[name] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.codecs);
      }
      getFields() {
        return Array.from(this.fields);
      }
      getKind() {
        return "object";
      }
    };
    exports2.ObjectCodec = ObjectCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js
var require_set = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SetCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var array_1 = require_array();
    var errors_1 = require_errors();
    var SetCodec = class extends ifaces_1.Codec {
      subCodec;
      constructor(tid, subCodec) {
        super(tid);
        this.subCodec = subCodec;
      }
      encode(_buf, _obj) {
        throw new errors_1.InvalidArgumentError("Sets cannot be passed in query arguments");
      }
      decode(buf, ctx) {
        if (this.subCodec instanceof array_1.ArrayCodec) {
          return this.decodeSetOfArrays(buf, ctx);
        } else {
          return this.decodeSet(buf, ctx);
        }
      }
      decodeSetOfArrays(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError(`expected 1-dimensional array of records of arrays`);
        }
        const len = buf.readUInt32();
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i4 = 0; i4 < len; i4++) {
          buf.discard(4);
          const recSize = buf.readUInt32();
          if (recSize !== 1) {
            throw new errors_1.ProtocolError("expected a record with a single element as an array set element envelope");
          }
          buf.discard(4);
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            throw new errors_1.ProtocolError("unexpected NULL value in array set element");
          }
          buf.sliceInto(elemBuf, elemLen);
          result[i4] = subCodec.decode(elemBuf, ctx);
          elemBuf.finish();
        }
        return result;
      }
      decodeSet(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError(`invalid set dimensinality: ${ndims}`);
        }
        const len = buf.readUInt32();
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i4 = 0; i4 < len; i4++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i4] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i4] = subCodec.decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "set";
      }
    };
    exports2.SetCodec = SetCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js
var require_record = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RecordCodec = exports2.SQLRowModeObject = exports2.SQLRowModeArray = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var SQLRowArrayCodec = {
      fromDatabase(values, _desc) {
        return values;
      },
      toDatabase() {
        throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
      }
    };
    var SQLRowObjectCodec = {
      fromDatabase(values, { names }) {
        return Object.fromEntries(names.map((key, index6) => [key, values[index6]]));
      },
      toDatabase() {
        throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
      }
    };
    exports2.SQLRowModeArray = {
      _private_sql_row: SQLRowArrayCodec
    };
    exports2.SQLRowModeObject = {
      _private_sql_row: SQLRowObjectCodec
    };
    var RecordCodec = class extends ifaces_1.Codec {
      subCodecs;
      names;
      constructor(tid, codecs, names) {
        super(tid);
        this.subCodecs = codecs;
        this.names = names;
      }
      encode(_buf, _object) {
        throw new errors_1.InvalidArgumentError("SQL records cannot be passed as arguments");
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Record: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const overload = ctx.getContainerOverload("_private_sql_row");
        if (overload != null && overload !== SQLRowObjectCodec) {
          const result = new Array(els);
          for (let i4 = 0; i4 < els; i4++) {
            buf.discard(4);
            const elemLen = buf.readInt32();
            let val2 = null;
            if (elemLen !== -1) {
              buf.sliceInto(elemBuf, elemLen);
              val2 = subCodecs[i4].decode(elemBuf, ctx);
              elemBuf.finish();
            }
            result[i4] = val2;
          }
          if (overload !== SQLRowArrayCodec) {
            return overload.fromDatabase(result, { names: this.names });
          }
          return result;
        } else {
          const names = this.names;
          const result = {};
          for (let i4 = 0; i4 < els; i4++) {
            buf.discard(4);
            const elemLen = buf.readInt32();
            let val2 = null;
            if (elemLen !== -1) {
              buf.sliceInto(elemBuf, elemLen);
              val2 = subCodecs[i4].decode(elemBuf, ctx);
              elemBuf.finish();
            }
            result[names[i4]] = val2;
          }
          return result;
        }
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getNames() {
        return Array.from(this.names);
      }
      getKind() {
        return "record";
      }
    };
    exports2.RecordCodec = RecordCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js
var require_sparseObject = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SparseObjectCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var SparseObjectCodec = class extends ifaces_1.Codec {
      codecs;
      names;
      constructor(tid, codecs, names) {
        super(tid);
        this.codecs = codecs;
        this.names = names;
      }
      encode(buf, object, ctx) {
        const elemBuf = new buffer_1.WriteBuffer();
        let objLen = 0;
        for (const [key, val2] of Object.entries(object)) {
          if (val2 !== void 0) {
            const i4 = this.names.indexOf(key);
            if (i4 === -1) {
              throw new errors_1.UnknownArgumentError(this.names.length ? `invalid global '${key}', valid globals are ${this.names.map((n3) => `'${n3}'`).join(", ")}` : `invalid global '${key}', no valid globals exist`);
            }
            objLen += 1;
            elemBuf.writeInt32(i4);
            if (val2 === null) {
              elemBuf.writeInt32(-1);
            } else {
              this.codecs[i4].encode(elemBuf, val2, ctx);
            }
          }
        }
        const elemData = elemBuf.unwrap();
        buf.writeInt32(4 + elemData.length);
        buf.writeInt32(objLen);
        buf.writeBuffer(elemData);
      }
      decode(buf, ctx) {
        const codecs = this.codecs;
        const names = this.names;
        const els = buf.readUInt32();
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = {};
        for (let _3 = 0; _3 < els; _3++) {
          const i4 = buf.readUInt32();
          const elemLen = buf.readInt32();
          const name = names[i4];
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = codecs[i4].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[name] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.codecs);
      }
      getKind() {
        return "sparse_object";
      }
    };
    exports2.SparseObjectCodec = SparseObjectCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js
var require_registry = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CodecsRegistry = void 0;
    var buffer_1 = require_buffer();
    var lru_1 = __importDefault2(require_lru());
    var ifaces_1 = require_ifaces();
    var codecs_1 = require_codecs();
    var consts_1 = require_consts();
    var tuple_1 = require_tuple();
    var array_1 = require_array();
    var namedtuple_1 = require_namedtuple();
    var enum_1 = require_enum();
    var object_1 = require_object();
    var set_1 = require_set();
    var record_1 = require_record();
    var range_1 = require_range3();
    var utils_1 = require_utils2();
    var sparseObject_1 = require_sparseObject();
    var errors_1 = require_errors();
    var CODECS_CACHE_SIZE = 1e3;
    var CODECS_BUILD_CACHE_SIZE = 200;
    var CTYPE_SET = 0;
    var CTYPE_SHAPE = 1;
    var CTYPE_BASE_SCALAR = 2;
    var CTYPE_SCALAR = 3;
    var CTYPE_TUPLE = 4;
    var CTYPE_NAMEDTUPLE = 5;
    var CTYPE_ARRAY = 6;
    var CTYPE_ENUM = 7;
    var CTYPE_INPUT_SHAPE = 8;
    var CTYPE_RANGE = 9;
    var CTYPE_OBJECT = 10;
    var CTYPE_COMPOUND = 11;
    var CTYPE_MULTIRANGE = 12;
    var CTYPE_RECORD = 13;
    var CodecsRegistry = class {
      codecsBuildCache;
      codecs;
      constructor() {
        this.codecs = new lru_1.default({ capacity: CODECS_CACHE_SIZE });
        this.codecsBuildCache = new lru_1.default({ capacity: CODECS_BUILD_CACHE_SIZE });
      }
      hasCodec(typeId) {
        if (this.codecs.has(typeId)) {
          return true;
        }
        return typeId === consts_1.NULL_CODEC_ID || typeId === tuple_1.EMPTY_TUPLE_CODEC_ID;
      }
      getCodec(typeId) {
        const codec = this.codecs.get(typeId);
        if (codec != null) {
          return codec;
        }
        if (typeId === tuple_1.EMPTY_TUPLE_CODEC_ID) {
          return tuple_1.EMPTY_TUPLE_CODEC;
        }
        if (typeId === consts_1.NULL_CODEC_ID) {
          return codecs_1.NULL_CODEC;
        }
        return null;
      }
      buildCodec(spec, protocolVersion) {
        if (!(0, utils_1.versionGreaterThanOrEqual)(protocolVersion, [2, 0])) {
          throw new errors_1.UnsupportedProtocolVersionError("unsupported old protocol version v1; downgrade to the previous version of gel-js");
        }
        const frb = new buffer_1.ReadBuffer(spec);
        const codecsList = [];
        let codec = null;
        while (frb.length) {
          const descLen = frb.readInt32();
          const descBuf = buffer_1.ReadBuffer.alloc();
          frb.sliceInto(descBuf, descLen);
          codec = this._buildCodec(descBuf, codecsList);
          descBuf.finish("unexpected trailing data in type descriptor buffer");
          if (codec == null) {
            continue;
          }
          codecsList.push(codec);
          this.codecs.set(codec.tid, codec);
        }
        if (!codecsList.length) {
          throw new errors_1.InternalClientError("could not build a codec");
        }
        return codecsList[codecsList.length - 1];
      }
      _buildCodec(frb, cl) {
        const t4 = frb.readUInt8();
        const tid = frb.readUUID();
        let res = this.codecs.get(tid);
        if (res == null) {
          res = this.codecsBuildCache.get(tid);
        }
        if (res != null) {
          frb.discard(frb.length);
          return res;
        }
        switch (t4) {
          case CTYPE_BASE_SCALAR: {
            res = codecs_1.SCALAR_CODECS.get(tid);
            if (!res) {
              if (consts_1.KNOWN_TYPES.has(tid)) {
                throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
              }
              throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
            }
            if (!(res instanceof ifaces_1.ScalarCodec)) {
              throw new errors_1.ProtocolError("could not build scalar codec: base scalar is a non-scalar codec");
            }
            break;
          }
          case CTYPE_SHAPE:
          case CTYPE_INPUT_SHAPE: {
            if (t4 === CTYPE_SHAPE) {
              frb.readBoolean();
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            const flags = new Array(els);
            const cards = new Array(els);
            for (let i4 = 0; i4 < els; i4++) {
              const flag = frb.readUInt32();
              const card = frb.readUInt8();
              const name = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build object codec: missing subcodec");
              }
              codecs[i4] = subCodec;
              names[i4] = name;
              flags[i4] = flag;
              cards[i4] = card;
              if (t4 === CTYPE_SHAPE) {
                frb.readUInt16();
              }
            }
            res = t4 === CTYPE_INPUT_SHAPE ? new sparseObject_1.SparseObjectCodec(tid, codecs, names) : new object_1.ObjectCodec(tid, codecs, names, flags, cards);
            break;
          }
          case CTYPE_SET: {
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build set codec: missing subcodec");
            }
            res = new set_1.SetCodec(tid, subCodec);
            break;
          }
          case CTYPE_SCALAR: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            const ancestors = [];
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              const ancestorPos = frb.readUInt16();
              const ancestorCodec = cl[ancestorPos];
              if (ancestorCodec == null) {
                throw new errors_1.ProtocolError("could not build scalar codec: missing a codec for base scalar");
              }
              if (!(ancestorCodec instanceof ifaces_1.ScalarCodec)) {
                throw new errors_1.ProtocolError(`a scalar codec expected for base scalar type, got ${ancestorCodec}`);
              }
              ancestors.push(ancestorCodec);
            }
            if (ancestorCount === 0) {
              res = codecs_1.SCALAR_CODECS.get(tid);
              if (res == null) {
                if (consts_1.KNOWN_TYPES.has(tid)) {
                  throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
                }
                throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
              }
            } else {
              const baseCodec = ancestors[ancestors.length - 1];
              res = baseCodec.derive(tid, typeName, ancestors);
            }
            break;
          }
          case CTYPE_ARRAY: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const els = frb.readUInt16();
            if (els !== 1) {
              throw new errors_1.ProtocolError("cannot handle arrays with more than one dimension");
            }
            const dimLen = frb.readInt32();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build array codec: missing subcodec");
            }
            res = new array_1.ArrayCodec(tid, typeName, subCodec, dimLen);
            break;
          }
          case CTYPE_TUPLE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            if (els === 0) {
              res = tuple_1.EMPTY_TUPLE_CODEC;
            } else {
              const codecs = new Array(els);
              for (let i4 = 0; i4 < els; i4++) {
                const pos = frb.readUInt16();
                const subCodec = cl[pos];
                if (subCodec == null) {
                  throw new errors_1.ProtocolError("could not build tuple codec: missing subcodec");
                }
                codecs[i4] = subCodec;
              }
              res = new tuple_1.TupleCodec(tid, typeName, codecs);
            }
            break;
          }
          case CTYPE_NAMEDTUPLE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            for (let i4 = 0; i4 < els; i4++) {
              names[i4] = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build namedtuple codec: missing subcodec");
              }
              codecs[i4] = subCodec;
            }
            res = new namedtuple_1.NamedTupleCodec(tid, typeName, codecs, names);
            break;
          }
          case CTYPE_RECORD: {
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            for (let i4 = 0; i4 < els; i4++) {
              names[i4] = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build record codec: missing subcodec");
              }
              codecs[i4] = subCodec;
            }
            res = new record_1.RecordCodec(tid, codecs, names);
            break;
          }
          case CTYPE_ENUM: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const values = [];
            for (let i4 = 0; i4 < els; i4++) {
              values.push(frb.readString());
            }
            res = new enum_1.EnumCodec(tid, typeName, values);
            break;
          }
          case CTYPE_RANGE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
            }
            res = new range_1.RangeCodec(tid, typeName, subCodec);
            break;
          }
          case CTYPE_OBJECT: {
            frb.discard(frb.length);
            res = codecs_1.NULL_CODEC;
            break;
          }
          case CTYPE_COMPOUND: {
            frb.discard(frb.length);
            res = codecs_1.NULL_CODEC;
            break;
          }
          case CTYPE_MULTIRANGE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i4 = 0; i4 < ancestorCount; i4++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
            }
            res = new range_1.MultiRangeCodec(tid, typeName, subCodec);
            break;
          }
        }
        if (res == null) {
          if (consts_1.KNOWN_TYPES.has(tid)) {
            throw new errors_1.InternalClientError(`could not build a codec for ${consts_1.KNOWN_TYPES.get(tid)} type`);
          } else {
            throw new errors_1.InternalClientError(`could not build a codec for ${tid} type`);
          }
        }
        this.codecsBuildCache.set(tid, res);
        return res;
      }
    };
    exports2.CodecsRegistry = CodecsRegistry;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js
var require_context = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NOOP_CODEC_CONTEXT = exports2.CodecContext = void 0;
    var NOOP = {
      toDatabase(data) {
        return data;
      },
      fromDatabase(data) {
        return data;
      }
    };
    var CodecContext = class {
      spec;
      map;
      constructor(spec) {
        if (spec === null || spec.size === 0) {
          this.spec = null;
        } else {
          this.spec = spec;
        }
        this.map = /* @__PURE__ */ new Map();
      }
      initCodec(codec) {
        const specMap = this.spec;
        const targetTypeName = codec.typeName;
        const s4 = specMap.get(targetTypeName);
        if (s4 != null) {
          this.map.set(targetTypeName, s4);
          return s4;
        }
        const ancestors = codec.ancestors;
        if (ancestors == null) {
          this.map.set(targetTypeName, NOOP);
          return NOOP;
        }
        for (let i4 = 0; i4 < ancestors.length; i4++) {
          const parent = ancestors[i4];
          const s5 = specMap.get(parent.typeName);
          if (s5 != null) {
            this.map.set(targetTypeName, s5);
            return s5;
          }
        }
        this.map.set(targetTypeName, NOOP);
        return NOOP;
      }
      getContainerOverload(kind) {
        if (this.spec === null || !this.spec.size) {
          return;
        }
        return this.spec.get(kind);
      }
      hasOverload(codec) {
        if (this.spec === null || !this.spec.size) {
          return false;
        }
        const op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return false;
        }
        if (op != null) {
          return true;
        }
        return this.initCodec(codec) !== NOOP;
      }
      postDecode(codec, value) {
        if (this.spec === null || !this.spec.size) {
          return value;
        }
        let op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return value;
        }
        if (op == null) {
          op = this.initCodec(codec);
        }
        return op.fromDatabase(value);
      }
      preEncode(codec, value) {
        if (this.spec === null || !this.spec.size) {
          return value;
        }
        let op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return value;
        }
        if (op == null) {
          op = this.initCodec(codec);
        }
        return op.toDatabase(value);
      }
    };
    exports2.CodecContext = CodecContext;
    exports2.NOOP_CODEC_CONTEXT = new CodecContext(null);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js
var require_options = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Options = exports2.TransactionOptions = exports2.RetryOptions = exports2.logWarnings = exports2.throwWarnings = exports2.RetryCondition = exports2.IsolationLevel = void 0;
    exports2.defaultBackoff = defaultBackoff;
    var errors = __importStar2(require_errors());
    var buffer_1 = require_buffer();
    var record_1 = require_record();
    var context_1 = require_context();
    function defaultBackoff(attempt) {
      return 2 ** attempt * 100 + Math.random() * 100;
    }
    var IsolationLevel;
    (function(IsolationLevel2) {
      IsolationLevel2["Serializable"] = "Serializable";
      IsolationLevel2["RepeatableRead"] = "RepeatableRead";
      IsolationLevel2["PreferRepeatableRead"] = "PreferRepeatableRead";
    })(IsolationLevel || (exports2.IsolationLevel = IsolationLevel = {}));
    var RetryCondition;
    (function(RetryCondition2) {
      RetryCondition2[RetryCondition2["TransactionConflict"] = 0] = "TransactionConflict";
      RetryCondition2[RetryCondition2["NetworkError"] = 1] = "NetworkError";
    })(RetryCondition || (exports2.RetryCondition = RetryCondition = {}));
    var RetryRule = class {
      attempts;
      backoff;
      constructor(attempts, backoff) {
        this.attempts = attempts;
        this.backoff = backoff;
      }
    };
    var throwWarnings = (warnings) => {
      throw new AggregateError(warnings, formatWarnings(warnings));
    };
    exports2.throwWarnings = throwWarnings;
    var logWarnings = (warnings) => {
      const merged = new Error(formatWarnings(warnings));
      console.warn(Object.assign(merged, { name: "" }));
    };
    exports2.logWarnings = logWarnings;
    var formatWarnings = (warnings) => `warnings occurred while running query:
${warnings.map((warn) => warn.message).join("\n")}`;
    var RetryOptions = class _RetryOptions {
      default;
      overrides;
      constructor(attempts = 3, backoff = defaultBackoff) {
        this.default = new RetryRule(attempts, backoff);
        this.overrides = /* @__PURE__ */ new Map();
      }
      withRule(condition, attempts, backoff) {
        const def = this.default;
        const overrides = new Map(this.overrides);
        overrides.set(condition, new RetryRule(attempts ?? def.attempts, backoff ?? def.backoff));
        const result = Object.create(_RetryOptions.prototype);
        result.default = def;
        result.overrides = overrides;
        return result;
      }
      getRuleForException(err2) {
        let result;
        if (err2 instanceof errors.TransactionConflictError) {
          result = this.overrides.get(RetryCondition.TransactionConflict);
        } else if (err2 instanceof errors.ClientError) {
          result = this.overrides.get(RetryCondition.NetworkError);
        }
        return result ?? this.default;
      }
      static defaults() {
        return _retryOptionsDefault;
      }
    };
    exports2.RetryOptions = RetryOptions;
    var _retryOptionsDefault = new RetryOptions();
    var TransactionOptions = class {
      isolation;
      readonly;
      deferrable;
      constructor({ isolation, readonly, deferrable } = {}) {
        this.isolation = isolation;
        this.readonly = readonly;
        this.deferrable = deferrable;
      }
      isDefault() {
        return this.isolation === void 0 && this.readonly === void 0 && this.deferrable === void 0;
      }
      static defaults() {
        return _defaultTransactionOptions;
      }
    };
    exports2.TransactionOptions = TransactionOptions;
    var _defaultTransactionOptions = new TransactionOptions();
    var TAG_ANNOTATION_KEY = "tag";
    var Options = class _Options {
      static schemaVersion = 0;
      module;
      moduleAliases;
      config;
      globals;
      retryOptions;
      transactionOptions;
      codecs;
      warningHandler;
      annotations = /* @__PURE__ */ new Map();
      cachedCodecContext = null;
      cachedCodecContextVer = -1;
      get tag() {
        return this.annotations.get(TAG_ANNOTATION_KEY) ?? null;
      }
      static signalSchemaChange() {
        this.schemaVersion += 1;
      }
      constructor({ retryOptions = RetryOptions.defaults(), transactionOptions = TransactionOptions.defaults(), warningHandler = exports2.logWarnings, module: module3 = "default", moduleAliases = {}, config = {}, globals = {}, codecs = {} } = {}) {
        this.retryOptions = retryOptions;
        this.transactionOptions = transactionOptions;
        this.warningHandler = warningHandler;
        this.module = module3;
        this.moduleAliases = new Map(Object.entries(moduleAliases));
        this.config = new Map(Object.entries(config));
        this.globals = new Map(Object.entries(globals));
        this.codecs = new Map(Object.entries(codecs));
      }
      makeCodecContext() {
        if (this.codecs.size === 0) {
          return context_1.NOOP_CODEC_CONTEXT;
        }
        if (this.cachedCodecContextVer === _Options.schemaVersion) {
          return this.cachedCodecContext;
        }
        const ctx = new context_1.CodecContext(this.codecs);
        this.cachedCodecContext = ctx;
        this.cachedCodecContextVer = _Options.schemaVersion;
        return ctx;
      }
      _cloneWith(mergeOptions) {
        const clone2 = Object.create(_Options.prototype);
        clone2.annotations = this.annotations;
        clone2.retryOptions = mergeOptions.retryOptions ?? this.retryOptions;
        clone2.transactionOptions = mergeOptions.transactionOptions ?? this.transactionOptions;
        clone2.warningHandler = mergeOptions.warningHandler ?? this.warningHandler;
        if (mergeOptions.config != null) {
          clone2.config = new Map([
            ...this.config,
            ...Object.entries(mergeOptions.config)
          ]);
        } else {
          clone2.config = this.config;
        }
        if (mergeOptions.globals != null) {
          clone2.globals = new Map([
            ...this.globals,
            ...Object.entries(mergeOptions.globals)
          ]);
        } else {
          clone2.globals = this.globals;
        }
        if (mergeOptions.moduleAliases != null) {
          clone2.moduleAliases = new Map([
            ...this.moduleAliases,
            ...Object.entries(mergeOptions.moduleAliases)
          ]);
        } else {
          clone2.moduleAliases = this.moduleAliases;
        }
        if (mergeOptions.codecs != null) {
          clone2.codecs = new Map([
            ...this.codecs,
            ...Object.entries(mergeOptions.codecs)
          ]);
        } else {
          clone2.codecs = this.codecs;
          clone2.cachedCodecContext = this.cachedCodecContext;
          clone2.cachedCodecContextVer = this.cachedCodecContextVer;
        }
        if (mergeOptions._dropSQLRowCodec && clone2.codecs.has("_private_sql_row")) {
          if (clone2.codecs === this.codecs) {
            clone2.codecs = new Map(clone2.codecs);
            clone2.cachedCodecContext = null;
            clone2.cachedCodecContextVer = -1;
          }
          clone2.codecs.delete("_private_sql_row");
        }
        clone2.module = mergeOptions.module ?? this.module;
        return clone2;
      }
      _serialise() {
        const state2 = {};
        if (this.module !== "default") {
          state2.module = this.module;
        }
        if (this.moduleAliases.size) {
          state2.aliases = Array.from(this.moduleAliases.entries());
        }
        if (this.config.size) {
          state2.config = Object.fromEntries(this.config.entries());
        }
        if (this.globals.size) {
          const globs = {};
          for (const [key, val2] of this.globals.entries()) {
            globs[key.includes("::") ? key : `${this.module}::${key}`] = val2;
          }
          state2.globals = globs;
        }
        return state2;
      }
      withModuleAliases({ module: module3, ...aliases }) {
        return this._cloneWith({
          module: module3 ?? this.module,
          moduleAliases: aliases
        });
      }
      withConfig(config) {
        return this._cloneWith({ config });
      }
      withCodecs(codecs) {
        return this._cloneWith({ codecs });
      }
      withSQLRowMode(mode) {
        if (mode === "object") {
          return this._cloneWith({ _dropSQLRowCodec: true });
        } else if (mode === "array") {
          return this._cloneWith({ codecs: record_1.SQLRowModeArray });
        } else {
          throw new errors.InterfaceError(`invalid mode=${mode}`);
        }
      }
      withGlobals(globals) {
        return this._cloneWith({
          globals: { ...this.globals, ...globals }
        });
      }
      withQueryTag(tag) {
        const annos = new Map(this.annotations);
        if (tag != null) {
          if (tag.startsWith("edgedb/")) {
            throw new errors.InterfaceError("reserved tag: edgedb/*");
          }
          if (tag.startsWith("gel/")) {
            throw new errors.InterfaceError("reserved tag: gel/*");
          }
          if (buffer_1.utf8Encoder.encode(tag).length > 128) {
            throw new errors.InterfaceError("tag too long (> 128 bytes)");
          }
          annos.set(TAG_ANNOTATION_KEY, tag);
        } else {
          annos.delete(TAG_ANNOTATION_KEY);
        }
        const clone2 = this._cloneWith({});
        clone2.annotations = annos;
        return clone2;
      }
      withTransactionOptions(opt) {
        return this._cloneWith({
          transactionOptions: opt instanceof TransactionOptions ? opt : new TransactionOptions(opt)
        });
      }
      withRetryOptions(opt) {
        return this._cloneWith({
          retryOptions: opt instanceof RetryOptions ? opt : new RetryOptions(opt.attempts, opt.backoff)
        });
      }
      withWarningHandler(handler) {
        return this._cloneWith({ warningHandler: handler });
      }
      isDefaultSession() {
        return this.config.size === 0 && this.globals.size === 0 && this.moduleAliases.size === 0 && this.module === "default" && this.transactionOptions.isDefault();
      }
      static defaults() {
        return _defaultOptions;
      }
    };
    exports2.Options = Options;
    var _defaultOptions = new Options();
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js
var require_event = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var errors_1 = require_errors();
    var Event = class {
      _promise;
      _resolve;
      _reject;
      _done;
      async wait() {
        await this._promise;
      }
      then(..._args) {
        throw new errors_1.InternalClientError("Event objects cannot be awaited on directly; use Event.wait()");
      }
      get done() {
        return this._done;
      }
      set() {
        if (this._done) {
          throw new errors_1.InternalClientError("emit(): the Event is already set");
        }
        this._resolve(true);
      }
      setError(reason) {
        if (this._done) {
          throw new errors_1.InternalClientError("emitError(): the Event is already set");
        }
        this._reject(reason);
      }
      constructor() {
        this._done = false;
        let futReject = null;
        let futResolve = null;
        this._promise = new Promise((resolve2, reject) => {
          futReject = (reason) => {
            this._done = true;
            reject(reason);
          };
          futResolve = (value) => {
            this._done = true;
            resolve2(value);
          };
        });
        if (!futReject || !futResolve) {
          throw new errors_1.InternalClientError("Promise executor was not called synchronously");
        }
        this._reject = futReject;
        this._resolve = futResolve;
      }
    };
    exports2.default = Event;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js
var require_queues = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LifoQueue = void 0;
    var errors_1 = require_errors();
    var LifoQueue = class {
      _promises;
      _resolvers;
      _rejecters;
      constructor() {
        this._resolvers = [];
        this._rejecters = [];
        this._promises = [];
      }
      _add() {
        this._promises.push(new Promise((resolve2, reject) => {
          this._resolvers.push(resolve2);
          this._rejecters.push(reject);
        }));
      }
      push(item) {
        if (!this._resolvers.length) {
          this._add();
        }
        const resolve2 = this._resolvers.shift();
        this._rejecters.shift();
        if (!resolve2) {
          throw new errors_1.InternalClientError("resolve function was null or undefined when attempting to push.");
        }
        resolve2(item);
      }
      get() {
        if (!this._promises.length) {
          this._add();
        }
        const promise = this._promises.pop();
        if (!promise) {
          throw new errors_1.InternalClientError("promise was null or undefined when attempting to get.");
        }
        return promise;
      }
      cancelAllPending(err2) {
        const rejecters = this._rejecters;
        this._rejecters = [];
        this._resolvers = [];
        for (const reject of rejecters) {
          reject(err2);
        }
      }
      get length() {
        return this._promises.length - this._resolvers.length;
      }
      get pending() {
        return Math.max(0, this._resolvers.length - this._promises.length);
      }
    };
    exports2.LifoQueue = LifoQueue;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js
var require_retry = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.retryingConnect = retryingConnect;
    var errors = __importStar2(require_errors());
    var utils_1 = require_utils2();
    var lastLoggingAt = 0;
    async function retryingConnect(connectWithTimeout, config, registry) {
      const maxTime = config.connectionParams.waitUntilAvailable === 0 ? 0 : Date.now() + config.connectionParams.waitUntilAvailable;
      while (true) {
        try {
          return await connectWithTimeout(config, registry);
        } catch (e4) {
          if (e4 instanceof errors.ClientConnectionError) {
            if (e4.hasTag(errors.SHOULD_RECONNECT)) {
              const now = Date.now();
              if (now > maxTime) {
                throw e4;
              }
              if (config.logging && (!lastLoggingAt || now - lastLoggingAt > 5e3)) {
                lastLoggingAt = now;
                const logMsg = [
                  `A client connection error occurred; reconnecting because of "waitUntilAvailable=${config.connectionParams.waitUntilAvailable}".`,
                  e4
                ];
                if (!config.fromProject && !config.fromEnv && await config.inProject()) {
                  logMsg.push(`


Hint: it looks like the program is running from a directory initialized with "gel project init". Consider calling "gel.connect()" without arguments.
`);
                }
                console.warn(...logMsg);
              }
            } else {
              throw e4;
            }
          } else {
            console.error("Unexpected connection error:", e4);
            throw e4;
          }
        }
        await (0, utils_1.sleep)(Math.trunc(10 + Math.random() * 200));
      }
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js
var require_enums = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OperatorKind = exports2.SelectModifierKind = exports2.ExpressionKind = exports2.TypeKind = exports2.Cardinality = void 0;
    var Cardinality;
    (function(Cardinality2) {
      Cardinality2["AtMostOne"] = "AtMostOne";
      Cardinality2["One"] = "One";
      Cardinality2["Many"] = "Many";
      Cardinality2["AtLeastOne"] = "AtLeastOne";
      Cardinality2["Empty"] = "Empty";
    })(Cardinality || (exports2.Cardinality = Cardinality = {}));
    var TypeKind;
    (function(TypeKind2) {
      TypeKind2["scalar"] = "scalar";
      TypeKind2["enum"] = "enum";
      TypeKind2["object"] = "object";
      TypeKind2["namedtuple"] = "namedtuple";
      TypeKind2["tuple"] = "tuple";
      TypeKind2["array"] = "array";
      TypeKind2["range"] = "range";
      TypeKind2["multirange"] = "multirange";
    })(TypeKind || (exports2.TypeKind = TypeKind = {}));
    var ExpressionKind;
    (function(ExpressionKind2) {
      ExpressionKind2["Set"] = "Set";
      ExpressionKind2["Array"] = "Array";
      ExpressionKind2["Tuple"] = "Tuple";
      ExpressionKind2["NamedTuple"] = "NamedTuple";
      ExpressionKind2["TuplePath"] = "TuplePath";
      ExpressionKind2["PathNode"] = "PathNode";
      ExpressionKind2["PathLeaf"] = "PathLeaf";
      ExpressionKind2["Literal"] = "Literal";
      ExpressionKind2["Cast"] = "Cast";
      ExpressionKind2["Select"] = "Select";
      ExpressionKind2["Update"] = "Update";
      ExpressionKind2["Delete"] = "Delete";
      ExpressionKind2["Insert"] = "Insert";
      ExpressionKind2["InsertUnlessConflict"] = "InsertUnlessConflict";
      ExpressionKind2["Function"] = "Function";
      ExpressionKind2["Operator"] = "Operator";
      ExpressionKind2["For"] = "For";
      ExpressionKind2["ForVar"] = "ForVar";
      ExpressionKind2["TypeIntersection"] = "TypeIntersection";
      ExpressionKind2["Alias"] = "Alias";
      ExpressionKind2["With"] = "With";
      ExpressionKind2["WithParams"] = "WithParams";
      ExpressionKind2["Param"] = "Param";
      ExpressionKind2["OptionalParam"] = "OptionalParam";
      ExpressionKind2["Detached"] = "Detached";
      ExpressionKind2["Global"] = "Global";
      ExpressionKind2["PolyShapeElement"] = "PolyShapeElement";
      ExpressionKind2["Group"] = "Group";
    })(ExpressionKind || (exports2.ExpressionKind = ExpressionKind = {}));
    var SelectModifierKind;
    (function(SelectModifierKind2) {
      SelectModifierKind2["filter"] = "filter";
      SelectModifierKind2["order_by"] = "order_by";
      SelectModifierKind2["offset"] = "offset";
      SelectModifierKind2["limit"] = "limit";
    })(SelectModifierKind || (exports2.SelectModifierKind = SelectModifierKind = {}));
    var OperatorKind;
    (function(OperatorKind2) {
      OperatorKind2["Infix"] = "Infix";
      OperatorKind2["Postfix"] = "Postfix";
      OperatorKind2["Prefix"] = "Prefix";
      OperatorKind2["Ternary"] = "Ternary";
    })(OperatorKind || (exports2.OperatorKind = OperatorKind = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js
var require_util3 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.util = void 0;
    var ifaces_1 = require_ifaces2();
    var enums_1 = require_enums();
    var util2;
    (function(util3) {
      function assertNever(arg, error2) {
        throw error2 ?? new Error(`${arg} is supposed to be of "never" type`);
      }
      util3.assertNever = assertNever;
      function splitName(name) {
        if (!name.includes("::"))
          throw new Error(`Invalid FQN ${name}`);
        const parts = name.split("::");
        return {
          mod: parts.slice(0, -1).join("::"),
          name: parts[parts.length - 1]
        };
      }
      util3.splitName = splitName;
      function toIdent(name) {
        if (name.includes("::")) {
          throw new Error(`toIdent: invalid name ${name}`);
        }
        return name.replace(/([^a-zA-Z0-9_]+)/g, "_");
      }
      util3.toIdent = toIdent;
      util3.deduplicate = (args) => [...new Set(args)];
      util3.getFromArrayMap = (map2, id) => {
        return map2[id] || [];
      };
      util3.defineProperty = (obj, name, def) => {
        return Object.defineProperty(obj, name, def);
      };
      util3.defineGetter = (obj, name, getter) => {
        return Object.defineProperty(obj, name, {
          get: getter,
          enumerable: true
        });
      };
      util3.defineMethod = (obj, name, method) => {
        obj[name] = method.bind(obj);
        return obj;
      };
      function flatMap(array2, callbackfn) {
        return Array.prototype.concat(...array2.map(callbackfn));
      }
      util3.flatMap = flatMap;
      function omitDollarPrefixed(object) {
        const obj = {};
        for (const key of Object.keys(object)) {
          if (!key.startsWith("$")) {
            obj[key] = object[key];
          }
        }
        return obj;
      }
      util3.omitDollarPrefixed = omitDollarPrefixed;
      util3.parseCardinality = (cardinality) => {
        switch (cardinality) {
          case ifaces_1.Cardinality.MANY:
            return enums_1.Cardinality.Many;
          case ifaces_1.Cardinality.ONE:
            return enums_1.Cardinality.One;
          case ifaces_1.Cardinality.AT_MOST_ONE:
            return enums_1.Cardinality.AtMostOne;
          case ifaces_1.Cardinality.AT_LEAST_ONE:
            return enums_1.Cardinality.AtLeastOne;
          case ifaces_1.Cardinality.NO_RESULT:
            return enums_1.Cardinality.Empty;
        }
        throw new Error(`Unexpected cardinality: ${cardinality}`);
      };
    })(util2 || (exports2.util = util2 = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js
var require_transaction = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Transaction = exports2.TransactionImpl = exports2.TransactionState = void 0;
    var errors = __importStar2(require_errors());
    var ifaces_1 = require_ifaces2();
    var options_1 = require_options();
    var TransactionState;
    (function(TransactionState2) {
      TransactionState2[TransactionState2["ACTIVE"] = 0] = "ACTIVE";
      TransactionState2[TransactionState2["COMMITTED"] = 1] = "COMMITTED";
      TransactionState2[TransactionState2["ROLLEDBACK"] = 2] = "ROLLEDBACK";
      TransactionState2[TransactionState2["FAILED"] = 3] = "FAILED";
    })(TransactionState || (exports2.TransactionState = TransactionState = {}));
    var TransactionImpl = class _TransactionImpl {
      _holder;
      _rawConn;
      _state;
      _opInProgress;
      constructor(holder, rawConn) {
        this._holder = holder;
        this._rawConn = rawConn;
        this._state = TransactionState.ACTIVE;
        this._opInProgress = false;
      }
      static async _startTransaction(holder, optimisticRepeatableRead) {
        const rawConn = await holder._getConnection();
        await rawConn.resetState();
        const options = holder.options.transactionOptions;
        const txOptions = [];
        if (options.isolation === options_1.IsolationLevel.RepeatableRead) {
          txOptions.push(`ISOLATION REPEATABLE READ`);
        } else if (options.isolation === options_1.IsolationLevel.Serializable) {
          txOptions.push(`ISOLATION SERIALIZABLE`);
        } else if (options.isolation === options_1.IsolationLevel.PreferRepeatableRead) {
          if (optimisticRepeatableRead) {
            txOptions.push(`ISOLATION REPEATABLE READ`);
          } else {
            txOptions.push(`ISOLATION SERIALIZABLE`);
          }
        } else if (options.isolation != null) {
          throw new errors.InterfaceError(`Invalid isolation level: ${options.isolation}`);
        }
        if (options.readonly !== void 0) {
          txOptions.push(options.readonly ? "READ ONLY" : "READ WRITE");
        }
        if (options.deferrable !== void 0) {
          txOptions.push(options.deferrable ? "DEFERRABLE" : "NOT DEFERRABLE");
        }
        await rawConn.fetch(`START TRANSACTION ${txOptions.join(", ")};`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, holder.options, true);
        return new _TransactionImpl(holder, rawConn);
      }
      async _waitForConnAbort() {
        await this._rawConn.connAbortWaiter.wait();
        const abortError = this._rawConn.getConnAbortError();
        if (abortError instanceof errors.GelError && abortError.cause instanceof errors.TransactionTimeoutError) {
          throw abortError.cause;
        } else {
          throw abortError;
        }
      }
      async _runOp(opname, op, errMessage) {
        if (this._opInProgress) {
          throw new errors.InterfaceError(errMessage ?? "Another query is in progress. Use the query methods on 'Client' to run queries concurrently.");
        }
        if (this._state !== TransactionState.ACTIVE) {
          throw new errors.InterfaceError(`cannot ${opname}; the transaction is ${this._state === TransactionState.COMMITTED ? "already committed" : this._state === TransactionState.ROLLEDBACK ? "already rolled back" : "in error state"}`);
        }
        this._opInProgress = true;
        try {
          return await op();
        } finally {
          this._opInProgress = false;
        }
      }
      async _runFetchOp(opName, ...args) {
        const { result, warnings } = await this._runOp(opName, () => this._rawConn.fetch(...args));
        if (warnings.length) {
          this._holder.options.warningHandler(warnings);
        }
        return result;
      }
      async _commit() {
        await this._runOp("commit", async () => {
          await this._rawConn.fetch("COMMIT", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
          this._state = TransactionState.COMMITTED;
        }, "A query is still in progress after transaction block has returned.");
      }
      async _rollback() {
        await this._runOp("rollback", async () => {
          await this._rawConn.fetch("ROLLBACK", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
          this._state = TransactionState.ROLLEDBACK;
        }, "A query is still in progress after transaction block has returned.");
      }
    };
    exports2.TransactionImpl = TransactionImpl;
    var Transaction = class _Transaction {
      impl;
      options;
      constructor(impl, options) {
        this.impl = impl;
        this.options = options;
      }
      withSQLRowMode(mode) {
        return new _Transaction(this.impl, this.options.withSQLRowMode(mode));
      }
      async execute(query, args) {
        await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options);
      }
      async executeSQL(query, args) {
        await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options, false, ifaces_1.Language.SQL);
      }
      async query(query, args) {
        return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
      }
      async querySQL(query, args) {
        return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options, false, ifaces_1.Language.SQL);
      }
      async queryJSON(query, args) {
        return this.impl._runFetchOp("queryJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY, this.options);
      }
      async querySingle(query, args) {
        return this.impl._runFetchOp("querySingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
      }
      async querySingleJSON(query, args) {
        return this.impl._runFetchOp("querySingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
      }
      async queryRequired(query, args) {
        return this.impl._runFetchOp("queryRequired", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
      }
      async queryRequiredJSON(query, args) {
        return this.impl._runFetchOp("queryRequiredJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
      }
      async queryRequiredSingle(query, args) {
        return this.impl._runFetchOp("queryRequiredSingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE, this.options);
      }
      async queryRequiredSingleJSON(query, args) {
        return this.impl._runFetchOp("queryRequiredSingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE, this.options);
      }
    };
    exports2.Transaction = Transaction;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js
var require_baseClient = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Client = exports2.BaseClientPool = exports2.ClientConnectionHolder = void 0;
    var registry_1 = require_registry();
    var errors = __importStar2(require_errors());
    var ifaces_1 = require_ifaces2();
    var options_1 = require_options();
    var event_1 = __importDefault2(require_event());
    var queues_1 = require_queues();
    var retry_1 = require_retry();
    var util_1 = require_util3();
    var transaction_1 = require_transaction();
    var utils_1 = require_utils2();
    var ClientConnectionHolder = class {
      _pool;
      _connection;
      _options;
      _inUse;
      constructor(pool) {
        this._pool = pool;
        this._connection = null;
        this._options = null;
        this._inUse = null;
      }
      get options() {
        return this._options ?? options_1.Options.defaults();
      }
      async _getConnection() {
        if (!this._connection || this._connection.isClosed()) {
          this._connection = await this._pool.getNewConnection();
        }
        return this._connection;
      }
      get connectionOpen() {
        return this._connection !== null && !this._connection.isClosed();
      }
      async acquire(options) {
        if (this._inUse) {
          throw new errors.InternalClientError("ClientConnectionHolder cannot be acquired, already in use");
        }
        this._options = options;
        this._inUse = new event_1.default();
        return this;
      }
      async release() {
        var _a2;
        if (this._inUse === null) {
          throw new errors.ClientError("ClientConnectionHolder.release() called on a free connection holder");
        }
        this._options = null;
        await ((_a2 = this._connection) == null ? void 0 : _a2.resetState());
        if (!this._inUse.done) {
          this._inUse.set();
        }
        this._inUse = null;
        this._pool.enqueue(this);
      }
      async _waitUntilReleasedAndClose() {
        var _a2;
        if (this._inUse) {
          await this._inUse.wait();
        }
        await ((_a2 = this._connection) == null ? void 0 : _a2.close());
      }
      terminate() {
        var _a2;
        (_a2 = this._connection) == null ? void 0 : _a2.close();
      }
      async transaction(action) {
        let result;
        let optimisticRepeatableRead = true;
        for (let iteration = 0; ; ++iteration) {
          const transaction = await transaction_1.TransactionImpl._startTransaction(this, optimisticRepeatableRead);
          const clientTx = new transaction_1.Transaction(transaction, this.options);
          let commitFailed = false;
          try {
            result = await Promise.race([
              action(clientTx),
              transaction._waitForConnAbort()
            ]);
            try {
              await transaction._commit();
            } catch (err2) {
              commitFailed = true;
              throw err2;
            }
          } catch (err2) {
            try {
              if (!commitFailed) {
                await transaction._rollback();
              }
            } catch (rollback_err) {
              if (!(rollback_err instanceof errors.GelError)) {
                throw rollback_err;
              }
            }
            if (err2 instanceof errors.CapabilityError && err2.message && err2.message.includes("REPEATABLE READ") && optimisticRepeatableRead) {
              optimisticRepeatableRead = false;
              iteration--;
              continue;
            }
            if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && !(commitFailed && err2 instanceof errors.ClientConnectionError)) {
              const rule = this.options.retryOptions.getRuleForException(err2);
              if (iteration + 1 >= rule.attempts) {
                throw err2;
              }
              await (0, utils_1.sleep)(rule.backoff(iteration + 1));
              continue;
            }
            throw err2;
          }
          return result;
        }
      }
      async retryingFetch(query, args, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
        for (let iteration = 0; ; ++iteration) {
          const conn = await this._getConnection();
          try {
            const { result, warnings } = await conn.fetch(query, args, outputFormat, expectedCardinality, this.options, false, language);
            if (warnings.length) {
              this.options.warningHandler(warnings);
            }
            return result;
          } catch (err2) {
            if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && (conn.getQueryCapabilities(query, outputFormat, expectedCardinality) === 0 || err2 instanceof errors.TransactionConflictError)) {
              const rule = this.options.retryOptions.getRuleForException(err2);
              if (iteration + 1 >= rule.attempts) {
                throw err2;
              }
              await (0, utils_1.sleep)(rule.backoff(iteration + 1));
              continue;
            }
            throw err2;
          }
        }
      }
      async execute(query, args) {
        await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT);
      }
      async executeSQL(query, args) {
        await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, ifaces_1.Language.SQL);
      }
      async query(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY);
      }
      async querySQL(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, ifaces_1.Language.SQL);
      }
      async queryJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY);
      }
      async querySingle(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE);
      }
      async querySingleJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE);
      }
      async queryRequired(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE);
      }
      async queryRequiredJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE);
      }
      async queryRequiredSingle(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE);
      }
      async queryRequiredSingleJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE);
      }
    };
    exports2.ClientConnectionHolder = ClientConnectionHolder;
    var BaseClientPool = class {
      _parseConnectArguments;
      _closing;
      _queue;
      _holders;
      _userConcurrency;
      _suggestedConcurrency;
      _connectConfig;
      _codecsRegistry;
      constructor(_parseConnectArguments, options) {
        this._parseConnectArguments = _parseConnectArguments;
        this.validateClientOptions(options);
        this._codecsRegistry = new registry_1.CodecsRegistry();
        this._queue = new queues_1.LifoQueue();
        this._holders = [];
        this._userConcurrency = options.concurrency ?? null;
        this._suggestedConcurrency = null;
        this._closing = null;
        this._connectConfig = { ...options };
        this._resizeHolderPool();
      }
      validateClientOptions(opts) {
        if (opts.concurrency != null && (typeof opts.concurrency !== "number" || !Number.isInteger(opts.concurrency) || opts.concurrency < 0)) {
          throw new errors.InterfaceError(`invalid 'concurrency' value: expected integer greater than 0 (got ${JSON.stringify(opts.concurrency)})`);
        }
      }
      _getStats() {
        return {
          queueLength: this._queue.pending,
          openConnections: this._holders.filter((holder) => holder.connectionOpen).length
        };
      }
      async ensureConnected() {
        if (this._closing) {
          throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
        }
        if (this._getStats().openConnections > 0) {
          return;
        }
        const connHolder = await this._queue.get();
        try {
          await connHolder._getConnection();
        } finally {
          this._queue.push(connHolder);
        }
      }
      get _concurrency() {
        return this._userConcurrency ?? this._suggestedConcurrency ?? 1;
      }
      _resizeHolderPool() {
        const holdersDiff = this._concurrency - this._holders.length;
        if (holdersDiff > 0) {
          for (let i4 = 0; i4 < holdersDiff; i4++) {
            const connectionHolder = new ClientConnectionHolder(this);
            this._holders.push(connectionHolder);
            this._queue.push(connectionHolder);
          }
        } else if (holdersDiff < 0) {
        }
      }
      __normalizedConnectConfig = null;
      _getNormalizedConnectConfig() {
        return this.__normalizedConnectConfig ?? (this.__normalizedConnectConfig = this._parseConnectArguments(this._connectConfig));
      }
      async resolveConnectionParams() {
        const config = await this._getNormalizedConnectConfig();
        return config.connectionParams;
      }
      async getNewConnection() {
        var _a2;
        if ((_a2 = this._closing) == null ? void 0 : _a2.done) {
          throw new errors.InterfaceError("The client is closed");
        }
        const config = await this._getNormalizedConnectConfig();
        const connection = await (0, retry_1.retryingConnect)(this._connectWithTimeout, config, this._codecsRegistry);
        const suggestedConcurrency = connection.serverSettings.suggested_pool_concurrency;
        if (suggestedConcurrency && suggestedConcurrency !== this._suggestedConcurrency) {
          this._suggestedConcurrency = suggestedConcurrency;
          this._resizeHolderPool();
        }
        return connection;
      }
      async acquireHolder(options) {
        if (this._closing) {
          throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
        }
        const connectionHolder = await this._queue.get();
        try {
          return await connectionHolder.acquire(options);
        } catch (error2) {
          this._queue.push(connectionHolder);
          throw error2;
        }
      }
      enqueue(holder) {
        this._queue.push(holder);
      }
      async close() {
        if (this._closing) {
          return await this._closing.wait();
        }
        this._closing = new event_1.default();
        this._queue.cancelAllPending(new errors.InterfaceError(`The client is closing`));
        const warningTimeoutId = setTimeout(() => {
          console.warn("Client.close() is taking over 60 seconds to complete. Check if you have any unreleased connections left.");
        }, 6e4);
        try {
          await Promise.all(this._holders.map((connectionHolder) => connectionHolder._waitUntilReleasedAndClose()));
        } catch (err2) {
          this._terminate();
          this._closing.setError(err2);
          throw err2;
        } finally {
          clearTimeout(warningTimeoutId);
        }
        this._closing.set();
      }
      _terminate() {
        for (const connectionHolder of this._holders) {
          connectionHolder.terminate();
        }
      }
      terminate() {
        var _a2;
        if ((_a2 = this._closing) == null ? void 0 : _a2.done) {
          return;
        }
        this._queue.cancelAllPending(new errors.InterfaceError(`The client is closed`));
        this._terminate();
        if (!this._closing) {
          this._closing = new event_1.default();
          this._closing.set();
        }
      }
      isClosed() {
        return !!this._closing;
      }
    };
    exports2.BaseClientPool = BaseClientPool;
    var Client = class _Client {
      pool;
      options;
      constructor(pool, options) {
        this.pool = pool;
        this.options = options;
      }
      withTransactionOptions(opts) {
        return new _Client(this.pool, this.options.withTransactionOptions(opts));
      }
      withRetryOptions(opts) {
        return new _Client(this.pool, this.options.withRetryOptions(opts));
      }
      withModuleAliases(aliases) {
        return new _Client(this.pool, this.options.withModuleAliases(aliases));
      }
      withConfig(config) {
        return new _Client(this.pool, this.options.withConfig(config));
      }
      withCodecs(codecs) {
        return new _Client(this.pool, this.options.withCodecs(codecs));
      }
      withSQLRowMode(mode) {
        return new _Client(this.pool, this.options.withSQLRowMode(mode));
      }
      withGlobals(globals) {
        return new _Client(this.pool, this.options.withGlobals(globals));
      }
      withQueryTag(tag) {
        return new _Client(this.pool, this.options.withQueryTag(tag));
      }
      withWarningHandler(handler) {
        return new _Client(this.pool, this.options.withWarningHandler(handler));
      }
      async ensureConnected() {
        await this.pool.ensureConnected();
        return this;
      }
      async resolveConnectionParams() {
        return this.pool.resolveConnectionParams();
      }
      isClosed() {
        return this.pool.isClosed();
      }
      async close() {
        await this.pool.close();
      }
      terminate() {
        this.pool.terminate();
      }
      async transaction(action) {
        if (this.pool.isStateless) {
          throw new errors.GelError(`cannot use 'transaction()' API on HTTP client`);
        }
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.transaction(action);
        } finally {
          await holder.release();
        }
      }
      async execute(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.execute(query, args);
        } finally {
          await holder.release();
        }
      }
      async executeSQL(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.executeSQL(query, args);
        } finally {
          await holder.release();
        }
      }
      async query(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.query(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySQL(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySQL(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySingle(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySingle(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySingleJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySingleJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequired(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequired(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredSingle(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredSingle(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredSingleJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredSingleJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async describe(query) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          const cxn = await holder._getConnection();
          const result = await cxn._parse(ifaces_1.Language.EDGEQL, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
          const cardinality = util_1.util.parseCardinality(result[0]);
          return {
            in: result[1],
            out: result[2],
            cardinality,
            capabilities: result[3]
          };
        } finally {
          await holder.release();
        }
      }
      async parse(query) {
        return await this.describe(query);
      }
    };
    exports2.Client = Client;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js
var require_systemUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.readFileUtf8 = readFileUtf8;
    exports2.hasFSReadPermission = hasFSReadPermission;
    exports2.hashSHA1toHex = hashSHA1toHex;
    exports2.walk = walk;
    exports2.exists = exists;
    exports2.input = input;
    var crypto7 = __importStar2(require("node:crypto"));
    var node_fs_1 = require("node:fs");
    var node_path_1 = __importDefault2(require("node:path"));
    var node_process_1 = __importDefault2(require("node:process"));
    var readline = __importStar2(require("node:readline"));
    var node_stream_1 = require("node:stream");
    async function readFileUtf8(...pathParts) {
      return await node_fs_1.promises.readFile(node_path_1.default.join(...pathParts), { encoding: "utf8" });
    }
    function hasFSReadPermission() {
      if (typeof Deno !== "undefined") {
        return Deno.permissions.querySync({ name: "read" }).state === "granted";
      }
      return true;
    }
    function hashSHA1toHex(msg) {
      return crypto7.createHash("sha1").update(msg).digest("hex");
    }
    async function walk(dir, params) {
      const { match: match2, skip = [] } = params || {};
      try {
        await node_fs_1.promises.access(dir);
      } catch (_err) {
        return [];
      }
      const dirents = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
      const files = await Promise.all(dirents.map((dirent) => {
        const fspath = node_path_1.default.resolve(dir, dirent.name);
        if (skip) {
          if (skip.some((re) => re.test(fspath))) {
            return [];
          }
        }
        if (dirent.isDirectory()) {
          return walk(fspath, params);
        }
        if (match2) {
          if (!match2.some((re) => re.test(fspath))) {
            return [];
          }
        }
        return [fspath];
      }));
      return Array.prototype.concat(...files);
    }
    async function exists(filepath) {
      try {
        await node_fs_1.promises.access(filepath);
        return true;
      } catch {
        return false;
      }
    }
    async function input(message, params) {
      let silent = false;
      const output = (params == null ? void 0 : params.silent) ? new node_stream_1.Writable({
        write(chunk, encoding, callback) {
          if (!silent)
            node_process_1.default.stdout.write(chunk, encoding);
          callback();
        }
      }) : node_process_1.default.stdout;
      const rl = readline.createInterface({
        input: node_process_1.default.stdin,
        output
      });
      return new Promise((resolve2) => {
        rl.question(message, (val2) => {
          rl.close();
          resolve2(val2);
        });
        silent = true;
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js
var require_platform = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isWindows = void 0;
    exports2.searchConfigDir = searchConfigDir;
    var node_path_1 = __importDefault2(require("node:path"));
    var node_os_1 = __importDefault2(require("node:os"));
    var systemUtils_1 = require_systemUtils();
    exports2.isWindows = process.platform === "win32";
    var homeDir = node_os_1.default.homedir;
    var _configDir;
    if (process.platform === "darwin") {
      _configDir = () => {
        return node_path_1.default.join(homeDir(), "Library", "Application Support", "edgedb");
      };
    } else if (process.platform === "win32") {
      _configDir = () => {
        const localAppDataDir = process.env.LOCALAPPDATA ?? node_path_1.default.join(homeDir(), "AppData", "Local");
        return node_path_1.default.join(localAppDataDir, "EdgeDB", "config");
      };
    } else {
      _configDir = () => {
        let xdgConfigDir = process.env.XDG_CONFIG_HOME;
        if (!xdgConfigDir || !node_path_1.default.isAbsolute(xdgConfigDir)) {
          xdgConfigDir = node_path_1.default.join(homeDir(), ".config");
        }
        return node_path_1.default.join(xdgConfigDir, "edgedb");
      };
    }
    async function searchConfigDir(...configPath) {
      const filePath = node_path_1.default.join(_configDir(), ...configPath);
      if (await (0, systemUtils_1.exists)(filePath)) {
        return filePath;
      }
      const fallbackPath = node_path_1.default.join(homeDir(), ".edgedb", ...configPath);
      if (await (0, systemUtils_1.exists)(fallbackPath)) {
        return fallbackPath;
      }
      return filePath;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js
var require_credentials = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getCredentialsPath = getCredentialsPath;
    exports2.readCredentialsFile = readCredentialsFile;
    exports2.validateCredentials = validateCredentials;
    var conUtils_1 = require_conUtils();
    var errors_1 = require_errors();
    async function getCredentialsPath(instanceName, serverUtils) {
      return serverUtils.searchConfigDir("credentials", instanceName + ".json");
    }
    async function readCredentialsFile(file, serverUtils) {
      try {
        const data = await serverUtils.readFileUtf8(file);
        return validateCredentials(JSON.parse(data));
      } catch (e4) {
        throw new errors_1.InterfaceError(`cannot read credentials file ${file}: ${e4}`);
      }
    }
    function validateCredentials(data) {
      const port = data.port;
      if (port != null && (typeof port !== "number" || port < 1 || port > 65535)) {
        throw new errors_1.InterfaceError("invalid `port` value");
      }
      const user = data.user;
      if (user == null) {
        throw new errors_1.InterfaceError("`user` key is required");
      }
      if (typeof user !== "string") {
        throw new errors_1.InterfaceError("`user` must be string");
      }
      const result = { user, port };
      const host = data.host;
      if (host != null) {
        if (typeof host !== "string") {
          throw new errors_1.InterfaceError("`host` must be string");
        }
        result.host = host;
      }
      const database = data.database;
      if (database != null) {
        if (typeof database !== "string") {
          throw new errors_1.InterfaceError("`database` must be string");
        }
        result.database = database;
      }
      const branch = data.branch;
      if (branch != null) {
        if (typeof branch !== "string") {
          throw new errors_1.InterfaceError("`branch` must be string");
        }
        if (database != null && branch !== database) {
          throw new errors_1.InterfaceError("`database` and `branch` cannot both be set");
        }
        result.branch = branch;
      }
      const password = data.password;
      if (password != null) {
        if (typeof password !== "string") {
          throw new errors_1.InterfaceError("`password` must be string");
        }
        result.password = password;
      }
      const caData = data.tls_ca;
      if (caData != null) {
        if (typeof caData !== "string") {
          throw new errors_1.InterfaceError("`tls_ca` must be string");
        }
        result.tlsCAData = caData;
      }
      const certData = data.tls_cert_data;
      if (certData != null) {
        if (typeof certData !== "string") {
          throw new errors_1.InterfaceError("`tls_cert_data` must be string");
        }
        if (caData != null && certData !== caData) {
          throw new errors_1.InterfaceError(`both 'tls_ca' and 'tls_cert_data' are defined, and are not in agreement`);
        }
        result.tlsCAData = certData;
      }
      let verifyHostname = data.tls_verify_hostname;
      const tlsSecurity = data.tls_security;
      if (verifyHostname != null) {
        if (typeof verifyHostname === "boolean") {
          verifyHostname = verifyHostname ? "strict" : "no_host_verification";
        } else {
          throw new errors_1.InterfaceError("`tls_verify_hostname` must be boolean");
        }
      }
      if (tlsSecurity != null && (typeof tlsSecurity !== "string" || !conUtils_1.validTlsSecurityValues.includes(tlsSecurity))) {
        throw new errors_1.InterfaceError(`\`tls_security\` must be one of ${conUtils_1.validTlsSecurityValues.map((val2) => `"${val2}"`).join(", ")}`);
      }
      if (verifyHostname && tlsSecurity && verifyHostname !== tlsSecurity && !(verifyHostname === "no_host_verification" && tlsSecurity === "insecure")) {
        throw new errors_1.InterfaceError(`both 'tls_security' and 'tls_verify_hostname' are defined, and are not in agreement`);
      }
      if (tlsSecurity || verifyHostname) {
        result.tlsSecurity = tlsSecurity ?? verifyHostname;
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js
var require_crcHqx = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.crcHqx = crcHqx;
    var crctabHqx = new Uint16Array([
      0,
      4129,
      8258,
      12387,
      16516,
      20645,
      24774,
      28903,
      33032,
      37161,
      41290,
      45419,
      49548,
      53677,
      57806,
      61935,
      4657,
      528,
      12915,
      8786,
      21173,
      17044,
      29431,
      25302,
      37689,
      33560,
      45947,
      41818,
      54205,
      50076,
      62463,
      58334,
      9314,
      13379,
      1056,
      5121,
      25830,
      29895,
      17572,
      21637,
      42346,
      46411,
      34088,
      38153,
      58862,
      62927,
      50604,
      54669,
      13907,
      9842,
      5649,
      1584,
      30423,
      26358,
      22165,
      18100,
      46939,
      42874,
      38681,
      34616,
      63455,
      59390,
      55197,
      51132,
      18628,
      22757,
      26758,
      30887,
      2112,
      6241,
      10242,
      14371,
      51660,
      55789,
      59790,
      63919,
      35144,
      39273,
      43274,
      47403,
      23285,
      19156,
      31415,
      27286,
      6769,
      2640,
      14899,
      10770,
      56317,
      52188,
      64447,
      60318,
      39801,
      35672,
      47931,
      43802,
      27814,
      31879,
      19684,
      23749,
      11298,
      15363,
      3168,
      7233,
      60846,
      64911,
      52716,
      56781,
      44330,
      48395,
      36200,
      40265,
      32407,
      28342,
      24277,
      20212,
      15891,
      11826,
      7761,
      3696,
      65439,
      61374,
      57309,
      53244,
      48923,
      44858,
      40793,
      36728,
      37256,
      33193,
      45514,
      41451,
      53516,
      49453,
      61774,
      57711,
      4224,
      161,
      12482,
      8419,
      20484,
      16421,
      28742,
      24679,
      33721,
      37784,
      41979,
      46042,
      49981,
      54044,
      58239,
      62302,
      689,
      4752,
      8947,
      13010,
      16949,
      21012,
      25207,
      29270,
      46570,
      42443,
      38312,
      34185,
      62830,
      58703,
      54572,
      50445,
      13538,
      9411,
      5280,
      1153,
      29798,
      25671,
      21540,
      17413,
      42971,
      47098,
      34713,
      38840,
      59231,
      63358,
      50973,
      55100,
      9939,
      14066,
      1681,
      5808,
      26199,
      30326,
      17941,
      22068,
      55628,
      51565,
      63758,
      59695,
      39368,
      35305,
      47498,
      43435,
      22596,
      18533,
      30726,
      26663,
      6336,
      2273,
      14466,
      10403,
      52093,
      56156,
      60223,
      64286,
      35833,
      39896,
      43963,
      48026,
      19061,
      23124,
      27191,
      31254,
      2801,
      6864,
      10931,
      14994,
      64814,
      60687,
      56684,
      52557,
      48554,
      44427,
      40424,
      36297,
      31782,
      27655,
      23652,
      19525,
      15522,
      11395,
      7392,
      3265,
      61215,
      65342,
      53085,
      57212,
      44955,
      49082,
      36825,
      40952,
      28183,
      32310,
      20053,
      24180,
      11923,
      16050,
      3793,
      7920
    ]);
    function crcHqx(data, crc) {
      crc &= 65535;
      const len = data.length;
      let i4 = 0;
      while (i4 < len) {
        crc = crc << 8 & 65280 ^ crctabHqx[crc >> 8 ^ data[i4++]];
      }
      return crc;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js
var require_conUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ResolvedConnectConfig = exports2.validTlsSecurityValues = void 0;
    exports2.isValidTlsSecurityValue = isValidTlsSecurityValue;
    exports2.getConnectArgumentsParser = getConnectArgumentsParser;
    exports2.parseDuration = parseDuration;
    var errors = __importStar2(require_errors());
    var credentials_1 = require_credentials();
    var datetime_1 = require_datetime();
    var datetime_2 = require_datetime2();
    var errors_1 = require_errors();
    var buffer_1 = require_buffer();
    var crcHqx_1 = require_crcHqx();
    var DOMAIN_NAME_MAX_LEN = 63;
    exports2.validTlsSecurityValues = [
      "insecure",
      "no_host_verification",
      "strict",
      "default"
    ];
    function isValidTlsSecurityValue(candidate) {
      return typeof candidate === "string" && exports2.validTlsSecurityValues.includes(candidate);
    }
    function getConnectArgumentsParser(utils) {
      return async (opts) => {
        return {
          ...await parseConnectDsnAndArgs(opts, utils),
          connectTimeout: opts.timeout,
          logging: opts.logging ?? true
        };
      };
    }
    function getEnv(envName, _required = false) {
      const gelEnv = envName;
      const edgedbEnv = envName.replace(/^GEL_/, "EDGEDB_");
      const gelValue = process.env[gelEnv];
      const edgedbValue = process.env[edgedbEnv];
      if (gelValue !== void 0 && edgedbValue !== void 0) {
        console.warn(`Both GEL_w+ and EDGEDB_w+ are set; EDGEDB_w+ will be ignored`);
      }
      return gelValue ?? edgedbValue;
    }
    var ResolvedConnectConfig = class {
      _host = null;
      _hostSource = null;
      _port = null;
      _portSource = null;
      _database = null;
      _databaseSource = null;
      _branch = null;
      _branchSource = null;
      _user = null;
      _userSource = null;
      _password = null;
      _passwordSource = null;
      _secretKey = null;
      _secretKeySource = null;
      _cloudProfile = null;
      _cloudProfileSource = null;
      _tlsCAData = null;
      _tlsCADataSource = null;
      _tlsSecurity = null;
      _tlsSecuritySource = null;
      _tlsServerName = null;
      _tlsServerNameSource = null;
      _waitUntilAvailable = null;
      _waitUntilAvailableSource = null;
      serverSettings = {};
      constructor() {
        this.setHost = this.setHost.bind(this);
        this.setPort = this.setPort.bind(this);
        this.setDatabase = this.setDatabase.bind(this);
        this.setBranch = this.setBranch.bind(this);
        this.setUser = this.setUser.bind(this);
        this.setPassword = this.setPassword.bind(this);
        this.setSecretKey = this.setSecretKey.bind(this);
        this.setTlsCAData = this.setTlsCAData.bind(this);
        this.setTlsCAFile = this.setTlsCAFile.bind(this);
        this.setTlsServerName = this.setTlsServerName.bind(this);
        this.setTlsSecurity = this.setTlsSecurity.bind(this);
        this.setWaitUntilAvailable = this.setWaitUntilAvailable.bind(this);
      }
      _setParam(param, value, source, validator2) {
        if (this[`_${param}`] === null) {
          this[`_${param}Source`] = source;
          if (value !== null) {
            this[`_${param}`] = validator2 ? validator2(value) : value;
            return true;
          }
        }
        return false;
      }
      async _setParamAsync(param, value, source, validator2) {
        if (this[`_${param}`] === null) {
          this[`_${param}Source`] = source;
          if (value !== null) {
            this[`_${param}`] = validator2 ? await validator2(value) : value;
            return true;
          }
        }
        return false;
      }
      setHost(host, source) {
        return this._setParam("host", host, source, validateHost);
      }
      setPort(port, source) {
        return this._setParam("port", port, source, parseValidatePort);
      }
      setDatabase(database, source) {
        return this._setParam("database", database, source, (db) => {
          if (db === "") {
            throw new errors_1.InterfaceError(`invalid database name: '${db}'`);
          }
          return db;
        });
      }
      setBranch(branch, source) {
        return this._setParam("branch", branch, source, (branchName) => {
          if (branchName === "") {
            throw new errors_1.InterfaceError(`invalid branch name: '${branchName}'`);
          }
          return branchName;
        });
      }
      setUser(user, source) {
        return this._setParam("user", user, source, (_user) => {
          if (_user === "") {
            throw new errors_1.InterfaceError(`invalid user name: '${_user}'`);
          }
          return _user;
        });
      }
      setPassword(password, source) {
        return this._setParam("password", password, source);
      }
      setSecretKey(secretKey, source) {
        return this._setParam("secretKey", secretKey, source);
      }
      setCloudProfile(cloudProfile, source) {
        return this._setParam("cloudProfile", cloudProfile, source);
      }
      setTlsCAData(caData, source) {
        return this._setParam("tlsCAData", caData, source);
      }
      setTlsCAFile(caFile, source, readFile2) {
        return this._setParamAsync("tlsCAData", caFile, source, (caFilePath) => readFile2(caFilePath));
      }
      setTlsServerName(serverName, source) {
        return this._setParam("tlsServerName", serverName, source, validateHost);
      }
      setTlsSecurity(tlsSecurity, source) {
        return this._setParam("tlsSecurity", tlsSecurity, source, (_tlsSecurity) => {
          if (!exports2.validTlsSecurityValues.includes(_tlsSecurity)) {
            throw new errors_1.InterfaceError(`invalid 'tlsSecurity' value: '${_tlsSecurity}', must be one of ${exports2.validTlsSecurityValues.map((val2) => `'${val2}'`).join(", ")}`);
          }
          const clientSecurity = getEnv("GEL_CLIENT_SECURITY");
          if (clientSecurity !== void 0) {
            if (!["default", "insecure_dev_mode", "strict"].includes(clientSecurity)) {
              throw new errors_1.InterfaceError(`invalid GEL_CLIENT_SECURITY value: '${clientSecurity}', must be one of 'default', 'insecure_dev_mode' or 'strict'`);
            }
            if (clientSecurity === "insecure_dev_mode") {
              if (_tlsSecurity === "default") {
                _tlsSecurity = "insecure";
              }
            } else if (clientSecurity === "strict") {
              if (_tlsSecurity === "insecure" || _tlsSecurity === "no_host_verification") {
                throw new errors_1.InterfaceError(`'tlsSecurity' value (${_tlsSecurity}) conflicts with GEL_CLIENT_SECURITY value (${clientSecurity}), 'tlsSecurity' value cannot be lower than security level set by GEL_CLIENT_SECURITY`);
              }
              _tlsSecurity = "strict";
            }
          }
          return _tlsSecurity;
        });
      }
      setWaitUntilAvailable(duration, source) {
        return this._setParam("waitUntilAvailable", duration, source, parseDuration);
      }
      addServerSettings(settings) {
        this.serverSettings = {
          ...settings,
          ...this.serverSettings
        };
      }
      get address() {
        return [this._host ?? "localhost", this._port ?? 5656];
      }
      get database() {
        return this._database ?? this._branch ?? "edgedb";
      }
      get branch() {
        return this._branch ?? this._database ?? "__default__";
      }
      get user() {
        return this._user ?? "edgedb";
      }
      get password() {
        return this._password ?? void 0;
      }
      get secretKey() {
        return this._secretKey ?? void 0;
      }
      get cloudProfile() {
        return this._cloudProfile ?? "default";
      }
      get tlsServerName() {
        return this._tlsServerName ?? void 0;
      }
      get tlsSecurity() {
        return this._tlsSecurity && this._tlsSecurity !== "default" ? this._tlsSecurity : this._tlsCAData !== null ? "no_host_verification" : "strict";
      }
      get waitUntilAvailable() {
        return this._waitUntilAvailable ?? 3e4;
      }
      explainConfig() {
        const output = [
          `Parameter          Value                                    Source`,
          `---------          -----                                    ------`
        ];
        const outputLine = (param, val2, rawVal, source) => {
          const isDefault = rawVal === null;
          const maxValLength = 40 - (isDefault ? 10 : 0);
          let value = String(val2);
          if (value.length > maxValLength) {
            value = value.slice(0, maxValLength - 3) + "...";
          }
          output.push(param.padEnd(19, " ") + (value + (isDefault ? " (default)" : "")).padEnd(42, " ") + (source ?? "default"));
        };
        outputLine("host", this.address[0], this._host, this._hostSource);
        outputLine("port", this.address[1], this._port, this._portSource);
        outputLine("database", this.database, this._database, this._databaseSource);
        outputLine("branch", this.branch, this._branch, this._branchSource);
        outputLine("user", this.user, this._user, this._userSource);
        outputLine("password", this.password && this.password.slice(0, 3).padEnd(this.password.length, "*"), this._password, this._passwordSource);
        outputLine("tlsCAData", this._tlsCAData && this._tlsCAData.replace(/\r\n?|\n/, ""), this._tlsCAData, this._tlsCADataSource);
        outputLine("tlsSecurity", this.tlsSecurity, this._tlsSecurity, this._tlsSecuritySource);
        outputLine("tlsServerName", this.tlsServerName, this._tlsServerName, this._tlsServerNameSource);
        outputLine("waitUntilAvailable", this.waitUntilAvailable, this._waitUntilAvailable, this._waitUntilAvailableSource);
        return output.join("\n");
      }
    };
    exports2.ResolvedConnectConfig = ResolvedConnectConfig;
    function parseValidatePort(port) {
      let parsedPort;
      if (typeof port === "string") {
        if (!/^\d*$/.test(port)) {
          throw new errors_1.InterfaceError(`invalid port: ${port}`);
        }
        parsedPort = parseInt(port, 10);
        if (Number.isNaN(parsedPort)) {
          throw new errors_1.InterfaceError(`invalid port: ${port}`);
        }
      } else {
        parsedPort = port;
      }
      if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
        throw new errors_1.InterfaceError(`invalid port: ${port}`);
      }
      return parsedPort;
    }
    function validateHost(host) {
      if (host.includes("/")) {
        throw new errors_1.InterfaceError(`unix socket paths not supported`);
      }
      if (!host.length || host.includes(",")) {
        throw new errors_1.InterfaceError(`invalid host: '${host}'`);
      }
      return host;
    }
    function parseDuration(duration) {
      if (typeof duration === "number") {
        if (duration < 0) {
          throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
        }
        return duration;
      }
      if (typeof duration === "string") {
        if (duration.startsWith("P")) {
          duration = datetime_1.Duration.from(duration);
        } else {
          return (0, datetime_1.parseHumanDurationString)(duration);
        }
      }
      if (duration instanceof datetime_1.Duration) {
        const invalidField = (0, datetime_2.checkValidGelDuration)(duration);
        if (invalidField) {
          throw new errors_1.InterfaceError(`invalid waitUntilAvailable duration, cannot have a '${invalidField}' value`);
        }
        if (duration.sign < 0) {
          throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
        }
        return duration.milliseconds + duration.seconds * 1e3 + duration.minutes * 6e4 + duration.hours * 36e5;
      }
      throw new errors_1.InterfaceError(`invalid duration`);
    }
    async function parseConnectDsnAndArgs(config, serverUtils) {
      const resolvedConfig = new ResolvedConnectConfig();
      let fromEnv = false;
      let fromProject = false;
      const [dsn, instanceName] = config.instanceName == null && config.dsn != null && !/^[a-z]+:\/\//i.test(config.dsn) ? [void 0, config.dsn] : [config.dsn, config.instanceName];
      let { hasCompoundOptions } = await resolveConfigOptions(resolvedConfig, {
        dsn,
        instanceName,
        credentials: config.credentials,
        credentialsFile: config.credentialsFile,
        host: config.host,
        port: config.port,
        database: config.database,
        branch: config.branch,
        user: config.user,
        password: config.password,
        secretKey: config.secretKey,
        cloudProfile: getEnv("GEL_CLOUD_PROFILE"),
        tlsCA: config.tlsCA,
        tlsCAFile: config.tlsCAFile,
        tlsServerName: config.tlsServerName,
        tlsSecurity: config.tlsSecurity,
        serverSettings: config.serverSettings,
        waitUntilAvailable: config.waitUntilAvailable
      }, {
        dsn: `'dsnOrInstanceName' option (parsed as dsn)`,
        instanceName: config.instanceName != null ? `'instanceName' option` : `'dsnOrInstanceName' option (parsed as instance name)`,
        credentials: `'credentials' option`,
        credentialsFile: `'credentialsFile' option`,
        host: `'host' option`,
        port: `'port' option`,
        database: `'database' option`,
        branch: `'branch' option`,
        user: `'user' option`,
        password: `'password' option`,
        secretKey: `'secretKey' option`,
        cloudProfile: `'GEL_CLOUD_PROFILE' environment variable`,
        tlsCA: `'tlsCA' option`,
        tlsCAFile: `'tlsCAFile' option`,
        tlsSecurity: `'tlsSecurity' option`,
        tlsServerName: `'tlsServerName' option`,
        serverSettings: `'serverSettings' option`,
        waitUntilAvailable: `'waitUntilAvailable' option`
      }, `Cannot have more than one of the following connection options: 'dsn', 'instanceName', 'credentials', 'credentialsFile' or 'host'/'port'`, serverUtils);
      if (!hasCompoundOptions) {
        let port = getEnv("GEL_PORT");
        if (resolvedConfig._port === null && (port == null ? void 0 : port.startsWith("tcp://"))) {
          console.warn(`GEL_PORT in 'tcp://host:port' format, so will be ignored`);
          port = void 0;
        }
        ({ hasCompoundOptions, anyOptionsUsed: fromEnv } = await resolveConfigOptions(resolvedConfig, {
          dsn: getEnv("GEL_DSN"),
          instanceName: getEnv("GEL_INSTANCE"),
          credentials: getEnv("GEL_CREDENTIALS"),
          credentialsFile: getEnv("GEL_CREDENTIALS_FILE"),
          host: getEnv("GEL_HOST"),
          port,
          database: getEnv("GEL_DATABASE"),
          branch: getEnv("GEL_BRANCH"),
          user: getEnv("GEL_USER"),
          password: getEnv("GEL_PASSWORD"),
          secretKey: getEnv("GEL_SECRET_KEY"),
          tlsCA: getEnv("GEL_TLS_CA"),
          tlsCAFile: getEnv("GEL_TLS_CA_FILE"),
          tlsServerName: getEnv("GEL_TLS_SERVER_NAME"),
          tlsSecurity: getEnv("GEL_CLIENT_TLS_SECURITY"),
          waitUntilAvailable: getEnv("GEL_WAIT_UNTIL_AVAILABLE")
        }, {
          dsn: `'GEL_DSN' environment variable`,
          instanceName: `'GEL_INSTANCE' environment variable`,
          credentials: `'GEL_CREDENTIALS' environment variable`,
          credentialsFile: `'GEL_CREDENTIALS_FILE' environment variable`,
          host: `'GEL_HOST' environment variable`,
          port: `'GEL_PORT' environment variable`,
          database: `'GEL_DATABASE' environment variable`,
          branch: `'GEL_BRANCH' environment variable`,
          user: `'GEL_USER' environment variable`,
          password: `'GEL_PASSWORD' environment variable`,
          secretKey: `'GEL_SECRET_KEY' environment variable`,
          tlsCA: `'GEL_TLS_CA' environment variable`,
          tlsCAFile: `'GEL_TLS_CA_FILE' environment variable`,
          tlsServerName: `'GEL_TLS_SERVER_NAME' environment variable`,
          tlsSecurity: `'GEL_CLIENT_TLS_SECURITY' environment variable`,
          waitUntilAvailable: `'GEL_WAIT_UNTIL_AVAILABLE' environment variable`
        }, `Cannot have more than one of the following connection environment variables: 'GEL_DSN', 'GEL_INSTANCE', 'GEL_CREDENTIALS', 'GEL_CREDENTIALS_FILE' or 'GEL_HOST'`, serverUtils));
      }
      if (!hasCompoundOptions) {
        if (!serverUtils) {
          throw new errors.ClientConnectionError("no connection options specified either by arguments to `createClient` API or environment variables; also cannot resolve from project config file in browser (or edge runtime) environment");
        }
        const projectDir = await (serverUtils == null ? void 0 : serverUtils.findProjectDir());
        if (!projectDir) {
          throw new errors.ClientConnectionError("no project config file found and no connection options specified either via arguments to `createClient()` API or via environment variables GEL_HOST, GEL_INSTANCE, GEL_DSN, GEL_CREDENTIALS or GEL_CREDENTIALS_FILE");
        }
        const stashDir = await serverUtils.findStashPath(projectDir);
        const instName = await serverUtils.readFileUtf8(stashDir, "instance-name").then((name) => name.trim()).catch(() => null);
        if (instName !== null) {
          const [cloudProfile, _database, branch] = await Promise.all([
            serverUtils.readFileUtf8(stashDir, "cloud-profile").then((name) => name.trim()).catch(() => void 0),
            serverUtils.readFileUtf8(stashDir, "database").then((name) => name.trim()).catch(() => void 0),
            serverUtils.readFileUtf8(stashDir, "branch").then((name) => name.trim()).catch(() => void 0)
          ]);
          let database = _database;
          if (database !== void 0 && branch !== void 0) {
            if (database !== branch) {
              throw new errors_1.InterfaceError("Both database and branch exist in the config dir and don't match.");
            } else {
              database = void 0;
            }
          }
          await resolveConfigOptions(resolvedConfig, { instanceName: instName, cloudProfile, database, branch }, {
            instanceName: `project linked instance ('${instName}')`,
            cloudProfile: `project defined cloud instance ('${cloudProfile}')`,
            database: `project default database`,
            branch: `project default branch`
          }, "", serverUtils);
          fromProject = true;
        } else {
          throw new errors.ClientConnectionError("Found project config file but the project is not initialized. Run 'gel project init'.");
        }
      }
      resolvedConfig.setTlsSecurity("default", "default");
      return {
        connectionParams: resolvedConfig,
        inProject: async () => await (serverUtils == null ? void 0 : serverUtils.findProjectDir(false)) != null,
        fromEnv,
        fromProject
      };
    }
    async function resolveConfigOptions(resolvedConfig, config, sources, compoundParamsError, serverUtils) {
      var _a2;
      let anyOptionsUsed = false;
      const readFile2 = (serverUtils == null ? void 0 : serverUtils.readFileUtf8) ?? ((fn) => {
        throw new errors_1.InterfaceError(`cannot read file "${fn}" in browser (or edge runtime) environment`);
      });
      if (config.tlsCA != null && config.tlsCAFile != null) {
        throw new errors_1.InterfaceError(`Cannot specify both ${sources.tlsCA} and ${sources.tlsCAFile}`);
      }
      if (config.database != null) {
        if (config.branch != null) {
          throw new errors_1.InterfaceError(`${sources.database} and ${sources.branch} are mutually exclusive`);
        }
        if (resolvedConfig._branch == null) {
          anyOptionsUsed = resolvedConfig.setDatabase(config.database ?? null, sources.database) || anyOptionsUsed;
        }
      }
      if (config.branch != null) {
        if (resolvedConfig._database == null) {
          anyOptionsUsed = resolvedConfig.setBranch(config.branch ?? null, sources.branch) || anyOptionsUsed;
        }
      }
      anyOptionsUsed = resolvedConfig.setUser(config.user ?? null, sources.user) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setPassword(config.password ?? null, sources.password) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setSecretKey(config.secretKey ?? null, sources.secretKey) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setCloudProfile(config.cloudProfile ?? null, sources.cloudProfile) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsCAData(config.tlsCA ?? null, sources.tlsCA) || anyOptionsUsed;
      anyOptionsUsed = await resolvedConfig.setTlsCAFile(config.tlsCAFile ?? null, sources.tlsCAFile, readFile2) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsServerName(config.tlsServerName ?? null, sources.tlsServerName) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsSecurity(config.tlsSecurity ?? null, sources.tlsSecurity) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setWaitUntilAvailable(config.waitUntilAvailable ?? null, sources.waitUntilAvailable) || anyOptionsUsed;
      resolvedConfig.addServerSettings(config.serverSettings ?? {});
      const compoundParamsCount = [
        config.dsn,
        config.instanceName,
        config.credentials,
        config.credentialsFile,
        config.host ?? config.port
      ].filter((param) => param !== void 0).length;
      if (compoundParamsCount > 1) {
        throw new errors_1.InterfaceError(compoundParamsError);
      }
      if (compoundParamsCount === 1) {
        if (config.dsn !== void 0 || config.host !== void 0 || config.port !== void 0) {
          let dsn = config.dsn;
          if (dsn === void 0) {
            if (config.port !== void 0) {
              resolvedConfig.setPort(config.port, sources.port);
            }
            const host = config.host != null ? validateHost(config.host) : "";
            dsn = `edgedb://${host.includes(":") ? `[${encodeURI(host)}]` : host}`;
          }
          await parseDSNIntoConfig(dsn, resolvedConfig, config.dsn ? sources.dsn : config.host !== void 0 ? sources.host : sources.port, readFile2);
        } else {
          let creds;
          let source;
          if (config.credentials != null) {
            creds = (0, credentials_1.validateCredentials)(JSON.parse(config.credentials));
            source = sources.credentials;
          } else {
            if (!serverUtils && !((_a2 = config.instanceName) == null ? void 0 : _a2.includes("/"))) {
              throw new errors_1.InterfaceError(`cannot ${config.credentialsFile ? `read credentials file "${config.credentialsFile}"` : `resolve instance name "${config.instanceName}"`} in browser (or edge runtime) environment`);
            }
            let credentialsFile = config.credentialsFile;
            if (credentialsFile === void 0) {
              if (/^\w(-?\w)*$/.test(config.instanceName)) {
                credentialsFile = await (0, credentials_1.getCredentialsPath)(config.instanceName, serverUtils);
                source = sources.instanceName;
              } else {
                if (!/^([A-Za-z0-9_-](-?[A-Za-z0-9_])*)\/([A-Za-z0-9](-?[A-Za-z0-9])*)$/.test(config.instanceName)) {
                  throw new errors_1.InterfaceError(`invalid DSN or instance name: '${config.instanceName}'`);
                }
                await parseCloudInstanceNameIntoConfig(resolvedConfig, config.instanceName, sources.instanceName, serverUtils);
                return { hasCompoundOptions: true, anyOptionsUsed: true };
              }
            } else {
              source = sources.credentialsFile;
            }
            creds = await (0, credentials_1.readCredentialsFile)(credentialsFile, serverUtils);
          }
          resolvedConfig.setHost(creds.host ?? null, source);
          resolvedConfig.setPort(creds.port ?? null, source);
          if (creds.database != null) {
            if (resolvedConfig._branch == null) {
              resolvedConfig.setDatabase(creds.database ?? null, source);
            }
          } else if (creds.branch != null) {
            if (resolvedConfig._database == null) {
              resolvedConfig.setBranch(creds.branch ?? null, source);
            }
          }
          resolvedConfig.setUser(creds.user ?? null, source);
          resolvedConfig.setPassword(creds.password ?? null, source);
          resolvedConfig.setTlsCAData(creds.tlsCAData ?? null, source);
          resolvedConfig.setTlsSecurity(creds.tlsSecurity ?? null, source);
        }
        return { hasCompoundOptions: true, anyOptionsUsed: true };
      }
      return { hasCompoundOptions: false, anyOptionsUsed };
    }
    async function parseDSNIntoConfig(_dsnString, config, source, readFile2) {
      let dsnString = _dsnString;
      let regexHostname = null;
      let zoneId = "";
      const regexResult = /\[(.*?)(%25.+?)\]/.exec(_dsnString);
      if (regexResult) {
        regexHostname = regexResult[1];
        zoneId = decodeURI(regexResult[2]);
        dsnString = dsnString.slice(0, regexResult.index + regexHostname.length + 1) + dsnString.slice(regexResult.index + regexHostname.length + regexResult[2].length + 1);
      }
      let parsed;
      try {
        parsed = new URL(dsnString);
        if (regexHostname !== null && parsed.hostname !== `[${regexHostname}]`) {
          throw new Error();
        }
      } catch (_3) {
        throw new errors_1.InterfaceError(`invalid DSN or instance name: '${_dsnString}'`);
      }
      if (parsed.protocol !== "edgedb:" && parsed.protocol !== "gel:") {
        throw new errors_1.InterfaceError(`invalid DSN: scheme is expected to be 'gel', got '${parsed.protocol.slice(0, -1)}'`);
      }
      const searchParams = /* @__PURE__ */ new Map();
      for (const [key, value] of parsed.searchParams) {
        if (searchParams.has(key)) {
          throw new errors_1.InterfaceError(`invalid DSN: duplicate query parameter '${key}'`);
        }
        searchParams.set(key, value);
      }
      async function handleDSNPart(paramName, value, currentValue, setter, formatter = (val2) => val2) {
        if ([
          value || null,
          searchParams.get(paramName),
          searchParams.get(`${paramName}_env`),
          searchParams.get(`${paramName}_file`)
        ].filter((param) => param != null).length > 1) {
          throw new errors_1.InterfaceError(`invalid DSN: more than one of ${value !== null ? `'${paramName}', ` : ""}'?${paramName}=', '?${paramName}_env=' or '?${paramName}_file=' was specified ${dsnString}`);
        }
        if (currentValue === null) {
          let param = value || (searchParams.get(paramName) ?? null);
          let paramSource = source;
          if (param === null) {
            const env3 = searchParams.get(`${paramName}_env`);
            if (env3 != null) {
              param = getEnv(env3, true) ?? null;
              if (param === null) {
                throw new errors_1.InterfaceError(`'${paramName}_env' environment variable '${env3}' doesn't exist`);
              }
              paramSource += ` (${paramName}_env: ${env3})`;
            }
          }
          if (param === null) {
            const file = searchParams.get(`${paramName}_file`);
            if (file != null) {
              param = await readFile2(file);
              paramSource += ` (${paramName}_file: ${file})`;
            }
          }
          param = param !== null ? formatter(param) : null;
          await setter(param, paramSource);
        }
        searchParams.delete(paramName);
        searchParams.delete(`${paramName}_env`);
        searchParams.delete(`${paramName}_file`);
      }
      const hostname = /^\[.*\]$/.test(parsed.hostname) ? parsed.hostname.slice(1, -1) + zoneId : parsed.hostname;
      await handleDSNPart("host", hostname, config._host, config.setHost);
      await handleDSNPart("port", parsed.port, config._port, config.setPort);
      const stripLeadingSlash = (str) => str.replace(/^\//, "");
      const searchParamsContainsDatabase = searchParams.has("database") || searchParams.has("database_env") || searchParams.has("database_file");
      const searchParamsContainsBranch = searchParams.has("branch") || searchParams.has("branch_env") || searchParams.has("branch_file");
      if (searchParamsContainsBranch) {
        if (searchParamsContainsDatabase) {
          throw new errors_1.InterfaceError(`invalid DSN: cannot specify both 'database' and 'branch'`);
        }
        if (config._database === null) {
          await handleDSNPart("branch", stripLeadingSlash(parsed.pathname), config._branch, config.setBranch, stripLeadingSlash);
        } else {
          searchParams.delete("branch");
          searchParams.delete("branch_env");
          searchParams.delete("branch_file");
        }
      } else {
        if (config._branch === null) {
          await handleDSNPart("database", stripLeadingSlash(parsed.pathname), config._database, config.setDatabase, stripLeadingSlash);
        } else {
          searchParams.delete("database");
          searchParams.delete("database_env");
          searchParams.delete("database_file");
        }
      }
      await handleDSNPart("user", parsed.username, config._user, config.setUser);
      await handleDSNPart("password", parsed.password, config._password, config.setPassword);
      await handleDSNPart("secret_key", null, config._secretKey, config.setSecretKey);
      await handleDSNPart("tls_ca", null, config._tlsCAData, config.setTlsCAData);
      await handleDSNPart("tls_ca_file", null, config._tlsCAData, (val2, _source) => config.setTlsCAFile(val2, _source, readFile2));
      await handleDSNPart("tls_server_name", null, config._tlsServerName, config.setTlsServerName);
      await handleDSNPart("tls_security", null, config._tlsSecurity, config.setTlsSecurity);
      await handleDSNPart("wait_until_available", null, config._waitUntilAvailable, config.setWaitUntilAvailable);
      const serverSettings = {};
      for (const [key, value] of searchParams) {
        serverSettings[key] = value;
      }
      config.addServerSettings(serverSettings);
    }
    async function parseCloudInstanceNameIntoConfig(config, cloudInstanceName, source, serverUtils) {
      const normInstanceName = cloudInstanceName.toLowerCase();
      const [org, instanceName] = normInstanceName.split("/");
      const domainName = `${instanceName}--${org}`;
      if (domainName.length > DOMAIN_NAME_MAX_LEN) {
        throw new errors_1.InterfaceError(`invalid instance name: cloud instance name length cannot exceed ${DOMAIN_NAME_MAX_LEN - 1} characters: ${cloudInstanceName}`);
      }
      let secretKey = config.secretKey;
      if (secretKey == null) {
        try {
          if (!serverUtils) {
            throw new errors_1.InterfaceError(`Cannot get secret key from cloud profile in browser (or edge runtime) environment`);
          }
          const profile = config.cloudProfile;
          const profilePath = await serverUtils.searchConfigDir("cloud-credentials", `${profile}.json`);
          const fileData = await serverUtils.readFileUtf8(profilePath);
          secretKey = JSON.parse(fileData)["secret_key"];
          if (!secretKey) {
            throw new errors_1.InterfaceError(`Cloud profile '${profile}' doesn't contain a secret key`);
          }
          config.setSecretKey(secretKey, `cloud-credentials/${profile}.json`);
        } catch (e4) {
          throw new errors_1.InterfaceError(`Cannot connect to cloud instances without a secret key: ${e4}`);
        }
      }
      try {
        const keyParts = secretKey.split(".");
        if (keyParts.length < 2) {
          throw new errors_1.InterfaceError("Invalid secret key: does not contain payload");
        }
        const dnsZone = _jwtBase64Decode(keyParts[1])["iss"];
        if (!dnsZone) {
          throw new errors_1.InterfaceError("Invalid secret key: payload does not contain 'iss' value");
        }
        const dnsBucket = ((0, crcHqx_1.crcHqx)(buffer_1.utf8Encoder.encode(normInstanceName), 0) % 100).toString(10).padStart(2, "0");
        const host = `${domainName}.c-${dnsBucket}.i.${dnsZone}`;
        config.setHost(host, `resolved from 'secretKey' and ${source}`);
      } catch (e4) {
        if (e4 instanceof errors.GelError) {
          throw e4;
        } else {
          throw new errors_1.InterfaceError(`Invalid secret key: ${e4}`);
        }
      }
    }
    function _jwtBase64Decode(payload) {
      return JSON.parse(buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(payload.padEnd(Math.ceil(payload.length / 4) * 4, "="))));
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js
var require_conUtils_server = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseConnectArguments = exports2.serverUtils = void 0;
    exports2.findStashPath = findStashPath;
    var platform = __importStar2(require_platform());
    var node_fs_1 = require("node:fs");
    var node_path_1 = __importDefault2(require("node:path"));
    var systemUtils_1 = require_systemUtils();
    var conUtils_1 = require_conUtils();
    var projectDirCache = /* @__PURE__ */ new Map();
    async function findProjectDir(required = true) {
      if (!required && !(0, systemUtils_1.hasFSReadPermission)()) {
        return null;
      }
      const workingDir = process.cwd();
      if (projectDirCache.has(workingDir)) {
        return projectDirCache.get(workingDir);
      }
      let dir = workingDir;
      const cwdDev = (await node_fs_1.promises.stat(dir)).dev;
      while (true) {
        if (await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "edgedb.toml")) || await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "gel.toml"))) {
          projectDirCache.set(workingDir, dir);
          return dir;
        }
        const parentDir = node_path_1.default.join(dir, "..");
        if (parentDir === dir || (await node_fs_1.promises.stat(parentDir)).dev !== cwdDev) {
          projectDirCache.set(workingDir, null);
          return null;
        }
        dir = parentDir;
      }
    }
    async function findStashPath(projectDir) {
      let projectPath = await node_fs_1.promises.realpath(projectDir);
      if (platform.isWindows && !projectPath.startsWith("\\\\")) {
        projectPath = "\\\\?\\" + projectPath;
      }
      const hash = (0, systemUtils_1.hashSHA1toHex)(projectPath);
      const baseName = node_path_1.default.basename(projectPath);
      const dirName = baseName + "-" + hash;
      return platform.searchConfigDir("projects", dirName);
    }
    exports2.serverUtils = {
      findProjectDir,
      findStashPath,
      readFileUtf8: systemUtils_1.readFileUtf8,
      searchConfigDir: platform.searchConfigDir
    };
    exports2.parseConnectArguments = (0, conUtils_1.getConnectArgumentsParser)(exports2.serverUtils);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js
var require_map = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.errorMapping = void 0;
    var errors = __importStar2(require_errors());
    exports2.errorMapping = /* @__PURE__ */ new Map();
    exports2.errorMapping.set(16777216, errors.InternalServerError);
    exports2.errorMapping.set(33554432, errors.UnsupportedFeatureError);
    exports2.errorMapping.set(50331648, errors.ProtocolError);
    exports2.errorMapping.set(50397184, errors.BinaryProtocolError);
    exports2.errorMapping.set(50397185, errors.UnsupportedProtocolVersionError);
    exports2.errorMapping.set(50397186, errors.TypeSpecNotFoundError);
    exports2.errorMapping.set(50397187, errors.UnexpectedMessageError);
    exports2.errorMapping.set(50462720, errors.InputDataError);
    exports2.errorMapping.set(50462976, errors.ParameterTypeMismatchError);
    exports2.errorMapping.set(50463232, errors.StateMismatchError);
    exports2.errorMapping.set(50528256, errors.ResultCardinalityMismatchError);
    exports2.errorMapping.set(50593792, errors.CapabilityError);
    exports2.errorMapping.set(50594048, errors.UnsupportedCapabilityError);
    exports2.errorMapping.set(50594304, errors.DisabledCapabilityError);
    exports2.errorMapping.set(50594560, errors.UnsafeIsolationLevelError);
    exports2.errorMapping.set(67108864, errors.QueryError);
    exports2.errorMapping.set(67174400, errors.InvalidSyntaxError);
    exports2.errorMapping.set(67174656, errors.EdgeQLSyntaxError);
    exports2.errorMapping.set(67174912, errors.SchemaSyntaxError);
    exports2.errorMapping.set(67175168, errors.GraphQLSyntaxError);
    exports2.errorMapping.set(67239936, errors.InvalidTypeError);
    exports2.errorMapping.set(67240192, errors.InvalidTargetError);
    exports2.errorMapping.set(67240193, errors.InvalidLinkTargetError);
    exports2.errorMapping.set(67240194, errors.InvalidPropertyTargetError);
    exports2.errorMapping.set(67305472, errors.InvalidReferenceError);
    exports2.errorMapping.set(67305473, errors.UnknownModuleError);
    exports2.errorMapping.set(67305474, errors.UnknownLinkError);
    exports2.errorMapping.set(67305475, errors.UnknownPropertyError);
    exports2.errorMapping.set(67305476, errors.UnknownUserError);
    exports2.errorMapping.set(67305477, errors.UnknownDatabaseError);
    exports2.errorMapping.set(67305478, errors.UnknownParameterError);
    exports2.errorMapping.set(67305479, errors.DeprecatedScopingError);
    exports2.errorMapping.set(67371008, errors.SchemaError);
    exports2.errorMapping.set(67436544, errors.SchemaDefinitionError);
    exports2.errorMapping.set(67436800, errors.InvalidDefinitionError);
    exports2.errorMapping.set(67436801, errors.InvalidModuleDefinitionError);
    exports2.errorMapping.set(67436802, errors.InvalidLinkDefinitionError);
    exports2.errorMapping.set(67436803, errors.InvalidPropertyDefinitionError);
    exports2.errorMapping.set(67436804, errors.InvalidUserDefinitionError);
    exports2.errorMapping.set(67436805, errors.InvalidDatabaseDefinitionError);
    exports2.errorMapping.set(67436806, errors.InvalidOperatorDefinitionError);
    exports2.errorMapping.set(67436807, errors.InvalidAliasDefinitionError);
    exports2.errorMapping.set(67436808, errors.InvalidFunctionDefinitionError);
    exports2.errorMapping.set(67436809, errors.InvalidConstraintDefinitionError);
    exports2.errorMapping.set(67436810, errors.InvalidCastDefinitionError);
    exports2.errorMapping.set(67437056, errors.DuplicateDefinitionError);
    exports2.errorMapping.set(67437057, errors.DuplicateModuleDefinitionError);
    exports2.errorMapping.set(67437058, errors.DuplicateLinkDefinitionError);
    exports2.errorMapping.set(67437059, errors.DuplicatePropertyDefinitionError);
    exports2.errorMapping.set(67437060, errors.DuplicateUserDefinitionError);
    exports2.errorMapping.set(67437061, errors.DuplicateDatabaseDefinitionError);
    exports2.errorMapping.set(67437062, errors.DuplicateOperatorDefinitionError);
    exports2.errorMapping.set(67437063, errors.DuplicateViewDefinitionError);
    exports2.errorMapping.set(67437064, errors.DuplicateFunctionDefinitionError);
    exports2.errorMapping.set(67437065, errors.DuplicateConstraintDefinitionError);
    exports2.errorMapping.set(67437066, errors.DuplicateCastDefinitionError);
    exports2.errorMapping.set(67437067, errors.DuplicateMigrationError);
    exports2.errorMapping.set(67502080, errors.SessionTimeoutError);
    exports2.errorMapping.set(67502336, errors.IdleSessionTimeoutError);
    exports2.errorMapping.set(67502592, errors.QueryTimeoutError);
    exports2.errorMapping.set(67504640, errors.TransactionTimeoutError);
    exports2.errorMapping.set(67504641, errors.IdleTransactionTimeoutError);
    exports2.errorMapping.set(83886080, errors.ExecutionError);
    exports2.errorMapping.set(83951616, errors.InvalidValueError);
    exports2.errorMapping.set(83951617, errors.DivisionByZeroError);
    exports2.errorMapping.set(83951618, errors.NumericOutOfRangeError);
    exports2.errorMapping.set(83951619, errors.AccessPolicyError);
    exports2.errorMapping.set(83951620, errors.QueryAssertionError);
    exports2.errorMapping.set(84017152, errors.IntegrityError);
    exports2.errorMapping.set(84017153, errors.ConstraintViolationError);
    exports2.errorMapping.set(84017154, errors.CardinalityViolationError);
    exports2.errorMapping.set(84017155, errors.MissingRequiredError);
    exports2.errorMapping.set(84082688, errors.TransactionError);
    exports2.errorMapping.set(84082944, errors.TransactionConflictError);
    exports2.errorMapping.set(84082945, errors.TransactionSerializationError);
    exports2.errorMapping.set(84082946, errors.TransactionDeadlockError);
    exports2.errorMapping.set(84148224, errors.WatchError);
    exports2.errorMapping.set(100663296, errors.ConfigurationError);
    exports2.errorMapping.set(117440512, errors.AccessError);
    exports2.errorMapping.set(117506048, errors.AuthenticationError);
    exports2.errorMapping.set(134217728, errors.AvailabilityError);
    exports2.errorMapping.set(134217729, errors.BackendUnavailableError);
    exports2.errorMapping.set(134217730, errors.ServerOfflineError);
    exports2.errorMapping.set(134217731, errors.UnknownTenantError);
    exports2.errorMapping.set(134217732, errors.ServerBlockedError);
    exports2.errorMapping.set(150994944, errors.BackendError);
    exports2.errorMapping.set(150995200, errors.UnsupportedBackendFeatureError);
    exports2.errorMapping.set(4026531840, errors.LogMessage);
    exports2.errorMapping.set(4026597376, errors.WarningMessage);
    exports2.errorMapping.set(4026662912, errors.StatusMessage);
    exports2.errorMapping.set(4026662913, errors.MigrationStatusMessage);
    exports2.errorMapping.set(4278190080, errors.ClientError);
    exports2.errorMapping.set(4278255616, errors.ClientConnectionError);
    exports2.errorMapping.set(4278255872, errors.ClientConnectionFailedError);
    exports2.errorMapping.set(4278255873, errors.ClientConnectionFailedTemporarilyError);
    exports2.errorMapping.set(4278256128, errors.ClientConnectionTimeoutError);
    exports2.errorMapping.set(4278256384, errors.ClientConnectionClosedError);
    exports2.errorMapping.set(4278321152, errors.InterfaceError);
    exports2.errorMapping.set(4278321408, errors.QueryArgumentError);
    exports2.errorMapping.set(4278321409, errors.MissingArgumentError);
    exports2.errorMapping.set(4278321410, errors.UnknownArgumentError);
    exports2.errorMapping.set(4278321411, errors.InvalidArgumentError);
    exports2.errorMapping.set(4278386688, errors.NoDataError);
    exports2.errorMapping.set(4278452224, errors.InternalClientError);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js
var require_resolve = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveErrorCode = resolveErrorCode;
    exports2.errorFromJSON = errorFromJSON;
    var errors = __importStar2(require_errors());
    var base_1 = require_base();
    var map_1 = require_map();
    function resolveErrorCode(code) {
      let result;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4294967040;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4294901760;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4278190080;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      return errors.GelError;
    }
    var _JSON_FIELDS = {
      hint: base_1.ErrorAttr.hint,
      details: base_1.ErrorAttr.details,
      start: base_1.ErrorAttr.characterStart,
      end: base_1.ErrorAttr.characterEnd,
      line: base_1.ErrorAttr.lineStart,
      col: base_1.ErrorAttr.columnStart
    };
    function errorFromJSON(data) {
      const errType = resolveErrorCode(data.code);
      const err2 = new errType(data.message);
      const attrs = /* @__PURE__ */ new Map();
      for (const [name, field] of Object.entries(_JSON_FIELDS)) {
        if (data[name] != null) {
          attrs.set(field, data[name]);
        }
      }
      err2._attrs = attrs;
      return err2;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js
var require_baseConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseRawConnection = exports2.RESTRICTED_CAPABILITIES = exports2.Capabilities = exports2.PROTO_VER_MIN = exports2.PROTO_VER = void 0;
    var codecs_1 = require_codecs();
    var object_1 = require_object();
    var utils_1 = require_utils2();
    var errors = __importStar2(require_errors());
    var resolve_1 = require_resolve();
    var context_1 = require_context();
    var ifaces_1 = require_ifaces2();
    var buffer_1 = require_buffer();
    var chars = __importStar2(require_chars());
    var event_1 = __importDefault2(require_event());
    var lru_1 = __importDefault2(require_lru());
    var options_1 = require_options();
    exports2.PROTO_VER = [3, 0];
    exports2.PROTO_VER_MIN = [0, 9];
    var TransactionStatus;
    (function(TransactionStatus2) {
      TransactionStatus2[TransactionStatus2["TRANS_IDLE"] = 0] = "TRANS_IDLE";
      TransactionStatus2[TransactionStatus2["TRANS_ACTIVE"] = 1] = "TRANS_ACTIVE";
      TransactionStatus2[TransactionStatus2["TRANS_INTRANS"] = 2] = "TRANS_INTRANS";
      TransactionStatus2[TransactionStatus2["TRANS_INERROR"] = 3] = "TRANS_INERROR";
      TransactionStatus2[TransactionStatus2["TRANS_UNKNOWN"] = 4] = "TRANS_UNKNOWN";
    })(TransactionStatus || (TransactionStatus = {}));
    var Capabilities;
    (function(Capabilities2) {
      Capabilities2[Capabilities2["NONE"] = 0] = "NONE";
      Capabilities2[Capabilities2["MODIFICATONS"] = 1] = "MODIFICATONS";
      Capabilities2[Capabilities2["SESSION_CONFIG"] = 2] = "SESSION_CONFIG";
      Capabilities2[Capabilities2["TRANSACTION"] = 4] = "TRANSACTION";
      Capabilities2[Capabilities2["DDL"] = 8] = "DDL";
      Capabilities2[Capabilities2["PERSISTENT_CONFIG"] = 16] = "PERSISTENT_CONFIG";
      Capabilities2[Capabilities2["SET_GLOBAL"] = 32] = "SET_GLOBAL";
      Capabilities2[Capabilities2["ALL"] = 4294967295] = "ALL";
    })(Capabilities || (exports2.Capabilities = Capabilities = {}));
    var NO_TRANSACTION_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION) >>> 0;
    var NO_TRANSACTION_CAPABILITIES_BYTES = new Uint8Array(Array(8).fill(255));
    new DataView(NO_TRANSACTION_CAPABILITIES_BYTES.buffer).setUint32(4, NO_TRANSACTION_CAPABILITIES);
    exports2.RESTRICTED_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION & ~Capabilities.SESSION_CONFIG & ~Capabilities.SET_GLOBAL) >>> 0;
    var CompilationFlag;
    (function(CompilationFlag2) {
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_IDS"] = 1] = "INJECT_OUTPUT_TYPE_IDS";
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_NAMES"] = 2] = "INJECT_OUTPUT_TYPE_NAMES";
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_OBJECT_IDS"] = 4] = "INJECT_OUTPUT_OBJECT_IDS";
    })(CompilationFlag || (CompilationFlag = {}));
    var OLD_ERROR_CODES = /* @__PURE__ */ new Map([
      [84082689, 84082945],
      [84082690, 84082946]
    ]);
    var BaseRawConnection = class {
      connected = false;
      lastStatus;
      codecsRegistry;
      queryCodecCache;
      serverSecret;
      serverSettings;
      serverXactStatus;
      buffer;
      messageWaiter;
      connWaiter;
      connAbortWaiter;
      _abortedWith = null;
      protocolVersion = exports2.PROTO_VER;
      stateCodec = codecs_1.INVALID_CODEC;
      stateCache = /* @__PURE__ */ new WeakMap();
      lastStateUpdate = null;
      adminUIMode = false;
      constructor(registry) {
        this.buffer = new buffer_1.ReadMessageBuffer();
        this.codecsRegistry = registry;
        this.queryCodecCache = new lru_1.default({ capacity: 1e3 });
        this.lastStatus = null;
        this.serverSecret = null;
        this.serverSettings = {};
        this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
        this.messageWaiter = null;
        this.connWaiter = new event_1.default();
        this.connAbortWaiter = new event_1.default();
      }
      throwNotImplemented(method) {
        throw new errors.InternalClientError(`method ${method} is not implemented`);
      }
      async _waitForMessage() {
        this.throwNotImplemented("_waitForMessage");
      }
      _sendData(_data3) {
        this.throwNotImplemented("_sendData");
      }
      getConnAbortError() {
        return this._abortedWith ?? new errors.InterfaceError(`client has been closed`);
      }
      _checkState() {
        if (this.isClosed()) {
          throw this.getConnAbortError();
        }
      }
      _abortWithError(err2) {
        this._abortedWith = err2;
        this._abort();
      }
      _ignoreHeaders() {
        let numFields = this.buffer.readInt16();
        while (numFields) {
          this.buffer.readInt16();
          this.buffer.readLenPrefixedBuffer();
          numFields--;
        }
      }
      _readHeaders() {
        const numFields = this.buffer.readInt16();
        const headers = {};
        for (let i4 = 0; i4 < numFields; i4++) {
          const key = this.buffer.readString();
          const value = this.buffer.readString();
          headers[key] = value;
        }
        return headers;
      }
      _abortWaiters(err2) {
        var _a2;
        if (!this.connWaiter.done) {
          this.connWaiter.setError(err2);
        }
        (_a2 = this.messageWaiter) == null ? void 0 : _a2.setError(err2);
        this.messageWaiter = null;
      }
      _parseHeaders() {
        const ret = /* @__PURE__ */ new Map();
        let numFields = this.buffer.readInt16();
        while (numFields) {
          const key = this.buffer.readInt16();
          const value = this.buffer.readLenPrefixedBuffer();
          ret.set(key, value);
          numFields--;
        }
        return ret;
      }
      _parseDescribeTypeMessage(query) {
        let capabilities = -1;
        let warnings = [];
        let unsafeIsolationDangers = [];
        const headers = this._readHeaders();
        if (headers.warnings != null) {
          warnings = JSON.parse(headers.warnings).map((warning3) => {
            const err2 = (0, resolve_1.errorFromJSON)(warning3);
            err2._query = query;
            return err2;
          });
        }
        if (headers.unsafe_isolation_dangers != null) {
          unsafeIsolationDangers = JSON.parse(headers.unsafe_isolation_dangers).map((danger) => {
            const err2 = (0, resolve_1.errorFromJSON)(danger);
            err2._query = query;
            return err2;
          });
        }
        capabilities = Number(this.buffer.readBigInt64());
        const cardinality = this.buffer.readChar();
        const inTypeId = this.buffer.readUUID();
        const inTypeData = this.buffer.readLenPrefixedBuffer();
        const outTypeId = this.buffer.readUUID();
        const outTypeData = this.buffer.readLenPrefixedBuffer();
        this.buffer.finishMessage();
        let inCodec = this.codecsRegistry.getCodec(inTypeId);
        if (inCodec == null) {
          inCodec = this.codecsRegistry.buildCodec(inTypeData, this.protocolVersion);
        }
        let outCodec = this.codecsRegistry.getCodec(outTypeId);
        if (outCodec == null) {
          outCodec = this.codecsRegistry.buildCodec(outTypeData, this.protocolVersion);
        }
        return [
          cardinality,
          inCodec,
          outCodec,
          capabilities,
          inTypeData,
          outTypeData,
          warnings,
          unsafeIsolationDangers
        ];
      }
      _parseCommandCompleteMessage() {
        this._ignoreHeaders();
        this.buffer.readBigInt64();
        const status = this.buffer.readString();
        const stateTypeId = this.buffer.readUUID();
        const stateData = this.buffer.readLenPrefixedBuffer();
        if (this.adminUIMode && stateTypeId === this.stateCodec.tid) {
          this.lastStateUpdate = this.stateCodec.decode(new buffer_1.ReadBuffer(stateData), context_1.NOOP_CODEC_CONTEXT);
        }
        this.buffer.finishMessage();
        return status;
      }
      _parseErrorMessage() {
        this.buffer.readChar();
        const code = this.buffer.readUInt32();
        const message = this.buffer.readString();
        const errorType = (0, resolve_1.resolveErrorCode)(OLD_ERROR_CODES.get(code) ?? code);
        const err2 = new errorType(message);
        err2._attrs = this._parseHeaders();
        this.buffer.finishMessage();
        if (err2 instanceof errors.AuthenticationError) {
          throw err2;
        }
        return err2;
      }
      _parseSyncMessage() {
        this._parseHeaders();
        const status = this.buffer.readChar();
        switch (status) {
          case chars.$I:
            this.serverXactStatus = TransactionStatus.TRANS_IDLE;
            break;
          case chars.$T:
            this.serverXactStatus = TransactionStatus.TRANS_INTRANS;
            break;
          case chars.$E:
            this.serverXactStatus = TransactionStatus.TRANS_INERROR;
            break;
          default:
            this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
        }
        this.buffer.finishMessage();
      }
      _redirectDataMessages(result) {
        const $D = chars.$D;
        const buffer = this.buffer;
        while (buffer.takeMessageType($D)) {
          const msg = buffer.consumeMessage();
          result.writeChar($D);
          result.writeInt32(msg.length + 4);
          result.writeBuffer(msg);
        }
      }
      _parseDataMessages(codec, result, ctx) {
        const frb = buffer_1.ReadBuffer.alloc();
        const $D = chars.$D;
        const buffer = this.buffer;
        if (Array.isArray(result)) {
          while (buffer.takeMessageType($D)) {
            buffer.consumeMessageInto(frb);
            frb.discard(6);
            result.push(codec.decode(frb, ctx));
            frb.finish();
          }
        } else {
          this._redirectDataMessages(result);
        }
      }
      _parseServerSettings(name, value) {
        switch (name) {
          case "suggested_pool_concurrency": {
            this.serverSettings.suggested_pool_concurrency = parseInt(buffer_1.utf8Decoder.decode(value), 10);
            break;
          }
          case "system_config": {
            const buf = new buffer_1.ReadBuffer(value);
            const typedescLen = buf.readInt32() - 16;
            const typedescId = buf.readUUID();
            const typedesc = buf.readBuffer(typedescLen);
            let codec = this.codecsRegistry.getCodec(typedescId);
            if (codec === null) {
              codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
            }
            buf.discard(4);
            const data = codec.decode(buf, context_1.NOOP_CODEC_CONTEXT);
            buf.finish();
            this.serverSettings.system_config = data;
            break;
          }
          default:
            this.serverSettings[name] = value;
            break;
        }
      }
      _parseDescribeStateMessage() {
        const typedescId = this.buffer.readUUID();
        const typedesc = this.buffer.readBuffer(this.buffer.readInt32());
        let codec = this.codecsRegistry.getCodec(typedescId);
        if (codec === null) {
          codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
        }
        this.stateCodec = codec;
        this.stateCache = /* @__PURE__ */ new WeakMap();
        this.buffer.finishMessage();
      }
      _fallthrough() {
        const mtype = this.buffer.getMessageType();
        switch (mtype) {
          case chars.$S: {
            const name = this.buffer.readString();
            const value = this.buffer.readLenPrefixedBuffer();
            this._parseServerSettings(name, value);
            this.buffer.finishMessage();
            break;
          }
          case chars.$L: {
            const severity = this.buffer.readChar();
            const code = this.buffer.readUInt32();
            const message = this.buffer.readString();
            this._parseHeaders();
            this.buffer.finishMessage();
            console.info("SERVER MESSAGE", severity, code, message);
            break;
          }
          default:
            throw new errors.UnexpectedMessageError(`unexpected message type ${mtype} ("${chars.chr(mtype)}")`);
        }
      }
      _encodeArgs(args, inCodec, ctx) {
        if (inCodec === codecs_1.NULL_CODEC) {
          if (args != null) {
            throw new errors.QueryArgumentError(`This query does not contain any query parameters, but query arguments were provided to the 'query*()' method`);
          }
          return codecs_1.NullCodec.BUFFER;
        }
        if (inCodec instanceof object_1.ObjectCodec) {
          return inCodec.encodeArgs(args, ctx);
        }
        throw new errors.ProtocolError("invalid input codec");
      }
      _isInTransaction() {
        return this.serverXactStatus === TransactionStatus.TRANS_INTRANS || this.serverXactStatus === TransactionStatus.TRANS_ACTIVE;
      }
      _setStateCodec(state2) {
        let encodedState = this.stateCache.get(state2);
        if (encodedState) {
          return encodedState;
        }
        const buf = new buffer_1.WriteBuffer();
        this.stateCodec.encode(buf, state2._serialise(), context_1.NOOP_CODEC_CONTEXT);
        encodedState = buf.unwrap();
        this.stateCache.set(state2, encodedState);
        return encodedState;
      }
      _encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, isExecute, unsafeIsolationDangers) {
        if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
          if (state2.annotations.size >= 1 << 16) {
            throw new errors.InternalClientError("too many annotations");
          }
          wb.writeUInt16(state2.annotations.size);
          for (const [name, value] of state2.annotations) {
            wb.writeString(name);
            wb.writeString(value);
          }
        } else {
          wb.writeUInt16(0);
        }
        wb.writeFlags(4294967295, capabilitiesFlags);
        wb.writeFlags(0, 0 | ((options == null ? void 0 : options.injectObjectids) ? CompilationFlag.INJECT_OUTPUT_OBJECT_IDS : 0) | ((options == null ? void 0 : options.injectTypeids) ? CompilationFlag.INJECT_OUTPUT_TYPE_IDS : 0) | ((options == null ? void 0 : options.injectTypenames) ? CompilationFlag.INJECT_OUTPUT_TYPE_NAMES : 0));
        wb.writeBigInt64((options == null ? void 0 : options.implicitLimit) ?? BigInt(0));
        if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
          wb.writeChar(language);
        }
        wb.writeChar(outputFormat);
        wb.writeChar(expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE ? ifaces_1.Cardinality.AT_MOST_ONE : ifaces_1.Cardinality.MANY);
        wb.writeString(query);
        if (!this.adminUIMode && state2.isDefaultSession()) {
          wb.writeBuffer(codecs_1.NULL_CODEC.tidBuffer);
          wb.writeInt32(0);
        } else {
          wb.writeBuffer(this.stateCodec.tidBuffer);
          if (this.stateCodec === codecs_1.INVALID_CODEC || this.stateCodec === codecs_1.NULL_CODEC) {
            wb.writeInt32(0);
          } else {
            if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0]) && isExecute && !this._isInTransaction()) {
              const isolation = state2.transactionOptions.isolation === options_1.IsolationLevel.PreferRepeatableRead ? unsafeIsolationDangers.length === 0 ? options_1.IsolationLevel.RepeatableRead : options_1.IsolationLevel.Serializable : state2.transactionOptions.isolation;
              if (isolation !== state2.config.get("default_transaction_isolation")) {
                state2 = state2.withConfig({
                  default_transaction_isolation: isolation
                }).withTransactionOptions({
                  isolation
                });
              }
              if (state2.transactionOptions.readonly !== state2.config.get("default_transaction_access_mode")) {
                state2 = state2.withConfig({
                  default_transaction_access_mode: state2.transactionOptions.readonly ? "ReadOnly" : "ReadWrite"
                });
              }
            }
            const encodedState = this._setStateCodec(state2);
            wb.writeBuffer(encodedState);
          }
        }
      }
      async _parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$P);
        this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, false, unsafeIsolationDangers);
        wb.endMessage();
        wb.writeSync();
        this._sendData(wb.unwrap());
        let parsing = true;
        let error2 = null;
        let newCard = null;
        let capabilities = -1;
        let inCodec = null;
        let outCodec = null;
        let inCodecBuf = null;
        let outCodecBuf = null;
        let warnings = [];
        while (parsing) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$T: {
              try {
                [
                  newCard,
                  inCodec,
                  outCodec,
                  capabilities,
                  inCodecBuf,
                  outCodecBuf,
                  warnings,
                  unsafeIsolationDangers
                ] = this._parseDescribeTypeMessage(query);
                const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
                this.queryCodecCache.set(key, [
                  newCard,
                  inCodec,
                  outCodec,
                  capabilities,
                  unsafeIsolationDangers
                ]);
              } catch (e4) {
                error2 = e4;
              }
              break;
            }
            case chars.$E: {
              error2 = this._parseErrorMessage();
              error2._query = query;
              break;
            }
            case chars.$s: {
              options_1.Options.signalSchemaChange();
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              parsing = false;
              break;
            }
            default:
              this._fallthrough();
          }
        }
        if (error2 !== null) {
          if (error2 instanceof errors.StateMismatchError) {
            return this._parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, unsafeIsolationDangers);
          }
          throw error2;
        }
        return [
          newCard,
          inCodec,
          outCodec,
          capabilities,
          inCodecBuf,
          outCodecBuf,
          warnings,
          unsafeIsolationDangers
        ];
      }
      async _executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
        let currentUnsafeIsolationDangers = unsafeIsolationDangers;
        let ctx = state2.makeCodecContext();
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$O);
        this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, true, currentUnsafeIsolationDangers);
        wb.writeBuffer(inCodec.tidBuffer);
        wb.writeBuffer(outCodec.tidBuffer);
        if (inCodec) {
          wb.writeBuffer(this._encodeArgs(args, inCodec, ctx));
        } else {
          wb.writeInt32(0);
        }
        wb.endMessage();
        wb.writeSync();
        this._sendData(wb.unwrap());
        let error2 = null;
        let parsing = true;
        let currentWarnings = [];
        while (parsing) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$D: {
              if (error2 == null) {
                try {
                  this._parseDataMessages(outCodec, result, ctx);
                } catch (e4) {
                  error2 = e4;
                  this.buffer.finishMessage();
                }
              } else {
                this.buffer.discardMessage();
              }
              break;
            }
            case chars.$C: {
              this.lastStatus = this._parseCommandCompleteMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              parsing = false;
              break;
            }
            case chars.$T: {
              try {
                ctx = state2.makeCodecContext();
                const [newCard, newInCodec, newOutCodec, capabilities, _3, __, _warnings, _dangers] = this._parseDescribeTypeMessage(query);
                if (outCodec !== codecs_1.NULL_CODEC && outCodec.tid !== newOutCodec.tid || inCodec !== codecs_1.NULL_CODEC && inCodec.tid !== newInCodec.tid) {
                  options_1.Options.signalSchemaChange();
                  ctx = state2.makeCodecContext();
                }
                const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
                this.queryCodecCache.set(key, [
                  newCard,
                  newInCodec,
                  newOutCodec,
                  capabilities,
                  _dangers
                ]);
                outCodec = newOutCodec;
                currentWarnings = _warnings;
                currentUnsafeIsolationDangers = _dangers;
              } catch (e4) {
                options_1.Options.signalSchemaChange();
                error2 = e4;
              }
              break;
            }
            case chars.$s: {
              options_1.Options.signalSchemaChange();
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$E: {
              error2 = this._parseErrorMessage();
              error2._query = query;
              break;
            }
            default:
              this._fallthrough();
          }
        }
        if (error2 != null) {
          if (error2 instanceof errors.StateMismatchError) {
            return this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags, options, currentUnsafeIsolationDangers);
          }
          throw error2;
        }
        return [currentWarnings, currentUnsafeIsolationDangers];
      }
      _getQueryCacheKey(query, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
        const expectOne = expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
        return [language, outputFormat, expectOne, query.length, query].join(";");
      }
      _validateFetchCardinality(card, outputFormat, expectedCardinality) {
        if (expectedCardinality === ifaces_1.Cardinality.ONE && card === ifaces_1.Cardinality.NO_RESULT) {
          throw new errors.NoDataError(`query executed via queryRequiredSingle${outputFormat === ifaces_1.OutputFormat.JSON ? "JSON" : ""}() returned no data`);
        }
      }
      async fetch(query, args = null, outputFormat, expectedCardinality, state2, privilegedMode = false, language = ifaces_1.Language.EDGEQL) {
        if (language !== ifaces_1.Language.EDGEQL && (0, utils_1.versionGreaterThan)([3, 0], this.protocolVersion)) {
          throw new errors.UnsupportedFeatureError(`the server does not support SQL queries, upgrade to 6.0 or newer`);
        }
        this._checkState();
        const requiredOne = expectedCardinality === ifaces_1.Cardinality.ONE;
        const expectOne = requiredOne || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
        const asJson = outputFormat === ifaces_1.OutputFormat.JSON;
        const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality, language);
        const ret = [];
        let warnings = [];
        let [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key) ?? [];
        if (card) {
          this._validateFetchCardinality(card, outputFormat, expectedCardinality);
        }
        if (!inCodec && args !== null || this.stateCodec === codecs_1.INVALID_CODEC && !state2.isDefaultSession()) {
          [card, inCodec, outCodec, , , , warnings, unsafeIsolationDangers] = await this._parse(language, query, outputFormat, expectedCardinality, state2, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
          this._validateFetchCardinality(card, outputFormat, expectedCardinality);
        }
        try {
          [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
        } catch (e4) {
          if (e4 instanceof errors.ParameterTypeMismatchError) {
            [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key);
            [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0);
          } else {
            throw e4;
          }
        }
        if (outputFormat === ifaces_1.OutputFormat.NONE) {
          return { result: null, warnings, unsafeIsolationDangers };
        }
        if (expectOne) {
          if (requiredOne && !ret.length) {
            throw new errors.NoDataError("query returned no data");
          } else {
            return {
              result: ret[0] ?? (asJson ? "null" : null),
              warnings,
              unsafeIsolationDangers
            };
          }
        } else {
          if (ret && ret.length) {
            if (asJson) {
              return { result: ret[0], warnings, unsafeIsolationDangers };
            } else {
              return { result: ret, warnings, unsafeIsolationDangers };
            }
          } else {
            if (asJson) {
              return { result: "[]", warnings, unsafeIsolationDangers };
            } else {
              return { result: ret, warnings, unsafeIsolationDangers };
            }
          }
        }
      }
      getQueryCapabilities(query, outputFormat, expectedCardinality) {
        var _a2;
        const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
        return ((_a2 = this.queryCodecCache.get(key)) == null ? void 0 : _a2[3]) ?? null;
      }
      async resetState() {
        if (this.connected && this.serverXactStatus !== TransactionStatus.TRANS_IDLE) {
          try {
            await this.fetch(`rollback`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, options_1.Options.defaults(), true);
          } catch {
            this._abortWithError(new errors.ClientConnectionClosedError("failed to reset state"));
          }
        }
      }
      _abort() {
        this.connected = false;
        this._abortWaiters(this.getConnAbortError());
        if (!this.connAbortWaiter.done) {
          this.connAbortWaiter.set();
        }
      }
      isClosed() {
        return !this.connected;
      }
      async close() {
        this._abort();
      }
    };
    exports2.BaseRawConnection = BaseRawConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js
var require_scram = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.saslprep = saslprep;
    exports2.getSCRAM = getSCRAM;
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var RAW_NONCE_LENGTH = 18;
    function saslprep(str) {
      return str.normalize("NFKC");
    }
    function getSCRAM({ randomBytes, H: H2, HMAC, makeKey }) {
      function bufferEquals(a3, b3) {
        if (a3.length !== b3.length) {
          return false;
        }
        for (let i4 = 0, len = a3.length; i4 < len; i4++) {
          if (a3[i4] !== b3[i4]) {
            return false;
          }
        }
        return true;
      }
      function generateNonce(length = RAW_NONCE_LENGTH) {
        return randomBytes(length);
      }
      function buildClientFirstMessage(clientNonce, username) {
        const bare = `n=${saslprep(username)},r=${(0, buffer_1.encodeB64)(clientNonce)}`;
        return [`n,,${bare}`, bare];
      }
      function parseServerFirstMessage(msg) {
        const attrs = msg.split(",");
        if (attrs.length < 3) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceAttr = attrs[0];
        if (!nonceAttr || nonceAttr[0] !== "r") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceB64 = nonceAttr.split("=", 2)[1];
        if (!nonceB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonce = (0, buffer_1.decodeB64)(nonceB64);
        const saltAttr = attrs[1];
        if (!saltAttr || saltAttr[0] !== "s") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const saltB64 = saltAttr.split("=", 2)[1];
        if (!saltB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const salt = (0, buffer_1.decodeB64)(saltB64);
        const iterAttr = attrs[2];
        if (!iterAttr || iterAttr[0] !== "i") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const iter = iterAttr.split("=", 2)[1];
        if (!iter || !iter.match(/^[0-9]*$/)) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const iterCount = parseInt(iter, 10);
        if (iterCount <= 0) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        return [nonce, salt, iterCount];
      }
      function parseServerFinalMessage(msg) {
        const attrs = msg.split(",");
        if (attrs.length < 1) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceAttr = attrs[0];
        if (!nonceAttr || nonceAttr[0] !== "v") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const signatureB64 = nonceAttr.split("=", 2)[1];
        if (!signatureB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        return (0, buffer_1.decodeB64)(signatureB64);
      }
      async function buildClientFinalMessage(password, salt, iterations, clientFirstBare, serverFirst, serverNonce) {
        const clientFinal = `c=biws,r=${(0, buffer_1.encodeB64)(serverNonce)}`;
        const authMessage = buffer_1.utf8Encoder.encode(`${clientFirstBare},${serverFirst},${clientFinal}`);
        const saltedPassword = await _getSaltedPassword(buffer_1.utf8Encoder.encode(saslprep(password)), salt, iterations);
        const clientKey = await _getClientKey(saltedPassword);
        const storedKey = await H2(clientKey);
        const clientSignature = await HMAC(storedKey, authMessage);
        const clientProof = _XOR(clientKey, clientSignature);
        const serverKey = await _getServerKey(saltedPassword);
        const serverProof = await HMAC(serverKey, authMessage);
        return [`${clientFinal},p=${(0, buffer_1.encodeB64)(clientProof)}`, serverProof];
      }
      async function _getSaltedPassword(password, salt, iterations) {
        const msg = new Uint8Array(salt.length + 4);
        msg.set(salt);
        msg.set([0, 0, 0, 1], salt.length);
        const keyFromPassword = await makeKey(password);
        let Hi = await HMAC(keyFromPassword, msg);
        let Ui = Hi;
        for (let _3 = 0; _3 < iterations - 1; _3++) {
          Ui = await HMAC(keyFromPassword, Ui);
          Hi = _XOR(Hi, Ui);
        }
        return Hi;
      }
      function _getClientKey(saltedPassword) {
        return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Client Key"));
      }
      function _getServerKey(saltedPassword) {
        return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Server Key"));
      }
      function _XOR(a3, b3) {
        const len = a3.length;
        if (len !== b3.length) {
          throw new errors_1.ProtocolError("scram.XOR: buffers are of different lengths");
        }
        const res = new Uint8Array(len);
        for (let i4 = 0; i4 < len; i4++) {
          res[i4] = a3[i4] ^ b3[i4];
        }
        return res;
      }
      return {
        bufferEquals,
        generateNonce,
        buildClientFirstMessage,
        parseServerFirstMessage,
        parseServerFinalMessage,
        buildClientFinalMessage,
        _getSaltedPassword,
        _getClientKey,
        _getServerKey,
        _XOR
      };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js
var require_browserCrypto = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.cryptoUtils = void 0;
    async function makeKey(key) {
      return await crypto.subtle.importKey("raw", key, {
        name: "HMAC",
        hash: { name: "SHA-256" }
      }, false, ["sign"]);
    }
    function randomBytes(size) {
      return crypto.getRandomValues(new Uint8Array(size));
    }
    async function H2(msg) {
      return new Uint8Array(await crypto.subtle.digest("SHA-256", msg));
    }
    async function HMAC(key, msg) {
      const cryptoKey = key instanceof Uint8Array ? await makeKey(key) : key;
      return new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg));
    }
    exports2.cryptoUtils = {
      makeKey,
      randomBytes,
      H: H2,
      HMAC
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js
var require_nodeCrypto = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.cryptoUtils = void 0;
    var node_crypto_1 = __importDefault2(require("node:crypto"));
    function makeKey(keyBytes) {
      return Promise.resolve(keyBytes);
    }
    function randomBytes(size) {
      return node_crypto_1.default.randomBytes(size);
    }
    async function H2(msg) {
      const sign = node_crypto_1.default.createHash("sha256");
      sign.update(msg);
      return sign.digest();
    }
    async function HMAC(key, msg) {
      const cryptoKey = key instanceof Uint8Array ? key : node_crypto_1.default.KeyObject.from(key);
      const hm = node_crypto_1.default.createHmac("sha256", cryptoKey);
      hm.update(msg);
      return hm.digest();
    }
    exports2.cryptoUtils = {
      makeKey,
      randomBytes,
      H: H2,
      HMAC
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js
var require_cryptoUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var browserCrypto_1 = require_browserCrypto();
    var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
    var cryptoUtils;
    function loadCrypto() {
      if (isNode) {
        try {
          require("node:crypto");
          cryptoUtils = require_nodeCrypto().cryptoUtils;
        } catch (_3) {
          if (typeof globalThis.crypto !== "undefined") {
            cryptoUtils = browserCrypto_1.cryptoUtils;
          } else {
            throw new Error("No crypto implementation found");
          }
        }
      } else {
        cryptoUtils = browserCrypto_1.cryptoUtils;
      }
    }
    loadCrypto();
    exports2.default = cryptoUtils;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js
var require_rawConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RawConnection = void 0;
    var node_net_1 = __importDefault2(require("node:net"));
    var tls = __importStar2(require("node:tls"));
    var baseConn_1 = require_baseConn();
    var utils_1 = require_utils2();
    var buffer_1 = require_buffer();
    var event_1 = __importDefault2(require_event());
    var chars = __importStar2(require_chars());
    var scram_1 = require_scram();
    var errors = __importStar2(require_errors());
    var cryptoUtils_1 = __importDefault2(require_cryptoUtils());
    var AuthenticationStatuses;
    (function(AuthenticationStatuses2) {
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_OK"] = 0] = "AUTH_OK";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL"] = 10] = "AUTH_SASL";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_CONTINUE"] = 11] = "AUTH_SASL_CONTINUE";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_FINAL"] = 12] = "AUTH_SASL_FINAL";
    })(AuthenticationStatuses || (AuthenticationStatuses = {}));
    var scram = (0, scram_1.getSCRAM)(cryptoUtils_1.default);
    var _tlsOptions = /* @__PURE__ */ new WeakMap();
    function getTlsOptions(config) {
      if (_tlsOptions.has(config)) {
        return _tlsOptions.get(config);
      }
      const tlsSecurity = config.tlsSecurity;
      const tlsOptions = {
        ALPNProtocols: ["edgedb-binary"],
        rejectUnauthorized: tlsSecurity !== "insecure"
      };
      const isIPAddress = node_net_1.default.isIP(config.address[0]) !== 0;
      if (!isIPAddress) {
        tlsOptions.servername = config.tlsServerName || config.address[0];
      }
      _tlsOptions.set(config, tlsOptions);
      if (config._tlsCAData !== null) {
        tlsOptions.ca = config._tlsCAData;
      }
      if (tlsSecurity === "no_host_verification") {
        tlsOptions.checkServerIdentity = (hostname, cert) => {
          const err2 = tls.checkServerIdentity(hostname, cert);
          if (err2 === void 0) {
            return void 0;
          }
          if (err2.message.startsWith("Hostname/IP does not match certificate")) {
            return void 0;
          }
          return err2;
        };
      }
      return tlsOptions;
    }
    var RawConnection = class extends baseConn_1.BaseRawConnection {
      config;
      sock;
      paused;
      constructor(sock, config, registry) {
        super(registry);
        this.config = config;
        this.paused = false;
        this.sock = sock;
        this.sock.setNoDelay();
        this.sock.on("error", this._onError.bind(this));
        this.sock.on("data", this._onData.bind(this));
        if (tls.TLSSocket && this.sock instanceof tls.TLSSocket) {
          this.sock.on("secureConnect", this._onConnect.bind(this));
        } else {
          this.sock.on("connect", this._onConnect.bind(this));
        }
        this.sock.on("close", this._onClose.bind(this));
      }
      _onConnect() {
        this.connWaiter.set();
      }
      _onClose() {
        if (!this.connected) {
          return;
        }
        const newErr = new errors.ClientConnectionClosedError(`the connection has been aborted`);
        if (!this.connWaiter.done || this.messageWaiter) {
          this._abortWaiters(newErr);
        }
        if (this.buffer.takeMessage() && this.buffer.getMessageType() === chars.$E) {
          Object.defineProperty(newErr, "cause", {
            enumerable: false,
            value: this._parseErrorMessage()
          });
        }
        this._abortWithError(newErr);
      }
      _onError(err2) {
        const newErr = new errors.ClientConnectionClosedError(`network error: ${err2}`, { cause: err2 });
        try {
          this._abortWaiters(newErr);
        } finally {
          this._abortWithError(newErr);
        }
      }
      _onData(data) {
        try {
          this.buffer.feed(data);
        } catch (e4) {
          if (this.messageWaiter) {
            this.messageWaiter.setError(e4);
            this.messageWaiter = null;
          }
          this._abortWithError(e4);
        }
        if (this.messageWaiter) {
          if (this.buffer.takeMessage()) {
            this.messageWaiter.set();
            this.messageWaiter = null;
          }
        }
      }
      async _waitForMessage() {
        if (this.buffer.takeMessage()) {
          return;
        }
        if (this.paused) {
          this.paused = false;
          this.sock.resume();
        }
        this.sock.ref();
        this.messageWaiter = new event_1.default();
        try {
          await this.messageWaiter.wait();
        } finally {
          this.sock.unref();
        }
      }
      _sendData(data) {
        this.sock.write(data);
      }
      static newSock(addr, options) {
        if (typeof addr === "string") {
          return node_net_1.default.createConnection(addr);
        }
        const [host, port] = addr;
        if (options == null) {
          return node_net_1.default.createConnection(port, host);
        }
        const opts = { ...options, host, port };
        return tls.connect(opts);
      }
      _abort() {
        if (this.sock && this.connected) {
          this.sock.destroy();
        }
        super._abort();
      }
      async close() {
        if (this.sock && this.connected) {
          this.sock.write(new buffer_1.WriteMessageBuffer().beginMessage(chars.$X).endMessage().unwrap());
        }
        return await super.close();
      }
      static async connectWithTimeout(config, registry, useTls = true) {
        const sock = this.newSock(config.connectionParams.address, useTls ? getTlsOptions(config.connectionParams) : void 0);
        const conn = new this(sock, config, registry);
        const connPromise = conn.connect();
        let timeoutCb = null;
        let timeoutHappened = false;
        if (config.connectTimeout) {
          timeoutCb = setTimeout(() => {
            if (!conn.connected) {
              timeoutHappened = true;
              conn.sock.destroy(new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`));
            }
          }, config.connectTimeout);
        }
        try {
          await connPromise;
        } catch (e4) {
          conn._abort();
          if (timeoutHappened && e4 instanceof errors.ClientConnectionClosedError) {
            throw new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`);
          }
          if (e4 instanceof errors.GelError) {
            throw e4;
          } else {
            let err2;
            switch (e4.code) {
              case "EPROTO":
                if (useTls === true) {
                  try {
                    return this.connectWithTimeout(config, registry, false);
                  } catch {
                  }
                }
                err2 = new errors.ClientConnectionFailedError(`${e4.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e4 });
                break;
              case "ECONNREFUSED":
              case "ECONNABORTED":
              case "ECONNRESET":
              case "ENOTFOUND":
              case "ENOENT":
                err2 = new errors.ClientConnectionFailedTemporarilyError(`${e4.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e4 });
                break;
              default:
                err2 = new errors.ClientConnectionFailedError(`${e4.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e4 });
                break;
            }
            throw err2;
          }
        } finally {
          if (timeoutCb != null) {
            clearTimeout(timeoutCb);
          }
        }
        return conn;
      }
      async connect() {
        await this.connWaiter.wait();
        if (this.sock instanceof tls.TLSSocket) {
          if (this.sock.alpnProtocol !== "edgedb-binary") {
            throw new errors.ClientConnectionFailedError("The server doesn't support the edgedb-binary protocol.");
          }
        }
        const handshake = new buffer_1.WriteMessageBuffer();
        handshake.beginMessage(chars.$V).writeInt16(this.protocolVersion[0]).writeInt16(this.protocolVersion[1]);
        const clientHandshakeOptions = {
          user: this.config.connectionParams.user,
          database: this.config.connectionParams.database
        };
        if (this.config.connectionParams.secretKey != null) {
          clientHandshakeOptions.secret_key = this.config.connectionParams.secretKey;
        }
        handshake.writeInt16(Object.keys(clientHandshakeOptions).length);
        for (const [key, value] of Object.entries(clientHandshakeOptions)) {
          handshake.writeString(key).writeString(value);
        }
        handshake.writeInt16(0);
        handshake.endMessage();
        this.sock.write(handshake.unwrap());
        while (true) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$v: {
              const hi = this.buffer.readInt16();
              const lo = this.buffer.readInt16();
              this._parseHeaders();
              this.buffer.finishMessage();
              const proposed = [hi, lo];
              if ((0, utils_1.versionGreaterThan)(proposed, baseConn_1.PROTO_VER) || (0, utils_1.versionGreaterThan)(baseConn_1.PROTO_VER_MIN, proposed)) {
                throw new errors.UnsupportedProtocolVersionError(`the server requested an unsupported version of the protocol ${hi}.${lo}`);
              }
              this.protocolVersion = [hi, lo];
              break;
            }
            case chars.$R: {
              const status = this.buffer.readInt32();
              if (status === AuthenticationStatuses.AUTH_OK) {
                this.buffer.finishMessage();
              } else if (status === AuthenticationStatuses.AUTH_SASL) {
                await this._authSasl();
              } else {
                throw new errors.ProtocolError(`unsupported authentication method requested by the server: ${status}`);
              }
              break;
            }
            case chars.$K: {
              this.serverSecret = this.buffer.readBuffer(32);
              this.buffer.finishMessage();
              break;
            }
            case chars.$E: {
              throw this._parseErrorMessage();
            }
            case chars.$s: {
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              if (!(this.sock instanceof tls.TLSSocket) && typeof Deno === "undefined") {
                const [major, minor] = this.protocolVersion;
                throw new errors.ProtocolError(`the protocol version requires TLS: ${major}.${minor}`);
              }
              this.connected = true;
              return;
            }
            default:
              this._fallthrough();
          }
        }
      }
      async _authSasl() {
        const numMethods = this.buffer.readInt32();
        if (numMethods <= 0) {
          throw new errors.ProtocolError("the server requested SASL authentication but did not offer any methods");
        }
        const methods = [];
        let foundScram256 = false;
        for (let _3 = 0; _3 < numMethods; _3++) {
          const method = this.buffer.readString();
          if (method === "SCRAM-SHA-256") {
            foundScram256 = true;
          }
          methods.push(method);
        }
        this.buffer.finishMessage();
        if (!foundScram256) {
          throw new errors.ProtocolError(`the server offered the following SASL authentication methods: ${methods.join(", ")}, neither are supported.`);
        }
        const clientNonce = scram.generateNonce();
        const [clientFirst, clientFirstBare] = scram.buildClientFirstMessage(clientNonce, this.config.connectionParams.user);
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$p).writeString("SCRAM-SHA-256").writeString(clientFirst).endMessage();
        this.sock.write(wb.unwrap());
        await this._ensureMessage(chars.$R, "SASLContinue");
        let status = this.buffer.readInt32();
        if (status !== AuthenticationStatuses.AUTH_SASL_CONTINUE) {
          throw new errors.ProtocolError(`expected SASLContinue from the server, received ${status}`);
        }
        const serverFirst = this.buffer.readString();
        this.buffer.finishMessage();
        const [serverNonce, salt, itercount] = scram.parseServerFirstMessage(serverFirst);
        const [clientFinal, expectedServerSig] = await scram.buildClientFinalMessage(this.config.connectionParams.password || "", salt, itercount, clientFirstBare, serverFirst, serverNonce);
        wb.reset().beginMessage(chars.$r).writeString(clientFinal).endMessage();
        this.sock.write(wb.unwrap());
        await this._ensureMessage(chars.$R, "SASLFinal");
        status = this.buffer.readInt32();
        if (status !== AuthenticationStatuses.AUTH_SASL_FINAL) {
          throw new errors.ProtocolError(`expected SASLFinal from the server, received ${status}`);
        }
        const serverFinal = this.buffer.readString();
        this.buffer.finishMessage();
        const serverSig = scram.parseServerFinalMessage(serverFinal);
        if (!scram.bufferEquals(serverSig, expectedServerSig)) {
          throw new errors.ProtocolError("server SCRAM proof does not match");
        }
      }
      async _ensureMessage(expectedMtype, err2) {
        if (!this.buffer.takeMessage()) {
          await this._waitForMessage();
        }
        const mtype = this.buffer.getMessageType();
        switch (mtype) {
          case chars.$E: {
            throw this._parseErrorMessage();
          }
          case expectedMtype: {
            return;
          }
          default: {
            throw new errors.UnexpectedMessageError(`expected ${err2} from the server, received ${chars.chr(mtype)}`);
          }
        }
      }
    };
    exports2.RawConnection = RawConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js
var require_fetchConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FetchConnection = exports2.AdminUIFetchConnection = void 0;
    var baseConn_1 = require_baseConn();
    var codecs_1 = require_codecs();
    var errors_1 = require_errors();
    var ifaces_1 = require_ifaces2();
    var buffer_1 = require_buffer();
    var chars = __importStar2(require_chars());
    var event_1 = __importDefault2(require_event());
    var utils_1 = require_utils2();
    var PROTO_MIME = `application/x.edgedb.v_${baseConn_1.PROTO_VER[0]}_${baseConn_1.PROTO_VER[1]}.binary'`;
    var PROTO_MIME_RE = /application\/x\.edgedb\.v_(\d+)_(\d+)\.binary/;
    var STUDIO_CAPABILITIES = (baseConn_1.RESTRICTED_CAPABILITIES | baseConn_1.Capabilities.SESSION_CONFIG | baseConn_1.Capabilities.SET_GLOBAL) >>> 0;
    var BaseFetchConnection = class extends baseConn_1.BaseRawConnection {
      authenticatedFetch;
      abortSignal = null;
      constructor(fetch3, registry) {
        super(registry);
        this.authenticatedFetch = fetch3;
      }
      async _waitForMessage() {
        if (this.buffer.takeMessage()) {
          return;
        }
        if (this.messageWaiter == null || this.messageWaiter.done) {
          throw new errors_1.InternalClientError(`message waiter was not initialized before waiting for response`);
        }
        await this.messageWaiter.wait();
      }
      async __sendData(data) {
        if (this.buffer.takeMessage()) {
          const mtype = this.buffer.getMessageType();
          throw new errors_1.InternalClientError(`sending request before reading all data of the previous one: ${chars.chr(mtype)}`);
        }
        if (this.messageWaiter != null && !this.messageWaiter.done) {
          throw new errors_1.InternalClientError(`sending request before waiting for completion of the previous one`);
        }
        this.messageWaiter = new event_1.default();
        try {
          const resp = await this.authenticatedFetch("", {
            method: "post",
            body: data,
            headers: {
              "Content-Type": PROTO_MIME
            },
            signal: this.abortSignal
          });
          if (!resp.ok) {
            throw new errors_1.ProtocolError(`fetch failed with status code ${resp.status}: ${resp.statusText}`);
          }
          const contentType = resp.headers.get("content-type");
          const matchProtoVer = contentType == null ? void 0 : contentType.match(PROTO_MIME_RE);
          if (matchProtoVer) {
            this.protocolVersion = [+matchProtoVer[1], +matchProtoVer[2]];
          }
          const respData = await resp.arrayBuffer();
          const buf = new Uint8Array(respData);
          try {
            this.buffer.feed(buf);
          } catch (e4) {
            this.messageWaiter.setError(e4);
          }
          if (!this.buffer.takeMessage()) {
            throw new errors_1.ProtocolError("no binary protocol messages in the response");
          }
          this.messageWaiter.set();
        } catch (e4) {
          this.messageWaiter.setError(e4);
        } finally {
          this.messageWaiter = null;
        }
      }
      _sendData(data) {
        this.__sendData(data);
      }
      async fetch(...args) {
        const protoVer = this.protocolVersion;
        try {
          return await super.fetch(...args);
        } catch (err2) {
          if (err2 instanceof errors_1.BinaryProtocolError && !(0, utils_1.versionEqual)(protoVer, this.protocolVersion)) {
            return await super.fetch(...args);
          }
          throw err2;
        }
      }
      static create(fetch3, registry) {
        const conn = new this(fetch3, registry);
        conn.connected = true;
        conn.connWaiter.set();
        return conn;
      }
    };
    var AdminUIFetchConnection = class extends BaseFetchConnection {
      adminUIMode = true;
      static create(fetch3, registry, knownServerVersion) {
        const conn = super.create(fetch3, registry);
        if (knownServerVersion && knownServerVersion[0] < 6) {
          conn.protocolVersion = [2, 0];
        }
        return conn;
      }
      async rawParse(language, query, state2, options, abortSignal) {
        this.abortSignal = abortSignal ?? null;
        const result = await this._parse(language, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, state2, STUDIO_CAPABILITIES, options);
        return [this.protocolVersion, ...result];
      }
      async rawExecute(language, query, state2, outCodec, options, inCodec, args = null, abortSignal) {
        this.abortSignal = abortSignal ?? null;
        const result = new buffer_1.WriteBuffer();
        const [warnings] = await this._executeFlow(language, query, args, outCodec ? ifaces_1.OutputFormat.BINARY : ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.MANY, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, result, STUDIO_CAPABILITIES, options);
        return [result.unwrap(), warnings];
      }
    };
    exports2.AdminUIFetchConnection = AdminUIFetchConnection;
    var FetchConnection = class _FetchConnection extends BaseFetchConnection {
      static createConnectWithTimeout(httpSCRAMAuth) {
        return async function connectWithTimeout(config, registry) {
          const fetch3 = await (0, utils_1.getAuthenticatedFetch)(config.connectionParams, httpSCRAMAuth);
          const conn = new _FetchConnection(fetch3, registry);
          conn.connected = true;
          conn.connWaiter.set();
          return conn;
        };
      }
    };
    exports2.FetchConnection = FetchConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js
var require_httpScram = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getHTTPSCRAMAuth = getHTTPSCRAMAuth;
    var errors_1 = require_errors();
    var buffer_1 = require_buffer();
    var scram_1 = require_scram();
    var AUTH_ENDPOINT = "/auth/token";
    function getHTTPSCRAMAuth(cryptoUtils) {
      const { bufferEquals, generateNonce, buildClientFirstMessage, buildClientFinalMessage, parseServerFirstMessage, parseServerFinalMessage } = (0, scram_1.getSCRAM)(cryptoUtils);
      return async function HTTPSCRAMAuth(baseUrl, username, password) {
        const authUrl = baseUrl + AUTH_ENDPOINT;
        const clientNonce = generateNonce();
        const [clientFirst, clientFirstBare] = buildClientFirstMessage(clientNonce, username);
        const serverFirstRes = await fetch(authUrl, {
          headers: {
            Authorization: `SCRAM-SHA-256 data=${utf8ToB64(clientFirst)}`
          }
        });
        const authenticateHeader = serverFirstRes.headers.get("WWW-Authenticate");
        if (serverFirstRes.status !== 401 || !authenticateHeader) {
          const body = await serverFirstRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        if (!authenticateHeader.startsWith("SCRAM-SHA-256")) {
          throw new errors_1.ProtocolError(`unsupported authentication scheme: ${authenticateHeader}`);
        }
        const authParams = authenticateHeader.split(/ (.+)?/, 2)[1] ?? "";
        if (authParams.length === 0) {
          const body = await serverFirstRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        const { sid, data: serverFirst } = parseScramAttrs(authParams);
        if (!sid || !serverFirst) {
          throw new errors_1.ProtocolError(`authentication challenge missing attributes: expected "sid" and "data", got '${authParams}'`);
        }
        const [serverNonce, salt, iterCount] = parseServerFirstMessage(serverFirst);
        const [clientFinal, expectedServerSig] = await buildClientFinalMessage(password, salt, iterCount, clientFirstBare, serverFirst, serverNonce);
        const serverFinalRes = await fetch(authUrl, {
          headers: {
            Authorization: `SCRAM-SHA-256 sid=${sid}, data=${utf8ToB64(clientFinal)}`
          }
        });
        const authInfoHeader = serverFinalRes.headers.get("Authentication-Info");
        if (!serverFinalRes.ok || !authInfoHeader) {
          const body = await serverFinalRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        const { data: serverFinal, sid: sidFinal } = parseScramAttrs(authInfoHeader);
        if (!sidFinal || !serverFinal) {
          throw new errors_1.ProtocolError(`authentication info missing attributes: expected "sid" and "data", got '${authInfoHeader}'`);
        }
        if (sidFinal !== sid) {
          throw new errors_1.ProtocolError("SCRAM session id does not match");
        }
        const serverSig = parseServerFinalMessage(serverFinal);
        if (!bufferEquals(serverSig, expectedServerSig)) {
          throw new errors_1.ProtocolError("server SCRAM proof does not match");
        }
        const authToken = await serverFinalRes.text();
        return authToken;
      };
    }
    function utf8ToB64(str) {
      return (0, buffer_1.encodeB64)(buffer_1.utf8Encoder.encode(str));
    }
    function b64ToUtf8(str) {
      return buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(str));
    }
    function parseScramAttrs(paramsStr) {
      const params = new Map(paramsStr.length > 0 ? paramsStr.split(",").map((attr) => attr.split(/=(.+)?/, 2)).map(([key, val2]) => [key.trim(), val2.trim()]) : []);
      const sid = params.get("sid") ?? null;
      const rawData = params.get("data");
      const data = rawData ? b64ToUtf8(rawData) : null;
      return { sid, data };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js
var require_nodeClient = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createClient = createClient;
    exports2.createHttpClient = createHttpClient;
    var baseClient_1 = require_baseClient();
    var conUtils_server_1 = require_conUtils_server();
    var options_1 = require_options();
    var rawConn_1 = require_rawConn();
    var fetchConn_1 = require_fetchConn();
    var httpScram_1 = require_httpScram();
    var cryptoUtils_1 = __importDefault2(require_cryptoUtils());
    var ClientPool = class extends baseClient_1.BaseClientPool {
      isStateless = false;
      _connectWithTimeout = rawConn_1.RawConnection.connectWithTimeout.bind(rawConn_1.RawConnection);
    };
    function createClient(options) {
      return new baseClient_1.Client(new ClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
    }
    var httpSCRAMAuth = (0, httpScram_1.getHTTPSCRAMAuth)(cryptoUtils_1.default);
    var FetchClientPool = class extends baseClient_1.BaseClientPool {
      isStateless = true;
      _connectWithTimeout = fetchConn_1.FetchConnection.createConnectWithTimeout(httpSCRAMAuth);
    };
    function createHttpClient(options) {
      return new baseClient_1.Client(new FetchClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js
var require_wkt = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseWKT = parseWKT;
    var postgis_1 = require_postgis();
    var sridRegex = /\s*SRID=([0-9]+)\s*;/iy;
    var endRegex = /\s*$/y;
    var geomTypes = [
      "POINT",
      "LINESTRING",
      "POLYGON",
      "MULTIPOINT",
      "MULTILINESTRING",
      "MULTIPOLYGON",
      "GEOMETRYCOLLECTION",
      "POLYHEDRALSURFACE",
      "TRIANGLE",
      "TIN",
      "CIRCULARSTRING",
      "COMPOUNDCURVE",
      "CURVEPOLYGON",
      "MULTICURVE",
      "MULTISURFACE"
    ];
    var geomTypeRegex = new RegExp(`\\s*(${geomTypes.join("|")})`, "iy");
    var zmFlagsRegex = /\s+(ZM|Z|M)/iy;
    var emptyOrOpenRegex = /\s+(EMPTY)|\s*\(/iy;
    var openRegex = /\s*\(/y;
    var closeRegex = /\s*\)/y;
    var commaRegex = /\s*,/y;
    var _num = "-?[0-9]+(?:\\.[0-9]+)?";
    var pointRegex = new RegExp(`\\s*(${_num})\\s+(${_num})(?:\\s+(${_num}))?(?:\\s+(${_num}))?`, "y");
    function parseWKT(wkt) {
      let i4 = 0;
      let hasZ = null;
      let hasM = null;
      let srid = null;
      sridRegex.lastIndex = i4;
      const _srid = sridRegex.exec(wkt);
      if (_srid) {
        srid = parseInt(_srid[1], 10);
        i4 += _srid[0].length;
      }
      const geom = _parseGeom();
      endRegex.lastIndex = i4;
      if (endRegex.exec(wkt) === null) {
        throw createParseError(wkt, i4, "expected end of wkt");
      }
      return geom;
      function _parseGeom(unnamedGeom = null, allowedGeoms = null) {
        geomTypeRegex.lastIndex = i4;
        const _geomType = geomTypeRegex.exec(wkt);
        const type = (_geomType == null ? void 0 : _geomType[1].toUpperCase()) ?? unnamedGeom;
        if (!type || allowedGeoms && !allowedGeoms.includes(type)) {
          throw createParseError(wkt, i4, `expected one of ${(allowedGeoms ? ["(", ...allowedGeoms] : geomTypes).join(", ")}`);
        }
        i4 += (_geomType == null ? void 0 : _geomType[0].length) ?? 0;
        if (_geomType !== null) {
          zmFlagsRegex.lastIndex = i4;
          const _zmFlags = zmFlagsRegex.exec(wkt);
          if (_zmFlags !== null) {
            const zm = _zmFlags[1].toLowerCase();
            hasZ = zm === "zm" || zm === "z";
            hasM = zm === "zm" || zm === "m";
            i4 += _zmFlags[0].length;
          } else {
            hasZ = null;
            hasM = null;
          }
        }
        const open = _geomType === null ? openRegex : emptyOrOpenRegex;
        open.lastIndex = i4;
        const _emptyOrOpen = open.exec(wkt);
        if (_emptyOrOpen === null) {
          throw createParseError(wkt, i4, _geomType === null ? `expected (` : `expected EMPTY or (`);
        }
        i4 += _emptyOrOpen[0].length;
        const empty = _emptyOrOpen[1] != null;
        let geom2;
        switch (type) {
          case "POINT":
            geom2 = _parsePoint(empty);
            break;
          case "LINESTRING":
          case "CIRCULARSTRING":
            geom2 = _parseLineString(empty, type === "CIRCULARSTRING" ? postgis_1.CircularString : postgis_1.LineString);
            break;
          case "POLYGON":
          case "TRIANGLE":
            geom2 = _parsePolygon(empty, type === "TRIANGLE" ? postgis_1.Triangle : postgis_1.Polygon);
            break;
          case "MULTIPOINT":
            geom2 = new postgis_1.MultiPoint(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parsePoint)), hasZ ?? false, hasM ?? false, srid);
            break;
          case "MULTILINESTRING":
            geom2 = new postgis_1.MultiLineString(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
            break;
          case "MULTIPOLYGON":
          case "POLYHEDRALSURFACE":
          case "TIN":
            {
              const Geom = type === "TIN" ? postgis_1.TriangulatedIrregularNetwork : type === "POLYHEDRALSURFACE" ? postgis_1.PolyhedralSurface : postgis_1.MultiPolygon;
              geom2 = new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(() => _parsePolygon(false, type === "TIN" ? postgis_1.Triangle : postgis_1.Polygon))), hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "GEOMETRYCOLLECTION": {
            geom2 = new postgis_1.GeometryCollection(empty ? [] : _checkDimensions(() => _parseCommaSep(_parseGeom)), hasZ ?? false, hasM ?? false, srid);
            break;
          }
          case "COMPOUNDCURVE":
            {
              const segments = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", ["LINESTRING", "CIRCULARSTRING"])));
              geom2 = new postgis_1.CompoundCurve(segments, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "CURVEPOLYGON":
          case "MULTICURVE":
            {
              const rings = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", [
                "LINESTRING",
                "CIRCULARSTRING",
                "COMPOUNDCURVE"
              ])));
              const Geom = type === "MULTICURVE" ? postgis_1.MultiCurve : postgis_1.CurvePolygon;
              geom2 = new Geom(rings, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "MULTISURFACE":
            {
              const surfaces = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("POLYGON", ["POLYGON", "CURVEPOLYGON"])));
              geom2 = new postgis_1.MultiSurface(surfaces, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          default:
            assertNever(type, `unknown geometry type ${type}`);
        }
        if (!empty) {
          closeRegex.lastIndex = i4;
          const _close = closeRegex.exec(wkt);
          if (_close === null) {
            throw createParseError(wkt, i4, `expected )`);
          }
          i4 += _close[0].length;
        }
        return geom2;
      }
      function _parsePoint(empty = false) {
        if (empty) {
          return new postgis_1.Point(NaN, NaN, hasZ ? NaN : null, hasM ? NaN : null, srid);
        }
        pointRegex.lastIndex = i4;
        const coords = pointRegex.exec(wkt);
        if (coords === null) {
          throw createParseError(wkt, i4, `expected between 2 to 4 coordinates`);
        }
        const x4 = parseFloat(coords[1]);
        const y2 = parseFloat(coords[2]);
        const z2 = coords[3] ? parseFloat(coords[3]) : null;
        const m4 = coords[4] ? parseFloat(coords[4]) : null;
        if (hasZ === null) {
          hasZ = z2 !== null;
          hasM = m4 !== null;
        } else {
          if (m4 === null) {
            if (hasZ && hasM) {
              throw createParseError(wkt, i4, `expected M coordinate`);
            }
          } else {
            if (!hasM) {
              throw createParseError(wkt, i4, `unexpected M coordinate`);
            }
          }
          if (z2 === null) {
            if (hasZ || hasM) {
              throw createParseError(wkt, i4, `expected ${hasZ ? "Z" : "M"} coordinate`);
            }
          } else {
            if (!hasZ && (!hasM || m4 !== null)) {
              throw createParseError(wkt, i4, `unexpected Z coordinate`);
            }
          }
        }
        i4 += coords[0].length;
        return new postgis_1.Point(x4, y2, hasZ ? z2 : null, hasZ ? m4 : z2, srid);
      }
      function _parseLineString(empty = false, Geom = postgis_1.LineString) {
        return new Geom(empty ? [] : _parseCommaSep(_parsePoint), hasZ ?? false, hasM ?? false, srid);
      }
      function _parsePolygon(empty = false, Geom = postgis_1.Polygon) {
        return new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
      }
      function _parseCommaSep(parseGeom) {
        const geoms = [parseGeom()];
        while (true) {
          commaRegex.lastIndex = i4;
          const comma = commaRegex.exec(wkt);
          if (comma === null) {
            break;
          }
          i4 += comma[0].length;
          geoms.push(parseGeom());
        }
        return geoms;
      }
      function _parseBracketedGeom(parseGeom) {
        openRegex.lastIndex = i4;
        const open = openRegex.exec(wkt);
        if (open === null) {
          throw createParseError(wkt, i4, `expected (`);
        }
        i4 += open[0].length;
        const geom2 = parseGeom();
        closeRegex.lastIndex = i4;
        const close = closeRegex.exec(wkt);
        if (close === null) {
          throw createParseError(wkt, i4, `expected )`);
        }
        i4 += close[0].length;
        return geom2;
      }
      function _checkDimensions(parseChildren) {
        const parentZ = hasZ;
        const parentM = hasM;
        const geoms = parseChildren();
        hasZ = parentZ ?? geoms[0].hasZ ?? false;
        hasM = parentM ?? geoms[0].hasM ?? false;
        if (geoms.some((geom2) => geom2.hasZ !== hasZ || geom2.hasM !== hasM)) {
          throw createParseError(wkt, i4, `child geometries have mixed dimensions`);
        }
        return geoms;
      }
    }
    function createParseError(_wkt, index6, error2) {
      return new Error(`${error2} at position ${index6}`);
    }
    function assertNever(_type, message) {
      throw new Error(message);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js
var require_index_shared = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
      for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
    };
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._ReadBuffer = exports2._CodecsRegistry = exports2.throwWarnings = exports2.logWarnings = exports2.defaultBackoff = exports2.Options = exports2.RetryOptions = exports2.RetryCondition = exports2.IsolationLevel = exports2.parseWKT = exports2.Float16Array = exports2.SparseVector = exports2.MultiRange = exports2.Range = exports2.ConfigMemory = exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalTime = exports2.LocalDate = exports2.LocalDateTime = void 0;
    var datetime_1 = require_datetime();
    Object.defineProperty(exports2, "LocalDateTime", { enumerable: true, get: function() {
      return datetime_1.LocalDateTime;
    } });
    Object.defineProperty(exports2, "LocalDate", { enumerable: true, get: function() {
      return datetime_1.LocalDate;
    } });
    Object.defineProperty(exports2, "LocalTime", { enumerable: true, get: function() {
      return datetime_1.LocalTime;
    } });
    Object.defineProperty(exports2, "Duration", { enumerable: true, get: function() {
      return datetime_1.Duration;
    } });
    Object.defineProperty(exports2, "RelativeDuration", { enumerable: true, get: function() {
      return datetime_1.RelativeDuration;
    } });
    Object.defineProperty(exports2, "DateDuration", { enumerable: true, get: function() {
      return datetime_1.DateDuration;
    } });
    var memory_1 = require_memory();
    Object.defineProperty(exports2, "ConfigMemory", { enumerable: true, get: function() {
      return memory_1.ConfigMemory;
    } });
    var range_1 = require_range2();
    Object.defineProperty(exports2, "Range", { enumerable: true, get: function() {
      return range_1.Range;
    } });
    Object.defineProperty(exports2, "MultiRange", { enumerable: true, get: function() {
      return range_1.MultiRange;
    } });
    var pgvector_1 = require_pgvector();
    Object.defineProperty(exports2, "SparseVector", { enumerable: true, get: function() {
      return pgvector_1.SparseVector;
    } });
    var utils_1 = require_utils2();
    Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
      return utils_1.Float16Array;
    } });
    __exportStar2(require_postgis(), exports2);
    var wkt_1 = require_wkt();
    Object.defineProperty(exports2, "parseWKT", { enumerable: true, get: function() {
      return wkt_1.parseWKT;
    } });
    var options_1 = require_options();
    Object.defineProperty(exports2, "IsolationLevel", { enumerable: true, get: function() {
      return options_1.IsolationLevel;
    } });
    Object.defineProperty(exports2, "RetryCondition", { enumerable: true, get: function() {
      return options_1.RetryCondition;
    } });
    Object.defineProperty(exports2, "RetryOptions", { enumerable: true, get: function() {
      return options_1.RetryOptions;
    } });
    Object.defineProperty(exports2, "Options", { enumerable: true, get: function() {
      return options_1.Options;
    } });
    Object.defineProperty(exports2, "defaultBackoff", { enumerable: true, get: function() {
      return options_1.defaultBackoff;
    } });
    Object.defineProperty(exports2, "logWarnings", { enumerable: true, get: function() {
      return options_1.logWarnings;
    } });
    Object.defineProperty(exports2, "throwWarnings", { enumerable: true, get: function() {
      return options_1.throwWarnings;
    } });
    __exportStar2(require_errors(), exports2);
    var reg = __importStar2(require_registry());
    var buf = __importStar2(require_buffer());
    exports2._CodecsRegistry = reg.CodecsRegistry;
    exports2._ReadBuffer = buf.ReadBuffer;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js
var require_typeutil = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js
var require_strictMap = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StrictMapSet = exports2.StrictMap = void 0;
    var StrictMap = class extends Map {
      get(key) {
        if (!this.has(key)) {
          throw new Error(`key "${key}" is not found`);
        }
        return super.get(key);
      }
    };
    exports2.StrictMap = StrictMap;
    var StrictMapSet = class extends StrictMap {
      appendAt(key, value) {
        const set = this.has(key) ? this.get(key) : /* @__PURE__ */ new Set();
        set.add(value);
        this.set(key, set);
      }
    };
    exports2.StrictMapSet = StrictMapSet;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js
var require_reservedKeywords = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reservedKeywords = void 0;
    exports2.reservedKeywords = /* @__PURE__ */ new Set([
      "__edgedbsys__",
      "__edgedbtpl__",
      "__source__",
      "__std__",
      "__subject__",
      "__type__",
      "abort",
      "alter",
      "analyze",
      "and",
      "anyarray",
      "anytuple",
      "anytype",
      "anyobject",
      "begin",
      "case",
      "check",
      "commit",
      "configure",
      "create",
      "deallocate",
      "declare",
      "delete",
      "describe",
      "detached",
      "discard",
      "distinct",
      "do",
      "drop",
      "else",
      "empty",
      "end",
      "execute",
      "exists",
      "explain",
      "extending",
      "fetch",
      "filter",
      "for",
      "get",
      "global",
      "grant",
      "group",
      "if",
      "ilike",
      "import",
      "in",
      "insert",
      "introspect",
      "is",
      "like",
      "limit",
      "listen",
      "load",
      "lock",
      "match",
      "module",
      "move",
      "not",
      "notify",
      "offset",
      "optional",
      "or",
      "order",
      "over",
      "partition",
      "policy",
      "populate",
      "prepare",
      "raise",
      "refresh",
      "reindex",
      "release",
      "reset",
      "revoke",
      "rollback",
      "select",
      "set",
      "single",
      "start",
      "typeof",
      "union",
      "update",
      "variadic",
      "when",
      "window",
      "with"
    ]);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js
var require_types = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.typeMapping = void 0;
    exports2.getTypes = getTypes;
    exports2.types = getTypes;
    exports2.topoSort = topoSort;
    exports2.getTypes = getTypes;
    exports2.types = getTypes;
    var strictMap_1 = require_strictMap();
    var numberType2 = {
      id: "00000000-0000-0000-0000-0000000001ff",
      name: "std::number",
      is_abstract: false,
      is_seq: false,
      kind: "scalar",
      enum_values: null,
      material_id: null,
      bases: []
    };
    exports2.typeMapping = /* @__PURE__ */ new Map([
      [
        "00000000-0000-0000-0000-000000000103",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000104",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000105",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000106",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000107",
        numberType2
      ]
    ]);
    async function getTypes(cxn, params) {
      var _a2, _b, _c, _d;
      const debug = (params == null ? void 0 : params.debug) === true;
      const version3 = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
      const v2Plus = version3 >= 2;
      const v4Plus = version3 >= 4;
      const QUERY = `
    WITH
      MODULE schema,

      material_scalars := (
        SELECT ScalarType
        FILTER NOT .abstract
           AND NOT EXISTS .enum_values
           AND NOT EXISTS (SELECT .ancestors FILTER NOT .abstract)
      )

    SELECT Type {
      id,
      name :=
        array_join(array_agg([IS ObjectType].union_of.name), ' | ')
        IF EXISTS [IS ObjectType].union_of
        ELSE .name,
      is_abstract := .abstract,

      kind := 'object' IF Type IS ObjectType ELSE
              'scalar' IF Type IS ScalarType ELSE
              'array' IF Type IS Array ELSE
              'tuple' IF Type IS Tuple ELSE
              ${v2Plus ? `'range' IF Type IS Range ELSE` : ``}
              ${v4Plus ? `'multirange' IF Type IS MultiRange ELSE` : ``}
              'unknown',

      [IS ScalarType].enum_values,
      is_seq := 'std::sequence' in [IS ScalarType].ancestors.name,
      # for sequence (abstract type that has non-abstract ancestor)
      single material_id := (
        SELECT x := Type[IS ScalarType].ancestors
        FILTER x IN material_scalars
        LIMIT 1
      ).id,

      [IS InheritingObject].bases: {
        id
      } ORDER BY @index ASC,

      [IS ObjectType].union_of,
      [IS ObjectType].intersection_of,
      [IS ObjectType].pointers: {
        card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
        name,
        target_id := .target.id,
        kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
        is_exclusive := exists (select .constraints filter .name = 'std::exclusive'),
        is_computed := len(.computed_fields) != 0,
        is_readonly := .readonly,
        has_default := EXISTS .default or ("std::sequence" in .target[IS ScalarType].ancestors.name),
        [IS Link].pointers: {
          card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
          name := '@' ++ .name,
          target_id := .target.id,
          kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
          is_computed := len(.computed_fields) != 0,
          is_readonly := .readonly
        } filter .name != '@source' and .name != '@target',
      } FILTER any(@is_owned),
      exclusives := assert_distinct((
        [is schema::ObjectType].constraints
        union
        [is schema::ObjectType].pointers.constraints
      ) {
        target := (.subject[is schema::Property].name ?? .subject[is schema::Link].name ?? .subjectexpr)
      } filter .name = 'std::exclusive'),
      backlinks := (
         SELECT DETACHED Link
         FILTER .target = Type
           AND NOT EXISTS .source[IS ObjectType].union_of
        ) {
        card := "AtMostOne"
          IF
          EXISTS (select .constraints filter .name = 'std::exclusive')
          ELSE
          "Many",
        name := '<' ++ .name ++ '[is ' ++ assert_exists(.source.name) ++ ']',
        stub := .name,
        target_id := .source.id,
        kind := 'link',
        is_exclusive := (EXISTS (select .constraints filter .name = 'std::exclusive')) AND <str>.cardinality = "One",
      },
      backlink_stubs := array_agg((
        WITH
          stubs := DISTINCT (SELECT DETACHED Link FILTER .target = Type).name,
          baseObjectId := (SELECT DETACHED ObjectType FILTER .name = 'std::BaseObject' LIMIT 1).id
        FOR stub in { stubs }
        UNION (
          SELECT {
            card := "Many",
            name := '<' ++ stub,
            target_id := baseObjectId,
            kind := 'link',
            is_exclusive := false,
          }
        )
      )),
      array_element_id := [IS Array].element_type.id,

      tuple_elements := (SELECT [IS Tuple].element_types {
        target_id := .type.id,
        name
      } ORDER BY @index ASC),
      ${v2Plus ? `range_element_id := [IS Range].element_type.id,` : ``}
      ${v4Plus ? `multirange_element_id := [IS MultiRange].element_type.id,` : ``}
    }
    ORDER BY .name;
  `;
      const _types = JSON.parse(await cxn.queryJSON(QUERY));
      if (debug)
        console.log(JSON.stringify(_types, null, 2));
      for (const type of _types) {
        if (Array.isArray(type.backlinks)) {
          for (const backlink of type.backlinks) {
            const isName = backlink.name.match(/\[is (.+)\]/)[1];
            if (isName.split("::").length === 2 && isName.startsWith("default::")) {
              backlink.name = backlink.name.replace(/\[is (.+)\]/, `[is ${isName.slice(9)}]`);
            }
          }
        }
        switch (type.kind) {
          case "scalar":
            if (exports2.typeMapping.has(type.id)) {
              type.cast_type = exports2.typeMapping.get(type.id).id;
            }
            if (type.is_seq) {
              type.cast_type = numberType2.id;
            }
            if (type.name !== "std::sequence" && ((_a2 = type.bases[0]) == null ? void 0 : _a2.id) === type.material_id) {
              type.cast_type = ((_b = exports2.typeMapping.get(type.material_id)) == null ? void 0 : _b.id) ?? type.material_id;
            }
            break;
          case "multirange":
            type.multirange_element_id = ((_c = exports2.typeMapping.get(type.multirange_element_id)) == null ? void 0 : _c.id) ?? type.multirange_element_id;
            break;
          case "range":
            type.range_element_id = ((_d = exports2.typeMapping.get(type.range_element_id)) == null ? void 0 : _d.id) ?? type.range_element_id;
            break;
          case "object": {
            const ptrs = {};
            for (const ptr of type.pointers) {
              ptrs[ptr.name] = ptr;
            }
            const rawExclusives = type.exclusives;
            const exclusives = [];
            for (const ex of rawExclusives) {
              const target = ex.target;
              if (target in ptrs) {
                exclusives.push({ [ex.target]: ptrs[ex.target] });
              }
              if (target[0] === "(" && target[target.length - 1] === ")") {
                const targets = target.slice(1, -1).split(" ").map((t4) => {
                  t4 = t4.trim();
                  if (t4[0] === ".")
                    t4 = t4.slice(1);
                  if (t4[t4.length - 1] === ",")
                    t4 = t4.slice(0, -1);
                  return t4;
                });
                const newEx = {};
                if (!targets.every((t4) => t4 in ptrs)) {
                  continue;
                }
                for (const t4 of targets) {
                  newEx[t4] = ptrs[t4];
                }
                exclusives.push(newEx);
              }
            }
            type.exclusives = exclusives;
            break;
          }
        }
      }
      _types.push(numberType2);
      const types3 = topoSort(_types);
      for (const [_3, type] of types3) {
        if (type.kind === "object" && type.union_of.length) {
          const unionTypes = type.union_of.map(({ id }) => {
            const t4 = types3.get(id);
            if (t4.kind !== "object") {
              throw new Error(`type '${t4.name}' of union '${type.name}' is not an object type`);
            }
            return t4;
          });
          const [first, ...rest] = unionTypes;
          const restPointerNames = rest.map((t4) => new Set(t4.pointers.map((p3) => p3.name)));
          for (const pointer of first.pointers) {
            if (restPointerNames.every((names) => names.has(pointer.name))) {
              type.pointers.push(pointer);
            }
          }
          type.backlinks = [];
          type.backlink_stubs = [];
        }
      }
      return types3;
    }
    function topoSort(types3) {
      const graph = new strictMap_1.StrictMap();
      const adj = new strictMap_1.StrictMap();
      for (const type of types3) {
        graph.set(type.id, type);
      }
      for (const type of types3) {
        if (type.kind !== "object" && type.kind !== "scalar") {
          continue;
        }
        for (const { id: base } of type.bases) {
          if (!graph.has(base)) {
            throw new Error(`reference to an unknown object type: ${base}`);
          }
          if (!adj.has(type.id)) {
            adj.set(type.id, /* @__PURE__ */ new Set());
          }
          adj.get(type.id).add(base);
        }
      }
      const visiting = /* @__PURE__ */ new Set();
      const visited = /* @__PURE__ */ new Set();
      const sorted = new strictMap_1.StrictMap();
      const visit = (type) => {
        if (visiting.has(type.name)) {
          const last = Array.from(visiting).slice(1, 2);
          throw new Error(`dependency cycle between ${type.name} and ${last}`);
        }
        if (!visited.has(type.id)) {
          visiting.add(type.name);
          if (adj.has(type.id)) {
            for (const adjId of adj.get(type.id).values()) {
              visit(graph.get(adjId));
            }
          }
          sorted.set(type.id, type);
          visited.add(type.id);
          visiting.delete(type.name);
        }
      };
      for (const type of types3) {
        visit(type);
      }
      return sorted;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js
var require_casts = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.casts = void 0;
    var types_1 = require_types();
    var reachableFrom = (source, adj, seen = /* @__PURE__ */ new Set()) => {
      const reachable = /* @__PURE__ */ new Set();
      if (seen.has(source))
        return [];
      seen.add(source);
      (adj[source] || []).map((cast) => {
        reachable.add(cast);
        for (const item of reachableFrom(cast, adj, seen)) {
          reachable.add(item);
        }
      });
      return [...reachable];
    };
    var casts = async (cxn, params) => {
      const allCastsRaw = await cxn.queryJSON(`WITH MODULE schema
        SELECT Cast {
            id,
            source := .from_type { id, name },
            target := .to_type { id, name },
            allow_assignment,
            allow_implicit,
        }
        FILTER .from_type IS ScalarType
        AND .to_type IS ScalarType
        # AND .from_type.is_abstract = false
        # AND .to_type.is_abstract = false
        `);
      const allCasts = JSON.parse(allCastsRaw);
      const types3 = /* @__PURE__ */ new Set();
      const typesById = {};
      const castsById = {};
      const castsBySource = {};
      const implicitCastsBySource = {};
      const implicitCastsByTarget = {};
      const assignmentCastsBySource = {};
      const assignmentCastsByTarget = {};
      for (const cast of allCasts) {
        if (types_1.typeMapping.has(cast.source.id) || types_1.typeMapping.has(cast.target.id)) {
          cast.allow_implicit = false;
          cast.allow_assignment = false;
        }
        typesById[cast.source.id] = cast.source;
        typesById[cast.target.id] = cast.target;
        types3.add(cast.source.id);
        types3.add(cast.target.id);
        castsById[cast.id] = cast;
        castsBySource[cast.source.id] = castsBySource[cast.source.id] || [];
        castsBySource[cast.source.id].push(cast.target.id);
        if (cast.allow_assignment || cast.allow_implicit) {
          assignmentCastsBySource[cast.source.id] ??= [];
          assignmentCastsBySource[cast.source.id].push(cast.target.id);
          assignmentCastsByTarget[cast.target.id] ??= [];
          assignmentCastsByTarget[cast.target.id].push(cast.source.id);
        }
        if (cast.allow_implicit) {
          implicitCastsBySource[cast.source.id] ??= [];
          implicitCastsBySource[cast.source.id].push(cast.target.id);
          implicitCastsByTarget[cast.target.id] ??= [];
          implicitCastsByTarget[cast.target.id].push(cast.source.id);
        }
      }
      const castMap = {};
      const implicitCastMap = {};
      const implicitCastFromMap = {};
      const assignmentCastMap = {};
      const assignableByMap = {};
      for (const type of [...types3]) {
        castMap[type] = castsBySource[type] || [];
        implicitCastMap[type] = reachableFrom(type, implicitCastsBySource);
        implicitCastFromMap[type] = reachableFrom(type, implicitCastsByTarget);
        assignmentCastMap[type] = reachableFrom(type, assignmentCastsBySource);
        assignableByMap[type] = reachableFrom(type, assignmentCastsByTarget);
      }
      if ((params == null ? void 0 : params.debug) === true) {
        console.log(`
IMPLICIT`);
        for (const [fromId, castArr] of Object.entries(implicitCastMap)) {
          console.log(`${typesById[fromId].name} implicitly castable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log("");
        for (const [fromId, castArr] of Object.entries(implicitCastFromMap)) {
          console.log(`${typesById[fromId].name} implicitly castable from: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
ASSIGNABLE TO`);
        for (const [fromId, castArr] of Object.entries(assignmentCastMap)) {
          console.log(`${typesById[fromId].name} assignable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
ASSIGNABLE BY`);
        for (const [fromId, castArr] of Object.entries(assignableByMap)) {
          console.log(`${typesById[fromId].name} assignable by: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
EXPLICIT`);
        for (const [fromId, castArr] of Object.entries(castMap)) {
          console.log(`${typesById[fromId].name} castable to: [${castArr.map((id) => {
            return typesById[id].name;
          }).join(", ")}]`);
        }
      }
      return {
        castsById,
        typesById,
        castMap,
        implicitCastMap,
        implicitCastFromMap,
        assignmentCastMap,
        assignableByMap
      };
    };
    exports2.casts = casts;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js
var require_functions = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.functions = void 0;
    exports2.replaceNumberTypes = replaceNumberTypes;
    var strictMap_1 = require_strictMap();
    var types_1 = require_types();
    var functions = async (cxn) => {
      var _a2;
      const functionsJson = await cxn.queryJSON(`
    with module schema
    select Function {
      id,
      name,
      annotations: {
        name,
        @value
      } filter .name = 'std::description',
      return_type: {id, name},
      return_typemod,
      params: {
        name,
        type: {id, name},
        kind,
        typemod,
        hasDefault := exists .default,
      } order by @index,
      preserves_optionality,
    } filter .internal = false
  `);
      const functionMap = new strictMap_1.StrictMap();
      const seenFuncDefHashes = /* @__PURE__ */ new Set();
      for (const func of JSON.parse(functionsJson)) {
        const { name } = func;
        const funcDef = {
          ...func,
          description: (_a2 = func.annotations[0]) == null ? void 0 : _a2["@value"]
        };
        replaceNumberTypes(funcDef);
        const hash = hashFuncDef(funcDef);
        if (!seenFuncDefHashes.has(hash)) {
          if (!functionMap.has(name)) {
            functionMap.set(name, [funcDef]);
          } else {
            functionMap.get(name).push(funcDef);
          }
          seenFuncDefHashes.add(hash);
        }
      }
      return functionMap;
    };
    exports2.functions = functions;
    function replaceNumberTypes(def) {
      if (types_1.typeMapping.has(def.return_type.id)) {
        const type = types_1.typeMapping.get(def.return_type.id);
        def.return_type = {
          id: type.id,
          name: type.name
        };
      }
      for (const param of def.params) {
        if (types_1.typeMapping.has(param.type.id)) {
          const type = types_1.typeMapping.get(param.type.id);
          param.type = {
            id: type.id,
            name: type.name
          };
        }
      }
    }
    function hashFuncDef(def) {
      return JSON.stringify({
        name: def.name,
        return_type: def.return_type.id,
        return_typemod: def.return_typemod,
        params: def.params.map((param) => JSON.stringify({
          kind: param.kind,
          type: param.type.id,
          typemod: param.typemod,
          hasDefault: !!param.hasDefault
        })).sort(),
        preserves_optionality: def.preserves_optionality
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js
var require_globals = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.globals = globals;
    async function globals(cxn) {
      const globalsMap = /* @__PURE__ */ new Map();
      const version3 = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
      if (version3 === 1) {
        return globalsMap;
      }
      const QUERY = `
    WITH
      MODULE schema
    SELECT schema::Global {
      id,
      name,
      target_id := .target.id,
      card := ("One" IF .required ELSE "One" IF EXISTS .default ELSE "AtMostOne")
        IF <str>.cardinality = "One" ELSE
        ("AtLeastOne" IF .required ELSE "Many"),
      has_default := exists .default,
    }
    ORDER BY .name;
  `;
      const allGlobals = JSON.parse(await cxn.queryJSON(QUERY));
      for (const g3 of allGlobals) {
        globalsMap.set(g3.id, g3);
      }
      return globalsMap;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js
var require_operators = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.operators = void 0;
    var strictMap_1 = require_strictMap();
    var functions_1 = require_functions();
    var util_1 = require_util3();
    var _operators = async (cxn) => {
      var _a2, _b;
      const operatorsJson = await cxn.queryJSON(`
    with module schema
    select Operator {
      id,
      name,
      annotations: {
        name,
        @value
      } filter .name in {'std::identifier', 'std::description'},
      operator_kind,
      return_type: {id, name},
      return_typemod,
      params: {
        name,
        type: {id, name},
        kind,
        typemod,
      } order by @index,
    } filter not .internal and not .abstract
  `);
      const operators = new strictMap_1.StrictMap();
      const seenOpDefHashes = /* @__PURE__ */ new Set();
      for (const op of JSON.parse(operatorsJson)) {
        const identifier = (_a2 = op.annotations.find((anno) => anno.name === "std::identifier")) == null ? void 0 : _a2["@value"];
        if (!identifier) {
          continue;
        }
        const { mod } = util_1.util.splitName(op.name);
        const name = `${mod}::${identifier}`;
        const opDef = {
          ...op,
          name,
          kind: op.operator_kind,
          originalName: op.name,
          description: (_b = op.annotations.find((anno) => anno.name === "std::description")) == null ? void 0 : _b["@value"],
          annotations: void 0
        };
        (0, functions_1.replaceNumberTypes)(opDef);
        const hash = hashOpDef(opDef);
        if (!seenOpDefHashes.has(hash)) {
          if (!operators.has(name)) {
            operators.set(name, [opDef]);
          } else {
            operators.get(name).push(opDef);
          }
          seenOpDefHashes.add(hash);
        }
      }
      return operators;
    };
    exports2.operators = _operators;
    function hashOpDef(def) {
      return JSON.stringify({
        name: def.name,
        return_type: def.return_type.id,
        return_typemod: def.return_typemod,
        params: def.params.map((param) => JSON.stringify({
          kind: param.kind,
          type: param.type.id,
          typemod: param.typemod,
          hasDefault: !!param.hasDefault
        })).sort(),
        operator_kind: def.operator_kind
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js
var require_scalars = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.scalars = void 0;
    var strictMap_1 = require_strictMap();
    var _scalars = async (cxn) => {
      const scalarArray = await cxn.queryJSON(`with module schema
select InheritingObject {
  id,
  name,
  is_abstract,
  bases: { id, name },
  ancestors: { id, name },
  children := .<bases[IS Type] { id, name },
  descendants := .<ancestors[IS Type] { id, name }
}
FILTER
  InheritingObject IS ScalarType OR
  InheritingObject IS ObjectType;
`);
      const scalars = new strictMap_1.StrictMap();
      for (const type of JSON.parse(scalarArray)) {
        scalars.set(type.id, type);
      }
      return scalars;
    };
    exports2.scalars = _scalars;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js
var require_queries = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
      for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_casts(), exports2);
    __exportStar2(require_functions(), exports2);
    __exportStar2(require_globals(), exports2);
    __exportStar2(require_operators(), exports2);
    __exportStar2(require_scalars(), exports2);
    __exportStar2(require_types(), exports2);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js
var require_analyzeQuery = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ImportMap = exports2.defaultApplyCardinalityToTsType = exports2.generateTsObjectField = exports2.generateTsObject = exports2.defaultCodecGenerators = exports2.defineCodecGeneratorTuple = exports2.generateTSTypeFromCodec = void 0;
    exports2.analyzeQuery = analyzeQuery;
    var array_1 = require_array();
    var enum_1 = require_enum();
    var ifaces_1 = require_ifaces();
    var namedtuple_1 = require_namedtuple();
    var object_1 = require_object();
    var range_1 = require_range3();
    var codecs_1 = require_codecs();
    var set_1 = require_set();
    var tuple_1 = require_tuple();
    var enums_1 = require_enums();
    var util_1 = require_util3();
    async function analyzeQuery(client, query) {
      const { cardinality, capabilities, in: inCodec, out: outCodec } = await client.describe(query);
      const args = (0, exports2.generateTSTypeFromCodec)(inCodec, enums_1.Cardinality.One, {
        optionalNulls: true,
        readonly: true
      });
      const result = (0, exports2.generateTSTypeFromCodec)(outCodec, cardinality);
      const imports = args.imports.merge(result.imports);
      return {
        result: result.type,
        args: args.type,
        cardinality,
        capabilities,
        query,
        importMap: imports,
        imports: imports.get("gel") ?? /* @__PURE__ */ new Set()
      };
    }
    var generateTSTypeFromCodec = (codec, cardinality = enums_1.Cardinality.One, options = {}) => {
      const optionsWithDefaults = {
        indent: "",
        optionalNulls: false,
        readonly: false,
        ...options
      };
      const context = {
        ...optionsWithDefaults,
        generators: exports2.defaultCodecGenerators,
        applyCardinality: (0, exports2.defaultApplyCardinalityToTsType)(optionsWithDefaults),
        ...options,
        imports: new ImportMap(),
        walk: (codec2, innerContext) => {
          innerContext ??= context;
          for (const [type2, generator] of innerContext.generators) {
            if (codec2 instanceof type2) {
              return generator(codec2, innerContext);
            }
          }
          throw new Error(`Unexpected codec kind: ${codec2.getKind()}`);
        }
      };
      const type = context.applyCardinality(context.walk(codec, context), cardinality);
      return {
        type,
        imports: context.imports
      };
    };
    exports2.generateTSTypeFromCodec = generateTSTypeFromCodec;
    var genDef = (codecType, generator) => [codecType, generator];
    exports2.defineCodecGeneratorTuple = genDef;
    exports2.defaultCodecGenerators = new Map([
      genDef(codecs_1.NullCodec, () => "null"),
      genDef(enum_1.EnumCodec, (codec) => {
        return `(${codec.values.map((val2) => JSON.stringify(val2)).join(" | ")})`;
      }),
      genDef(ifaces_1.ScalarCodec, (codec, ctx) => {
        if (codec.tsModule) {
          ctx.imports.add(codec.tsModule, codec.tsType);
        }
        return codec.tsType;
      }),
      genDef(object_1.ObjectCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs();
        const fields = codec.getFields().map((field, i4) => ({
          name: field.name,
          codec: subCodecs[i4],
          cardinality: util_1.util.parseCardinality(field.cardinality)
        }));
        return (0, exports2.generateTsObject)(fields, ctx);
      }),
      genDef(namedtuple_1.NamedTupleCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs();
        const fields = codec.getNames().map((name, i4) => ({
          name,
          codec: subCodecs[i4],
          cardinality: enums_1.Cardinality.One
        }));
        return (0, exports2.generateTsObject)(fields, ctx);
      }),
      genDef(tuple_1.TupleCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs().map((subCodec) => ctx.walk(subCodec));
        const tuple = `[${subCodecs.join(", ")}]`;
        return ctx.readonly ? `(readonly ${tuple})` : tuple;
      }),
      genDef(array_1.ArrayCodec, (codec, ctx) => ctx.applyCardinality(ctx.walk(codec.getSubcodecs()[0]), enums_1.Cardinality.Many)),
      genDef(range_1.RangeCodec, (codec, ctx) => {
        const subCodec = codec.getSubcodecs()[0];
        if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
          throw Error("expected range subtype to be scalar type");
        }
        ctx.imports.add(codec.tsModule, codec.tsType);
        return `${codec.tsType}<${ctx.walk(subCodec)}>`;
      }),
      genDef(range_1.MultiRangeCodec, (codec, ctx) => {
        const subCodec = codec.getSubcodecs()[0];
        if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
          throw Error("expected multirange subtype to be scalar type");
        }
        ctx.imports.add(codec.tsModule, codec.tsType);
        return `${codec.tsType}<${ctx.walk(subCodec)}>`;
      })
    ]);
    var generateTsObject = (fields, ctx) => {
      const properties = fields.map((field) => (0, exports2.generateTsObjectField)(field, ctx));
      return `{
${properties.join("\n")}
${ctx.indent}}`;
    };
    exports2.generateTsObject = generateTsObject;
    var generateTsObjectField = (field, ctx) => {
      const codec = unwrapSetCodec(field.codec, field.cardinality);
      const name = JSON.stringify(field.name);
      const value = ctx.applyCardinality(ctx.walk(codec, { ...ctx, indent: ctx.indent + "  " }), field.cardinality);
      const optional = ctx.optionalNulls && field.cardinality === enums_1.Cardinality.AtMostOne;
      const questionMark = optional ? "?" : "";
      const isReadonly = ctx.readonly ? "readonly " : "";
      return `${ctx.indent}  ${isReadonly}${name}${questionMark}: ${value};`;
    };
    exports2.generateTsObjectField = generateTsObjectField;
    function unwrapSetCodec(codec, cardinality) {
      if (!(codec instanceof set_1.SetCodec)) {
        return codec;
      }
      if (cardinality === enums_1.Cardinality.Many || cardinality === enums_1.Cardinality.AtLeastOne) {
        return codec.getSubcodecs()[0];
      }
      throw new Error("Sub-codec is SetCodec, but upper cardinality is one");
    }
    var defaultApplyCardinalityToTsType = (ctx) => (type, cardinality) => {
      switch (cardinality) {
        case enums_1.Cardinality.Many:
          return `${ctx.readonly ? "Readonly" : ""}Array<${type}>`;
        case enums_1.Cardinality.One:
          return type;
        case enums_1.Cardinality.AtMostOne:
          return `${type} | null`;
        case enums_1.Cardinality.AtLeastOne: {
          const tuple = `[(${type}), ...(${type})[]]`;
          return ctx.readonly ? `(readonly ${tuple})` : tuple;
        }
      }
      throw new Error(`Unexpected cardinality: ${cardinality}`);
    };
    exports2.defaultApplyCardinalityToTsType = defaultApplyCardinalityToTsType;
    var ImportMap = class _ImportMap extends Map {
      add(module3, specifier) {
        if (!this.has(module3)) {
          this.set(module3, /* @__PURE__ */ new Set());
        }
        this.get(module3).add(specifier);
        return this;
      }
      merge(map2) {
        const out = new _ImportMap();
        for (const [mod, specifiers] of [...this, ...map2]) {
          for (const specifier of specifiers) {
            out.add(mod, specifier);
          }
        }
        return out;
      }
    };
    exports2.ImportMap = ImportMap;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js
var require_reflection = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
      for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
    };
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Capabilities = exports2.introspect = void 0;
    __exportStar2(require_enums(), exports2);
    __exportStar2(require_util3(), exports2);
    __exportStar2(require_typeutil(), exports2);
    __exportStar2(require_util3(), exports2);
    __exportStar2(require_strictMap(), exports2);
    __exportStar2(require_reservedKeywords(), exports2);
    exports2.introspect = __importStar2(require_queries());
    __exportStar2(require_analyzeQuery(), exports2);
    var baseConn_1 = require_baseConn();
    Object.defineProperty(exports2, "Capabilities", { enumerable: true, get: function() {
      return baseConn_1.Capabilities;
    } });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js
var require_index_node = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m4, k3);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m4, k3, k22) {
      if (k22 === void 0) k22 = k3;
      o3[k22] = m4[k3];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
    } : function(o3, v6) {
      o3["default"] = v6;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
      for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.$ = exports2.Client = exports2.ResolvedConnectConfig = exports2._RawConnection = exports2.systemUtils = exports2.createHttpClient = exports2.createClient = void 0;
    var nodeClient_1 = require_nodeClient();
    exports2.default = nodeClient_1.createClient;
    var nodeClient_2 = require_nodeClient();
    Object.defineProperty(exports2, "createClient", { enumerable: true, get: function() {
      return nodeClient_2.createClient;
    } });
    Object.defineProperty(exports2, "createHttpClient", { enumerable: true, get: function() {
      return nodeClient_2.createHttpClient;
    } });
    var systemUtils = __importStar2(require_systemUtils());
    exports2.systemUtils = systemUtils;
    var rawConn_1 = require_rawConn();
    Object.defineProperty(exports2, "_RawConnection", { enumerable: true, get: function() {
      return rawConn_1.RawConnection;
    } });
    var conUtils_1 = require_conUtils();
    Object.defineProperty(exports2, "ResolvedConnectConfig", { enumerable: true, get: function() {
      return conUtils_1.ResolvedConnectConfig;
    } });
    var baseClient_1 = require_baseClient();
    Object.defineProperty(exports2, "Client", { enumerable: true, get: function() {
      return baseClient_1.Client;
    } });
    __exportStar2(require_index_shared(), exports2);
    exports2.$ = __importStar2(require_reflection());
  }
});

// src/cli/connections.ts
var connections_exports = {};
__export(connections_exports, {
  connectToLibSQL: () => connectToLibSQL,
  connectToMySQL: () => connectToMySQL,
  connectToSQLite: () => connectToSQLite,
  connectToSingleStore: () => connectToSingleStore,
  prepareGelDB: () => prepareGelDB,
  preparePostgresDB: () => preparePostgresDB
});
var preparePostgresDB, prepareGelDB, parseSingleStoreCredentials, connectToSingleStore, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, preparePGliteParams, connectToSQLite, connectToLibSQL;
var init_connections = __esm({
  "src/cli/connections.ts"() {
    "use strict";
    init_src();
    init_wrapper();
    init_global();
    init_utils2();
    init_utils5();
    init_outputs();
    preparePostgresDB = async (credentials2) => {
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "aws-data-api") {
          assertPackages("@aws-sdk/client-rds-data");
          const { RDSDataClient, ExecuteStatementCommand, TypeHint } = await Promise.resolve().then(() => __toESM(require_dist_cjs51()));
          const { AwsDataApiSession, drizzle } = await import("drizzle-orm/aws-data-api/pg");
          const { migrate: migrate2 } = await import("drizzle-orm/aws-data-api/pg/migrator");
          const { PgDialect: PgDialect2 } = await import("drizzle-orm/pg-core");
          const config = {
            database: credentials2.database,
            resourceArn: credentials2.resourceArn,
            secretArn: credentials2.secretArn
          };
          const rdsClient = new RDSDataClient();
          const session = new AwsDataApiSession(
            rdsClient,
            new PgDialect2(),
            void 0,
            config,
            void 0
          );
          const db = drizzle(rdsClient, config);
          const migrateFn = async (config2) => {
            return migrate2(db, config2);
          };
          const query = async (sql, params) => {
            const prepared = session.prepareQuery(
              { sql, params: params ?? [] },
              void 0,
              void 0,
              false
            );
            const result = await prepared.all();
            return result;
          };
          const proxy = async (params) => {
            const prepared = session.prepareQuery(
              {
                sql: params.sql,
                params: params.params ?? [],
                typings: params.typings
              },
              void 0,
              void 0,
              params.mode === "array"
            );
            if (params.mode === "array") {
              const result2 = await prepared.values();
              return result2.rows;
            }
            const result = await prepared.execute();
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            throw new Error("Transaction not supported");
          };
          return {
            packageName: "@aws-sdk/client-rds-data",
            query,
            proxy,
            transactionProxy,
            migrate: migrateFn
          };
        }
        if (driver2 === "pglite") {
          assertPackages("@electric-sql/pglite");
          const { PGlite, types: types3 } = await import("@electric-sql/pglite");
          const { drizzle } = await import("drizzle-orm/pglite");
          const { migrate: migrate2 } = await import("drizzle-orm/pglite/migrator");
          const pglite = new PGlite(normalisePGliteUrl(credentials2.url));
          await pglite.waitReady;
          const drzl = drizzle(pglite);
          const migrateFn = async (config) => {
            return migrate2(drzl, config);
          };
          const parsers = {
            [types3.TIMESTAMP]: (value) => value,
            [types3.TIMESTAMPTZ]: (value) => value,
            [types3.INTERVAL]: (value) => value,
            [types3.DATE]: (value) => value
          };
          const query = async (sql, params = []) => {
            const result = await pglite.query(sql, params, {
              parsers
            });
            return result.rows;
          };
          const proxy = async (params) => {
            const preparedParams = preparePGliteParams(params.params || []);
            const result = await pglite.query(params.sql, preparedParams, {
              rowMode: params.mode,
              parsers
            });
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            const results = [];
            try {
              await pglite.transaction(async (tx) => {
                for (const query2 of queries) {
                  const result = await tx.query(query2.sql, void 0, {
                    parsers
                  });
                  results.push(result.rows);
                }
              });
            } catch (error2) {
              results.push(error2);
            }
            return results;
          };
          return { packageName: "pglite", query, proxy, transactionProxy, migrate: migrateFn };
        }
        assertUnreachable(driver2);
      }
      if (await checkPackage("pg")) {
        console.log(withStyle.info(`Using 'pg' driver for database querying`));
        const { default: pg } = await import("pg");
        const { drizzle } = await import("drizzle-orm/node-postgres");
        const { migrate: migrate2 } = await import("drizzle-orm/node-postgres/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pg.types.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pg.types.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new pg.Pool({ connectionString: credentials2.url, max: 1 }) : new pg.Pool({ ...credentials2, ssl, max: 1 });
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "pg", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("postgres")) {
        console.log(
          withStyle.info(`Using 'postgres' driver for database querying`)
        );
        const postgres = await import("postgres");
        const { drizzle } = await import("drizzle-orm/postgres-js");
        const { migrate: migrate2 } = await import("drizzle-orm/postgres-js/migrator");
        const client = "url" in credentials2 ? postgres.default(credentials2.url, { max: 1 }) : postgres.default({ ...credentials2, max: 1 });
        const transparentParser = (val2) => val2;
        for (const type of ["1184", "1082", "1083", "1114"]) {
          client.options.parsers[type] = transparentParser;
          client.options.serializers[type] = transparentParser;
        }
        client.options.serializers["114"] = transparentParser;
        client.options.serializers["3802"] = transparentParser;
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.unsafe(sql, params ?? []);
          return result;
        };
        const proxy = async (params) => {
          if (params.mode === "array") {
            return await client.unsafe(params.sql, params.params).values();
          }
          return await client.unsafe(params.sql, params.params);
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await client.begin(async (sql) => {
              for (const query2 of queries) {
                const result = await sql.unsafe(query2.sql);
                results.push(result);
              }
            });
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return { packageName: "postgres", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("@vercel/postgres")) {
        console.log(
          withStyle.info(`Using '@vercel/postgres' driver for database querying`)
        );
        console.log(
          withStyle.fullWarning(
            "'@vercel/postgres' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
          )
        );
        const { VercelPool, types: pgTypes } = await import("@vercel/postgres");
        const { drizzle } = await import("drizzle-orm/vercel-postgres");
        const { migrate: migrate2 } = await import("drizzle-orm/vercel-postgres/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pgTypes.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new VercelPool({ connectionString: credentials2.url }) : new VercelPool({ ...credentials2, ssl });
        await client.connect();
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "@vercel/postgres", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("@neondatabase/serverless")) {
        console.log(
          withStyle.info(
            `Using '@neondatabase/serverless' driver for database querying`
          )
        );
        console.log(
          withStyle.fullWarning(
            "'@neondatabase/serverless' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
          )
        );
        const { Pool, neonConfig, types: pgTypes } = await import("@neondatabase/serverless");
        const { drizzle } = await import("drizzle-orm/neon-serverless");
        const { migrate: migrate2 } = await import("drizzle-orm/neon-serverless/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pgTypes.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new Pool({ connectionString: credentials2.url, max: 1 }) : new Pool({ ...credentials2, max: 1, ssl });
        neonConfig.webSocketConstructor = wrapper_default;
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "@neondatabase/serverless", query, proxy, transactionProxy, migrate: migrateFn };
      }
      console.error(
        "To connect to Postgres database - please install either of 'pg', 'postgres', '@neondatabase/serverless' or '@vercel/postgres' drivers"
      );
      process.exit(1);
    };
    prepareGelDB = async (credentials2) => {
      if (await checkPackage("gel")) {
        const gel = await Promise.resolve().then(() => __toESM(require_index_node()));
        let client;
        if (!credentials2) {
          client = gel.createClient();
          try {
            await client.querySQL(`select 1;`);
          } catch (error2) {
            if (error2 instanceof gel.ClientConnectionError) {
              console.error(
                `It looks like you forgot to link the Gel project or provide the database credentials.
To link your project, please refer https://docs.geldata.com/reference/cli/gel_instance/gel_instance_link, or add the dbCredentials to your configuration file.`
              );
              process.exit(1);
            }
            throw error2;
          }
        } else if ("url" in credentials2) {
          "tlsSecurity" in credentials2 ? client = gel.createClient({ dsn: credentials2.url, tlsSecurity: credentials2.tlsSecurity, concurrency: 1 }) : client = gel.createClient({ dsn: credentials2.url, concurrency: 1 });
        } else {
          gel.createClient({ ...credentials2, concurrency: 1 });
        }
        const query = async (sql, params) => {
          const result = (params == null ? void 0 : params.length) ? await client.querySQL(sql, params) : await client.querySQL(sql);
          return result;
        };
        const proxy = async (params) => {
          const { method, mode, params: sqlParams, sql, typings } = params;
          let result;
          switch (mode) {
            case "array":
              result = (sqlParams == null ? void 0 : sqlParams.length) ? await client.withSQLRowMode("array").querySQL(sql, sqlParams) : await client.withSQLRowMode("array").querySQL(sql);
              break;
            case "object":
              result = (sqlParams == null ? void 0 : sqlParams.length) ? await client.querySQL(sql, sqlParams) : await client.querySQL(sql);
              break;
          }
          return result;
        };
        const transactionProxy = async (queries) => {
          const result = [];
          try {
            await client.transaction(async (tx) => {
              for (const query2 of queries) {
                const res = await tx.querySQL(query2.sql);
                result.push(res);
              }
            });
          } catch (error2) {
            result.push(error2);
          }
          return result;
        };
        return { packageName: "gel", query, proxy, transactionProxy };
      }
      console.error(
        "To connect to gel database - please install 'edgedb' driver"
      );
      process.exit(1);
    };
    parseSingleStoreCredentials = (credentials2) => {
      if ("url" in credentials2) {
        const url = credentials2.url;
        const connectionUrl = new URL(url);
        const pathname = connectionUrl.pathname;
        const database = pathname.split("/")[pathname.split("/").length - 1];
        if (!database) {
          console.error(
            "You should specify a database name in connection string (singlestore://USER:PASSWORD@HOST:PORT/DATABASE)"
          );
          process.exit(1);
        }
        return { database, url };
      } else {
        return {
          database: credentials2.database,
          credentials: credentials2
        };
      }
    };
    connectToSingleStore = async (it) => {
      const result = parseSingleStoreCredentials(it);
      if (await checkPackage("mysql2")) {
        const { createConnection } = await import("mysql2/promise");
        const { drizzle } = await import("drizzle-orm/singlestore");
        const { migrate: migrate2 } = await import("drizzle-orm/singlestore/migrator");
        const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        await connection.connect();
        const query = async (sql, params) => {
          const res = await connection.execute(sql, params);
          return res[0];
        };
        const proxy = async (params) => {
          const result2 = await connection.query({
            sql: params.sql,
            values: params.params,
            rowsAsArray: params.mode === "array"
          });
          return result2[0];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.beginTransaction();
            for (const query2 of queries) {
              const res = await connection.query(query2.sql);
              results.push(res[0]);
            }
            await connection.commit();
          } catch (error2) {
            await connection.rollback();
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "mysql2",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      console.error(
        "To connect to SingleStore database - please install 'mysql2' driver"
      );
      process.exit(1);
    };
    parseMysqlCredentials = (credentials2) => {
      if ("url" in credentials2) {
        const url = credentials2.url;
        const connectionUrl = new URL(url);
        const pathname = connectionUrl.pathname;
        const database = pathname.split("/")[pathname.split("/").length - 1];
        if (!database) {
          console.error(
            "You should specify a database name in connection string (mysql://USER:PASSWORD@HOST:PORT/DATABASE)"
          );
          process.exit(1);
        }
        return { database, url };
      } else {
        return {
          database: credentials2.database,
          credentials: credentials2
        };
      }
    };
    connectToMySQL = async (it) => {
      const result = parseMysqlCredentials(it);
      if (await checkPackage("mysql2")) {
        const { createConnection } = await import("mysql2/promise");
        const { drizzle } = await import("drizzle-orm/mysql2");
        const { migrate: migrate2 } = await import("drizzle-orm/mysql2/migrator");
        const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const typeCast = (field, next) => {
          if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
            return field.string();
          }
          return next();
        };
        await connection.connect();
        const query = async (sql, params) => {
          const res = await connection.execute({
            sql,
            values: params,
            typeCast
          });
          return res[0];
        };
        const proxy = async (params) => {
          const result2 = await connection.query({
            sql: params.sql,
            values: params.params,
            rowsAsArray: params.mode === "array",
            typeCast
          });
          return result2[0];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.beginTransaction();
            for (const query2 of queries) {
              const res = await connection.query(query2.sql);
              results.push(res[0]);
            }
            await connection.commit();
          } catch (error2) {
            await connection.rollback();
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "mysql2",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      if (await checkPackage("@planetscale/database")) {
        const { Client } = await import("@planetscale/database");
        const { drizzle } = await import("drizzle-orm/planetscale-serverless");
        const { migrate: migrate2 } = await import("drizzle-orm/planetscale-serverless/migrator");
        const connection = new Client(result);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const res = await connection.execute(sql, params);
          return res.rows;
        };
        const proxy = async (params) => {
          const result2 = await connection.execute(
            params.sql,
            params.params,
            params.mode === "array" ? { as: "array" } : void 0
          );
          return result2.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.transaction(async (tx) => {
              for (const query2 of queries) {
                const res = await tx.execute(query2.sql);
                results.push(res.rows);
              }
            });
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "@planetscale/database",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      console.error(
        "To connect to MySQL database - please install either of 'mysql2' or '@planetscale/database' drivers"
      );
      process.exit(1);
    };
    prepareSqliteParams = (params, driver2) => {
      return params.map((param) => {
        if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
          const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
          if (driver2 === "d1-http") {
            return value;
          }
          return Buffer.from(value);
        }
        return param;
      });
    };
    preparePGliteParams = (params) => {
      return params.map((param) => {
        if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
          const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
          return value;
        }
        return param;
      });
    };
    connectToSQLite = async (credentials2) => {
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "d1-http") {
          const { drizzle } = await import("drizzle-orm/sqlite-proxy");
          const { migrate: migrate2 } = await import("drizzle-orm/sqlite-proxy/migrator");
          const remoteCallback = async (sql, params, method) => {
            const res = await fetch2(
              `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/${method === "values" ? "raw" : "query"}`,
              {
                method: "POST",
                body: JSON.stringify({ sql, params }),
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${credentials2.token}`
                }
              }
            );
            const data = await res.json();
            if (!data.success) {
              throw new Error(
                data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
              );
            }
            const result = data.result[0].results;
            const rows = Array.isArray(result) ? result : result.rows;
            return {
              rows
            };
          };
          const remoteBatchCallback = async (queries) => {
            const sql = queries.map((q3) => q3.sql).join("; ");
            const res = await fetch2(
              `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/query`,
              {
                method: "POST",
                body: JSON.stringify({ sql }),
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${credentials2.token}`
                }
              }
            );
            const data = await res.json();
            if (!data.success) {
              throw new Error(
                data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
              );
            }
            const rows = data.result.map((result) => {
              const res2 = result.results;
              return Array.isArray(res2) ? res2 : res2.rows;
            });
            return {
              rows
            };
          };
          const drzl = drizzle(remoteCallback);
          const migrateFn = async (config) => {
            return migrate2(
              drzl,
              async (queries) => {
                for (const query of queries) {
                  await remoteCallback(query, [], "run");
                }
              },
              config
            );
          };
          const db = {
            query: async (sql, params) => {
              const res = await remoteCallback(sql, params || [], "all");
              return res.rows;
            },
            run: async (query) => {
              await remoteCallback(query, [], "run");
            }
          };
          const proxy = async (params) => {
            const preparedParams = prepareSqliteParams(params.params || [], "d1-http");
            const result = await remoteCallback(
              params.sql,
              preparedParams,
              params.mode === "array" ? "values" : "all"
            );
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            const result = await remoteBatchCallback(queries);
            return result.rows;
          };
          return { ...db, packageName: "d1-http", proxy, transactionProxy, migrate: migrateFn };
        } else {
          assertUnreachable(driver2);
        }
      }
      if (await checkPackage("@libsql/client")) {
        const { createClient } = await import("@libsql/client");
        const { drizzle } = await import("drizzle-orm/libsql");
        const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql")
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(drzl, config);
        };
        const db = {
          query: async (sql, params) => {
            const res = await client.execute({ sql, args: params || [] });
            return res.rows;
          },
          run: async (query) => {
            await client.execute(query);
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          const result = await client.execute({
            sql: params.sql,
            args: preparedParams
          });
          if (params.mode === "array") {
            return result.rows.map((row) => Object.values(row));
          } else {
            return result.rows;
          }
        };
        const transactionProxy = async (queries) => {
          const results = [];
          let transaction = null;
          try {
            transaction = await client.transaction();
            for (const query of queries) {
              const result = await transaction.execute(query.sql);
              results.push(result.rows);
            }
            await transaction.commit();
          } catch (error2) {
            results.push(error2);
            await (transaction == null ? void 0 : transaction.rollback());
          } finally {
            transaction == null ? void 0 : transaction.close();
          }
          return results;
        };
        return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("better-sqlite3")) {
        const { default: Database } = await import("better-sqlite3");
        const { drizzle } = await import("drizzle-orm/better-sqlite3");
        const { migrate: migrate2 } = await import("drizzle-orm/better-sqlite3/migrator");
        const sqlite = new Database(
          normaliseSQLiteUrl(credentials2.url, "better-sqlite")
        );
        const drzl = drizzle(sqlite);
        const migrateFn = async (config) => {
          return migrate2(drzl, config);
        };
        const db = {
          query: async (sql, params = []) => {
            return sqlite.prepare(sql).bind(params).all();
          },
          run: async (query) => {
            sqlite.prepare(query).run();
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          if (params.method === "values" || params.method === "get" || params.method === "all") {
            return sqlite.prepare(params.sql).raw(params.mode === "array").all(preparedParams);
          }
          sqlite.prepare(params.sql).run(preparedParams);
          return [];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = sqlite.transaction((queries2) => {
            for (const query of queries2) {
              let result = [];
              if (query.method === "values" || query.method === "get" || query.method === "all") {
                result = sqlite.prepare(query.sql).all();
              } else {
                sqlite.prepare(query.sql).run();
              }
              results.push(result);
            }
          });
          try {
            tx(queries);
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return { ...db, packageName: "better-sqlite3", proxy, transactionProxy, migrate: migrateFn };
      }
      console.log(
        "Please install either 'better-sqlite3' or '@libsql/client' for Drizzle Kit to connect to SQLite databases"
      );
      process.exit(1);
    };
    connectToLibSQL = async (credentials2) => {
      if (await checkPackage("@libsql/client")) {
        const { createClient } = await import("@libsql/client");
        const { drizzle } = await import("drizzle-orm/libsql");
        const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql"),
          authToken: credentials2.authToken
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(drzl, config);
        };
        const db = {
          query: async (sql, params) => {
            const res = await client.execute({ sql, args: params || [] });
            return res.rows;
          },
          run: async (query) => {
            await client.execute(query);
          },
          batchWithPragma: async (queries) => {
            await client.migrate(queries);
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          const result = await client.execute({
            sql: params.sql,
            args: preparedParams
          });
          if (params.mode === "array") {
            return result.rows.map((row) => Object.values(row));
          } else {
            return result.rows;
          }
        };
        const transactionProxy = async (queries) => {
          const results = [];
          let transaction = null;
          try {
            transaction = await client.transaction();
            for (const query of queries) {
              const result = await transaction.execute(query.sql);
              results.push(result.rows);
            }
            await transaction.commit();
          } catch (error2) {
            results.push(error2);
            await (transaction == null ? void 0 : transaction.rollback());
          } finally {
            transaction == null ? void 0 : transaction.close();
          }
          return results;
        };
        return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
      }
      console.log(
        "Please install '@libsql/client' for Drizzle Kit to connect to LibSQL databases"
      );
      process.exit(1);
    };
  }
});

// src/cli/selector-ui.ts
var import_hanji5, Select;
var init_selector_ui = __esm({
  "src/cli/selector-ui.ts"() {
    "use strict";
    init_source();
    import_hanji5 = __toESM(require_hanji());
    Select = class extends import_hanji5.Prompt {
      constructor(items) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.on("detach", (terminal) => terminal.toggleCursor("show"));
        this.data = new import_hanji5.SelectState(
          items.map((it) => ({ label: it, value: `${it}-value` }))
        );
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") return "";
        let text = ``;
        this.data.items.forEach((it, idx) => {
          text += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : `  ${it.label}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return {
          index: this.data.selectedIdx,
          value: this.data.items[this.data.selectedIdx].value
        };
      }
    };
  }
});

// src/cli/commands/libSqlPushUtils.ts
var getOldTableName2, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
var init_libSqlPushUtils = __esm({
  "src/cli/commands/libSqlPushUtils.ts"() {
    "use strict";
    init_source();
    init_utils2();
    init_sqliteSchema();
    init_sqlgenerator();
    getOldTableName2 = (tableName, meta) => {
      for (const key of Object.keys(meta.tables)) {
        const value = meta.tables[key];
        if (`"${tableName}"` === value) {
          return key.substring(1, key.length - 1);
        }
      }
      return tableName;
    };
    _moveDataStatements2 = (tableName, json, dataLoss = false) => {
      const statements = [];
      const newTableName = `__new_${tableName}`;
      const tableColumns = Object.values(json.tables[tableName].columns);
      const referenceData = Object.values(json.tables[tableName].foreignKeys);
      const compositePKs = Object.values(
        json.tables[tableName].compositePrimaryKeys
      ).map((it) => SQLiteSquasher.unsquashPK(it));
      const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
      const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
      const mappedCheckConstraints = checkConstraints.map(
        (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
      );
      statements.push(
        new SQLiteCreateTableConvertor().convert({
          type: "sqlite_create_table",
          tableName: newTableName,
          columns: tableColumns,
          referenceData: fks,
          compositePKs,
          checkConstraints: mappedCheckConstraints
        })
      );
      if (!dataLoss) {
        const columns = Object.keys(json.tables[tableName].columns).map(
          (c3) => `"${c3}"`
        );
        statements.push(
          `INSERT INTO \`${newTableName}\`(${columns.join(
            ", "
          )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
        );
      }
      statements.push(
        new SQLiteDropTableConvertor().convert({
          type: "drop_table",
          tableName,
          schema: ""
        })
      );
      statements.push(
        new SqliteRenameTableConvertor().convert({
          fromSchema: "",
          tableNameFrom: newTableName,
          tableNameTo: tableName,
          toSchema: "",
          type: "rename_table"
        })
      );
      for (const idx of Object.values(json.tables[tableName].indexes)) {
        statements.push(
          new CreateSqliteIndexConvertor().convert({
            type: "create_index",
            tableName,
            schema: "",
            data: idx
          })
        );
      }
      return statements;
    };
    libSqlLogSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await connection.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_drop_column") {
          const tableName = statement.tableName;
          const res = await connection.query(
            `select count(*) as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "sqlite_alter_table_add_column" && statement.column.notNull && !statement.column.default) {
          const newTableName = statement.tableName;
          const res = await connection.query(
            `select count(*) as count from \`${newTableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to add not-null ${source_default.underline(
                statement.column.name
              )} column without default value, which contains ${count} items`
            );
            tablesToTruncate.push(newTableName);
            statementsToExecute.push(`delete from ${newTableName};`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          const tableName = statement.tableName;
          if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
            const res = await connection.query(
              `select count(*) as count from \`${tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(tableName);
              statementsToExecute.push(`delete from \`${tableName}\``);
              shouldAskForApprove = true;
            }
          }
          const modifyStatements = new LibSQLModifyColumn().convert(statement, json2);
          statementsToExecute.push(
            ...Array.isArray(modifyStatements) ? modifyStatements : [modifyStatements]
          );
        } else if (statement.type === "recreate_table") {
          const tableName = statement.tableName;
          let dataLoss = false;
          const oldTableName = getOldTableName2(tableName, meta);
          const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
          const currentColumnNames = Object.keys(json2.tables[tableName].columns);
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            prevColumnNames,
            currentColumnNames
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await connection.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count = Number(res[0].count);
              if (count > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await connection.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json2.tables[tableName].columns[addedColumn];
              const count = Number(res.count);
              if (count > 0 && columnConf.notNull && !columnConf.default) {
                dataLoss = true;
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
              }
            }
          }
          const tablesReferencingCurrent = [];
          for (const table6 of Object.values(json2.tables)) {
            const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t4) => SQLiteSquasher.unsquashPushFK(t4).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
            tablesReferencingCurrent.push(...tablesRefs);
          }
          if (!tablesReferencingCurrent.length) {
            statementsToExecute.push(..._moveDataStatements2(tableName, json2, dataLoss));
            continue;
          }
          statementsToExecute.push(
            ..._moveDataStatements2(tableName, json2, dataLoss)
          );
        } else if (statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") {
          const tableName = statement.tableName;
          const res = await connection.query(
            `select count("${statement.columnName}") as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else {
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        }
      }
      return {
        statementsToExecute: [...new Set(statementsToExecute)],
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/mysqlPushUtils.ts
var import_hanji6, filterStatements, logSuggestionsAndReturn2;
var init_mysqlPushUtils = __esm({
  "src/cli/commands/mysqlPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji6 = __toESM(require_hanji());
    init_mysqlSchema();
    init_selector_ui();
    init_outputs();
    filterStatements = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if ((serialStatement == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : serialStatement.newDataType.startsWith("serial")) && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn2 = async (db, statements, json2) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column11) => column11.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column11) => column11.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            const unsquashedUnique = MySqlSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji6.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if ((data == null ? void 0 : data.index) === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/pgPushUtils.ts
function concatSchemaAndTableName(schema6, table6) {
  return schema6 ? `"${schema6}"."${table6}"` : `"${table6}"`;
}
function tableNameWithSchemaFrom(schema6, tableName, renamedSchemas, renamedTables) {
  const newSchemaName = schema6 ? renamedSchemas[schema6] ? renamedSchemas[schema6] : schema6 : void 0;
  const newTableName = renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] ? renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] : tableName;
  return concatSchemaAndTableName(newSchemaName, newTableName);
}
var import_hanji7, pgSuggestions;
var init_pgPushUtils = __esm({
  "src/cli/commands/pgPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji7 = __toESM(require_hanji());
    init_pgSchema();
    init_sqlgenerator();
    init_selector_ui();
    pgSuggestions = async (db, statements) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      const matViewsToRemove = [];
      let renamedSchemas = {};
      let renamedTables = {};
      for (const statement of statements) {
        if (statement.type === "rename_schema") {
          renamedSchemas[statement.to] = statement.from;
        } else if (statement.type === "rename_table") {
          renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
        } else if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count} items`);
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_view" && statement.materialized) {
          const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count} items`
            );
            matViewsToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = '${statement.name}';`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count} tables`);
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
                statement.newDataType
              )} with ${count} items`
            );
            statementsToExecute.push(
              `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
          const tableNameWithSchema = tableNameWithSchemaFrom(
            statement.schema,
            statement.tableName,
            renamedSchemas,
            renamedTables
          );
          const pkNameResponse = await db.query(
            `SELECT constraint_name FROM information_schema.table_constraints
        WHERE table_schema = '${typeof statement.schema === "undefined" || statement.schema === "" ? "public" : statement.schema}'
            AND table_name = '${statement.tableName}'
            AND constraint_type = 'PRIMARY KEY';`
          );
          statementsToExecute.push(
            `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${pkNameResponse[0].constraint_name}"`
          );
          continue;
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(
                `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
              );
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            const unsquashedUnique = PgSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji7.render)(
              new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
            );
            if ((data == null ? void 0 : data.index) === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(
                `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
              );
              shouldAskForApprove = true;
            }
          }
        }
        const stmnt = fromJson([statement], "postgresql", "push");
        if (typeof stmnt !== "undefined") {
          statementsToExecute.push(...stmnt);
        }
      }
      return {
        statementsToExecute: [...new Set(statementsToExecute)],
        shouldAskForApprove,
        infoToPrint,
        matViewsToRemove: [...new Set(matViewsToRemove)],
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/singlestorePushUtils.ts
function findColumnTypeAlternations(columns1, columns2) {
  const changes = [];
  for (const key in columns1) {
    if (columns1.hasOwnProperty(key) && columns2.hasOwnProperty(key)) {
      const col1 = columns1[key];
      const col2 = columns2[key];
      if (col1.type !== col2.type) {
        changes.push(col2.name);
      }
    }
  }
  return changes;
}
var import_hanji8, filterStatements2, logSuggestionsAndReturn3;
var init_singlestorePushUtils = __esm({
  "src/cli/commands/singlestorePushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji8 = __toESM(require_hanji());
    init_sqlgenerator();
    init_singlestoreSchema();
    init_utils2();
    init_selector_ui();
    init_outputs();
    filterStatements2 = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if ((serialStatement == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : serialStatement.newDataType.startsWith("serial")) && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn3 = async (db, statements, json2, json1) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column11) => column11.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column11) => column11.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji8.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if ((data == null ? void 0 : data.index) === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "singlestore_recreate_table") {
          const tableName = statement.tableName;
          const prevColumns = json1.tables[tableName].columns;
          const currentColumns = json2.tables[tableName].columns;
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            Object.keys(prevColumns),
            Object.keys(currentColumns)
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await db.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count = Number(res[0].count);
              if (count > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await db.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json2.tables[tableName].columns[addedColumn];
              const count = Number(res.count);
              if (count > 0 && columnConf.notNull && !columnConf.default) {
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
              }
            }
          }
          const columnWithChangedType = findColumnTypeAlternations(prevColumns, currentColumns);
          for (const column11 of columnWithChangedType) {
            const [res] = await db.query(
              `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column11}\` IS NOT NULL;`
            );
            const count = Number(res.count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about recreate ${source_default.underline(tableName)} table with data type changing for ${source_default.underline(
                  column11
                )} column, which contains ${count} items`
              );
              shouldAskForApprove = true;
              tablesToTruncate.push(tableName);
              statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
            }
          }
        }
        const stmnt = fromJson([statement], "singlestore", "push");
        if (typeof stmnt !== "undefined") {
          statementsToExecute.push(...stmnt);
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
var init_brace_expressions = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js"() {
    posixClasses = {
      "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
      "[:alpha:]": ["\\p{L}\\p{Nl}", true],
      "[:ascii:]": ["\\x00-\\x7f", false],
      "[:blank:]": ["\\p{Zs}\\t", true],
      "[:cntrl:]": ["\\p{Cc}", true],
      "[:digit:]": ["\\p{Nd}", true],
      "[:graph:]": ["\\p{Z}\\p{C}", true, true],
      "[:lower:]": ["\\p{Ll}", true],
      "[:print:]": ["\\p{C}", true],
      "[:punct:]": ["\\p{P}", true],
      "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
      "[:upper:]": ["\\p{Lu}", true],
      "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
      "[:xdigit:]": ["A-Fa-f0-9", false]
    };
    braceEscape = (s4) => s4.replace(/[[\]\\-]/g, "\\$&");
    regexpEscape = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    rangesToString = (ranges) => ranges.join("");
    parseClass = (glob2, position) => {
      const pos = position;
      if (glob2.charAt(pos) !== "[") {
        throw new Error("not in a brace expression");
      }
      const ranges = [];
      const negs = [];
      let i4 = pos + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos;
      let rangeStart = "";
      WHILE: while (i4 < glob2.length) {
        const c3 = glob2.charAt(i4);
        if ((c3 === "!" || c3 === "^") && i4 === pos + 1) {
          negate = true;
          i4++;
          continue;
        }
        if (c3 === "]" && sawStart && !escaping) {
          endPos = i4 + 1;
          break;
        }
        sawStart = true;
        if (c3 === "\\") {
          if (!escaping) {
            escaping = true;
            i4++;
            continue;
          }
        }
        if (c3 === "[" && !escaping) {
          for (const [cls, [unip, u3, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i4)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos, true];
              }
              i4 += cls.length;
              if (neg)
                negs.push(unip);
              else
                ranges.push(unip);
              uflag = uflag || u3;
              continue WHILE;
            }
          }
        }
        escaping = false;
        if (rangeStart) {
          if (c3 > rangeStart) {
            ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c3));
          } else if (c3 === rangeStart) {
            ranges.push(braceEscape(c3));
          }
          rangeStart = "";
          i4++;
          continue;
        }
        if (glob2.startsWith("-]", i4 + 1)) {
          ranges.push(braceEscape(c3 + "-"));
          i4 += 2;
          continue;
        }
        if (glob2.startsWith("-", i4 + 1)) {
          rangeStart = c3;
          i4 += 2;
          continue;
        }
        ranges.push(braceEscape(c3));
        i4++;
      }
      if (endPos < i4) {
        return ["", false, 0, false];
      }
      if (!ranges.length && !negs.length) {
        return ["$.", false, glob2.length - pos, true];
      }
      if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
        const r4 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r4), false, endPos - pos, false];
      }
      const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
      const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
      const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
      return [comb, uflag, endPos - pos, true];
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js
var escape;
var init_escape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js"() {
    escape = (s4, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s4.replace(/[?*()[\]]/g, "[$&]") : s4.replace(/[?*()[\]\\]/g, "\\$&");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js
var unescape2;
var init_unescape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() {
    unescape2 = (s4, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s4.replace(/\[([^\/\\])\]/g, "$1") : s4.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path3, sep, GLOBSTAR, plTypes, qmark, star, twoStarDot, twoStarNoDot, charSet, reSpecials, addPatternStartSet, filter, ext, defaults, braceExpand, MAX_PATTERN_LENGTH, assertValidPattern, makeRe, match, globUnescape, globMagic, regExpEscape, Minimatch;
var init_mjs = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js"() {
    import_brace_expansion = __toESM(require_brace_expansion(), 1);
    init_brace_expressions();
    init_escape();
    init_unescape();
    init_escape();
    init_unescape();
    minimatch = (p3, pattern, options = {}) => {
      assertValidPattern(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options).match(p3);
    };
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = (ext2) => (f5) => !f5.startsWith(".") && f5.endsWith(ext2);
    starDotExtTestDot = (ext2) => (f5) => f5.endsWith(ext2);
    starDotExtTestNocase = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f5) => !f5.startsWith(".") && f5.toLowerCase().endsWith(ext2);
    };
    starDotExtTestNocaseDot = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f5) => f5.toLowerCase().endsWith(ext2);
    };
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = (f5) => !f5.startsWith(".") && f5.includes(".");
    starDotStarTestDot = (f5) => f5 !== "." && f5 !== ".." && f5.includes(".");
    dotStarRE = /^\.\*+$/;
    dotStarTest = (f5) => f5 !== "." && f5 !== ".." && f5.startsWith(".");
    starRE = /^\*+$/;
    starTest = (f5) => f5.length !== 0 && !f5.startsWith(".");
    starTestDot = (f5) => f5.length !== 0 && f5 !== "." && f5 !== "..";
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
    };
    qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
    };
    qmarksTestDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
    };
    qmarksTest = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
    };
    qmarksTestNoExt = ([$0]) => {
      const len = $0.length;
      return (f5) => f5.length === len && !f5.startsWith(".");
    };
    qmarksTestNoExtDot = ([$0]) => {
      const len = $0.length;
      return (f5) => f5.length === len && f5 !== "." && f5 !== "..";
    };
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path3 = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep = defaultPlatform === "win32" ? path3.win32.sep : path3.posix.sep;
    minimatch.sep = sep;
    GLOBSTAR = Symbol("globstar **");
    minimatch.GLOBSTAR = GLOBSTAR;
    plTypes = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    qmark = "[^/]";
    star = qmark + "*?";
    twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    charSet = (s4) => s4.split("").reduce((set, c3) => {
      set[c3] = true;
      return set;
    }, {});
    reSpecials = charSet("().*{}+?[]^$\\!");
    addPatternStartSet = charSet("[.(");
    filter = (pattern, options = {}) => (p3) => minimatch(p3, pattern, options);
    minimatch.filter = filter;
    ext = (a3, b3 = {}) => Object.assign({}, a3, b3);
    defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m4 = (p3, pattern, options = {}) => orig(p3, pattern, ext(def, options));
      return Object.assign(m4, {
        Minimatch: class Minimatch extends orig.Minimatch {
          constructor(pattern, options = {}) {
            super(pattern, ext(def, options));
          }
          static defaults(options) {
            return orig.defaults(ext(def, options)).Minimatch;
          }
        },
        unescape: (s4, options = {}) => orig.unescape(s4, ext(def, options)),
        escape: (s4, options = {}) => orig.escape(s4, ext(def, options)),
        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
        defaults: (options) => orig.defaults(ext(def, options)),
        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
        sep: orig.sep,
        GLOBSTAR
      });
    };
    minimatch.defaults = defaults;
    braceExpand = (pattern, options = {}) => {
      assertValidPattern(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return (0, import_brace_expansion.default)(pattern);
    };
    minimatch.braceExpand = braceExpand;
    MAX_PATTERN_LENGTH = 1024 * 64;
    assertValidPattern = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError("pattern is too long");
      }
    };
    makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
    minimatch.makeRe = makeRe;
    match = (list, pattern, options = {}) => {
      const mm = new Minimatch(pattern, options);
      list = list.filter((f5) => mm.match(f5));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    minimatch.match = match;
    globUnescape = (s4) => s4.replace(/\\(.)/g, "$1");
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    Minimatch = class {
      options;
      set;
      pattern;
      windowsPathsNoEscape;
      nonegate;
      negate;
      comment;
      empty;
      preserveMultipleSlashes;
      partial;
      globSet;
      globParts;
      nocase;
      isWindows;
      platform;
      windowsNoMagicRoot;
      regexp;
      constructor(pattern, options = {}) {
        assertValidPattern(pattern);
        options = options || {};
        this.options = options;
        this.pattern = pattern;
        this.platform = options.platform || defaultPlatform;
        this.isWindows = this.platform === "win32";
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        this.make();
      }
      hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
          return true;
        }
        for (const pattern of this.set) {
          for (const part of pattern) {
            if (typeof part !== "string")
              return true;
          }
        }
        return false;
      }
      debug(..._3) {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        this.globSet = [...new Set(this.braceExpand())];
        if (options.debug) {
          this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        const rawGlobParts = this.globSet.map((s4) => this.slashSplit(s4));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s4, _3, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s4[0] === "" && s4[1] === "" && (s4[2] === "?" || !globMagic.test(s4[2])) && !globMagic.test(s4[3]);
            const isDrive = /^[a-z]:/i.test(s4[0]);
            if (isUNC) {
              return [...s4.slice(0, 4), ...s4.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s4[0], ...s4.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s4.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s4) => s4.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i4 = 0; i4 < this.set.length; i4++) {
            const p3 = this.set[i4];
            if (p3[0] === "" && p3[1] === "" && this.globParts[i4][2] === "?" && typeof p3[3] === "string" && /^[a-z]:$/i.test(p3[3])) {
              p3[2] = "?";
            }
          }
        }
        this.debug(this.pattern, this.set);
      }
      // various transforms to equivalent pattern sets that are
      // faster to process in a filesystem walk.  The goal is to
      // eliminate what we can, and push all ** patterns as far
      // to the right as possible, even if it increases the number
      // of patterns that we have to process.
      preprocess(globParts) {
        if (this.options.noglobstar) {
          for (let i4 = 0; i4 < globParts.length; i4++) {
            for (let j3 = 0; j3 < globParts[i4].length; j3++) {
              if (globParts[i4][j3] === "**") {
                globParts[i4][j3] = "*";
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          globParts = this.firstPhasePreProcess(globParts);
          globParts = this.secondPhasePreProcess(globParts);
        } else if (optimizationLevel >= 1) {
          globParts = this.levelOneOptimize(globParts);
        } else {
          globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
      }
      // just get rid of adjascent ** portions
      adjascentGlobstarOptimize(globParts) {
        return globParts.map((parts) => {
          let gs = -1;
          while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
            let i4 = gs;
            while (parts[i4 + 1] === "**") {
              i4++;
            }
            if (i4 !== gs) {
              parts.splice(gs, i4 - gs);
            }
          }
          return parts;
        });
      }
      // get rid of adjascent ** and resolve .. portions
      levelOneOptimize(globParts) {
        return globParts.map((parts) => {
          parts = parts.reduce((set, part) => {
            const prev = set[set.length - 1];
            if (part === "**" && prev === "**") {
              return set;
            }
            if (part === "..") {
              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
                set.pop();
                return set;
              }
            }
            set.push(part);
            return set;
          }, []);
          return parts.length === 0 ? [""] : parts;
        });
      }
      levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
          parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
          didSomething = false;
          if (!this.preserveMultipleSlashes) {
            for (let i4 = 1; i4 < parts.length - 1; i4++) {
              const p3 = parts[i4];
              if (i4 === 1 && p3 === "" && parts[0] === "")
                continue;
              if (p3 === "." || p3 === "") {
                didSomething = true;
                parts.splice(i4, 1);
                i4--;
              }
            }
            if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
              didSomething = true;
              parts.pop();
            }
          }
          let dd = 0;
          while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
            const p3 = parts[dd - 1];
            if (p3 && p3 !== "." && p3 !== ".." && p3 !== "**") {
              didSomething = true;
              parts.splice(dd - 1, 2);
              dd -= 2;
            }
          }
        } while (didSomething);
        return parts.length === 0 ? [""] : parts;
      }
      // First phase: single-pattern processing
      // <pre> is 1 or more portions
      // <rest> is 1 or more portions
      // <p> is any portion other than ., .., '', or **
      // <e> is . or ''
      //
      // **/.. is *brutal* for filesystem walking performance, because
      // it effectively resets the recursive walk each time it occurs,
      // and ** cannot be reduced out by a .. pattern part like a regexp
      // or most strings (other than .., ., and '') can be.
      //
      // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
      // <pre>/<e>/<rest> -> <pre>/<rest>
      // <pre>/<p>/../<rest> -> <pre>/<rest>
      // **/**/<rest> -> **/<rest>
      //
      // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
      // this WOULD be allowed if ** did follow symlinks, or * didn't
      firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
          didSomething = false;
          for (let parts of globParts) {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
              let gss = gs;
              while (parts[gss + 1] === "**") {
                gss++;
              }
              if (gss > gs) {
                parts.splice(gs + 1, gss - gs);
              }
              let next = parts[gs + 1];
              const p3 = parts[gs + 2];
              const p22 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p3 || p3 === "." || p3 === ".." || !p22 || p22 === "." || p22 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other = parts.slice(0);
              other[gs] = "**";
              globParts.push(other);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i4 = 1; i4 < parts.length - 1; i4++) {
                const p3 = parts[i4];
                if (i4 === 1 && p3 === "" && parts[0] === "")
                  continue;
                if (p3 === "." || p3 === "") {
                  didSomething = true;
                  parts.splice(i4, 1);
                  i4--;
                }
              }
              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
                didSomething = true;
                parts.pop();
              }
            }
            let dd = 0;
            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
              const p3 = parts[dd - 1];
              if (p3 && p3 !== "." && p3 !== ".." && p3 !== "**") {
                didSomething = true;
                const needDot = dd === 1 && parts[dd + 1] === "**";
                const splin = needDot ? ["."] : [];
                parts.splice(dd - 1, 2, ...splin);
                if (parts.length === 0)
                  parts.push("");
                dd -= 2;
              }
            }
          }
        } while (didSomething);
        return globParts;
      }
      // second phase: multi-pattern dedupes
      // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
      // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
      // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
      //
      // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
      // ^-- not valid because ** doens't follow symlinks
      secondPhasePreProcess(globParts) {
        for (let i4 = 0; i4 < globParts.length - 1; i4++) {
          for (let j3 = i4 + 1; j3 < globParts.length; j3++) {
            const matched = this.partsMatch(globParts[i4], globParts[j3], !this.preserveMultipleSlashes);
            if (!matched)
              continue;
            globParts[i4] = matched;
            globParts[j3] = [];
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a3, b3, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a3.length && bi < b3.length) {
          if (a3[ai] === b3[bi]) {
            result.push(which === "b" ? b3[bi] : a3[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a3[ai] === "**" && b3[bi] === a3[ai + 1]) {
            result.push(a3[ai]);
            ai++;
          } else if (emptyGSMatch && b3[bi] === "**" && a3[ai] === b3[bi + 1]) {
            result.push(b3[bi]);
            bi++;
          } else if (a3[ai] === "*" && b3[bi] && (this.options.dot || !b3[bi].startsWith(".")) && b3[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a3[ai]);
            ai++;
            bi++;
          } else if (b3[bi] === "*" && a3[ai] && (this.options.dot || !a3[ai].startsWith(".")) && a3[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b3[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a3.length === b3.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial = false) {
        const options = this.options;
        if (this.isWindows) {
          const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
          const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
          if (fileUNC && patternUNC) {
            const fd = file[3];
            const pd = pattern[3];
            if (fd.toLowerCase() === pd.toLowerCase()) {
              file[3] = pd;
            }
          } else if (patternUNC && typeof file[0] === "string") {
            const pd = pattern[3];
            const fd = file[0];
            if (pd.toLowerCase() === fd.toLowerCase()) {
              pattern[3] = fd;
              pattern = pattern.slice(3);
            }
          } else if (fileUNC && typeof pattern[0] === "string") {
            const fd = file[3];
            if (fd.toLowerCase() === pattern[0].toLowerCase()) {
              pattern[0] = fd;
              file = file.slice(3);
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          file = this.levelTwoFileOptimize(file);
        }
        this.debug("matchOne", this, { file, pattern });
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p3 = pattern[pi];
          var f5 = file[fi];
          this.debug(pattern, p3, f5);
          if (p3 === false) {
            return false;
          }
          if (p3 === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p3, f5]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) {
                return true;
              }
            }
            return false;
          }
          let hit;
          if (typeof p3 === "string") {
            hit = f5 === p3;
            this.debug("string match", p3, f5, hit);
          } else {
            hit = p3.test(f5);
            this.debug("pattern match", p3, f5, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        } else {
          throw new Error("wtf?");
        }
      }
      braceExpand() {
        return braceExpand(this.pattern, this.options);
      }
      parse(pattern) {
        assertValidPattern(pattern);
        const options = this.options;
        if (pattern === "**")
          return GLOBSTAR;
        if (pattern === "")
          return "";
        let m4;
        let fastTest = null;
        if (m4 = pattern.match(starRE)) {
          fastTest = options.dot ? starTestDot : starTest;
        } else if (m4 = pattern.match(starDotExtRE)) {
          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m4[1]);
        } else if (m4 = pattern.match(qmarksRE)) {
          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m4);
        } else if (m4 = pattern.match(starDotStarRE)) {
          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m4 = pattern.match(dotStarRE)) {
          fastTest = dotStarTest;
        }
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar = false;
        let uflag = false;
        let pl;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p3) => p3.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star;
                hasMagic = true;
                break;
              case "?":
                re += qmark;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i4 = 0, c3; i4 < pattern.length && (c3 = pattern.charAt(i4)); i4++) {
          this.debug("%s	%s %s %j", pattern, i4, re, c3);
          if (escaping) {
            if (c3 === "/") {
              return false;
            }
            if (reSpecials[c3]) {
              re += "\\";
            }
            re += c3;
            escaping = false;
            continue;
          }
          switch (c3) {
            // Should already be path-split by now.
            /* c8 ignore start */
            case "/": {
              return false;
            }
            /* c8 ignore stop */
            case "\\":
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i4, re, c3);
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c3;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i4 - 1,
                reStart: re.length,
                open: plTypes[stateChar].open,
                close: plTypes[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i4 + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i4 + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              const [src, needUflag, consumed, magic] = parseClass(pattern, i4);
              if (consumed) {
                re += src;
                uflag = uflag || needUflag;
                i4 += consumed - 1;
                hasMagic = hasMagic || magic;
              } else {
                re += "\\[";
              }
              continue;
            case "]":
              re += "\\" + c3;
              continue;
            default:
              clearStateChar();
              re += regExpEscape(c3);
              break;
          }
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug(this.pattern, "setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t4 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t4 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet[re.charAt(0)];
        for (let n3 = negativeLists.length - 1; n3 > -1; n3--) {
          const nl = negativeLists[n3];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i4 = 0; i4 < openParensBefore; i4++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape(re);
        }
        const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
        try {
          const ext2 = fastTest ? {
            _glob: pattern,
            _src: re,
            test: fastTest
          } : {
            _glob: pattern,
            _src: re
          };
          return Object.assign(new RegExp("^" + re + "$", flags), ext2);
        } catch (er) {
          this.debug("invalid regexp", er);
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false)
          return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          const pp = pattern.map((p3) => typeof p3 === "string" ? regExpEscape(p3) : p3 === GLOBSTAR ? GLOBSTAR : p3._src);
          pp.forEach((p3, i4) => {
            const next = pp[i4 + 1];
            const prev = pp[i4 - 1];
            if (p3 !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i4] = twoStar;
              }
            } else if (next === void 0) {
              pp[i4 - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i4 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i4 + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p3) => p3 !== GLOBSTAR).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate)
          re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      slashSplit(p3) {
        if (this.preserveMultipleSlashes) {
          return p3.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p3)) {
          return ["", ...p3.split(/\/+/)];
        } else {
          return p3.split(/\/+/);
        }
      }
      match(f5, partial = this.partial) {
        this.debug("match", f5, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f5 === "";
        }
        if (f5 === "/" && partial) {
          return true;
        }
        const options = this.options;
        if (this.isWindows) {
          f5 = f5.split("\\").join("/");
        }
        const ff = this.slashSplit(f5);
        this.debug(this.pattern, "split", ff);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename = ff[ff.length - 1];
        if (!filename) {
          for (let i4 = ff.length - 2; !filename && i4 >= 0; i4--) {
            filename = ff[i4];
          }
        }
        for (let i4 = 0; i4 < set.length; i4++) {
          const pattern = set[i4];
          let file = ff;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) {
              return true;
            }
            return !this.negate;
          }
        }
        if (options.flipNegate) {
          return false;
        }
        return this.negate;
      }
      static defaults(def) {
        return minimatch.defaults(def).Minimatch;
      }
    };
    minimatch.Minimatch = Minimatch;
    minimatch.escape = escape;
    minimatch.unescape = unescape2;
  }
});

// src/cli/commands/mysqlIntrospect.ts
var mysqlIntrospect_exports = {};
__export(mysqlIntrospect_exports, {
  mysqlPushIntrospect: () => mysqlPushIntrospect
});
var import_hanji9, mysqlPushIntrospect;
var init_mysqlIntrospect = __esm({
  "src/cli/commands/mysqlIntrospect.ts"() {
    "use strict";
    import_hanji9 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_mysqlSerializer();
    init_views();
    mysqlPushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji9.renderWithTask)(
        progress,
        fromDatabase(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/cli/commands/singlestoreIntrospect.ts
var singlestoreIntrospect_exports = {};
__export(singlestoreIntrospect_exports, {
  singlestorePushIntrospect: () => singlestorePushIntrospect
});
var import_hanji10, singlestorePushIntrospect;
var init_singlestoreIntrospect = __esm({
  "src/cli/commands/singlestoreIntrospect.ts"() {
    "use strict";
    import_hanji10 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_singlestoreSerializer();
    init_views();
    singlestorePushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji10.renderWithTask)(
        progress,
        fromDatabase4(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/cli/commands/pgIntrospect.ts
var pgIntrospect_exports = {};
__export(pgIntrospect_exports, {
  pgPushIntrospect: () => pgPushIntrospect
});
var import_hanji11, pgPushIntrospect;
var init_pgIntrospect = __esm({
  "src/cli/commands/pgIntrospect.ts"() {
    "use strict";
    import_hanji11 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_pgSerializer();
    init_views();
    pgPushIntrospect = async (db, filters, schemaFilters, entities, tsSchema) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji11.renderWithTask)(
        progress,
        fromDatabase2(db, filter2, schemaFilters, entities, void 0, tsSchema)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/introspect-sqlite.ts
var import_casing2, sqliteImportsList, indexName4, objToStatement2, relations, escapeColumnKey, withCasing, dbColumnName, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column6, createTableColumns, createTableIndexes, createTableUniques, createTableChecks, createTablePKs, createTableFKs;
var init_introspect_sqlite = __esm({
  "src/introspect-sqlite.ts"() {
    "use strict";
    import_casing2 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    sqliteImportsList = /* @__PURE__ */ new Set([
      "sqliteTable",
      "integer",
      "real",
      "text",
      "numeric",
      "blob"
    ]);
    indexName4 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    objToStatement2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
      statement += " }";
      return statement;
    };
    relations = /* @__PURE__ */ new Set();
    escapeColumnKey = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    withCasing = (value, casing2) => {
      if (casing2 === "preserve") {
        return escapeColumnKey(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey(value.camelCase());
      }
      return value;
    };
    dbColumnName = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing2.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript = (schema6, casing2) => {
      Object.values(schema6.tables).forEach((table6) => {
        Object.values(table6.foreignKeys).forEach((fk5) => {
          const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
          relations.add(relation);
        });
      });
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          const checkImports = Object.values(it.checkConstraints).map(
            (it2) => "check"
          );
          res.sqlite.push(...idxImports);
          res.sqlite.push(...fkImpots);
          res.sqlite.push(...pkImports);
          res.sqlite.push(...uniqueImports);
          res.sqlite.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            return col.type;
          }).filter((type) => {
            return sqliteImportsList.has(type);
          });
          res.sqlite.push(...columnImports);
          return res;
        },
        { sqlite: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        imports.sqlite.push("sqliteView");
        const columnImports = Object.values(it.columns).map((col) => {
          return col.type;
        }).filter((type) => {
          return sqliteImportsList.has(type);
        });
        imports.sqlite.push(...columnImports);
      });
      const tableStatements = Object.values(schema6.tables).map((table6) => {
        const func = "sqliteTable";
        let statement = "";
        if (imports.sqlite.includes(withCasing(table6.name, casing2))) {
          statement = `// Table name is in conflict with ${withCasing(
            table6.name,
            casing2
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing(table6.name, casing2)} = ${func}("${table6.name}", {
`;
        statement += createTableColumns(
          Object.values(table6.columns),
          Object.values(table6.foreignKeys),
          casing2
        );
        statement += "}";
        const filteredFKs = Object.values(table6.foreignKeys).filter((it) => {
          return it.columnsFrom.length > 1 || isSelf(it);
        });
        if (Object.keys(table6.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes(
            table6.name,
            Object.values(table6.indexes),
            casing2
          );
          statement += createTableFKs(Object.values(filteredFKs), casing2);
          statement += createTablePKs(
            Object.values(table6.compositePrimaryKeys),
            casing2
          );
          statement += createTableUniques(
            Object.values(table6.uniqueConstraints),
            casing2
          );
          statement += createTableChecks(
            Object.values(table6.checkConstraints),
            casing2
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((view5) => {
        var _a2;
        const func = "sqliteView";
        let statement = "";
        if (imports.sqlite.includes(withCasing(view5.name, casing2))) {
          statement = `// Table name is in conflict with ${withCasing(
            view5.name,
            casing2
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing(view5.name, casing2)} = ${func}("${view5.name}", {
`;
        statement += createTableColumns(
          Object.values(view5.columns),
          [],
          casing2
        );
        statement += "})";
        statement += `.as(sql\`${(_a2 = view5.definition) == null ? void 0 : _a2.replaceAll("`", "\\`")}\`);`;
        return statement;
      });
      const uniqueSqliteImports = [
        "sqliteTable",
        "AnySQLiteColumn",
        ...new Set(imports.sqlite)
      ];
      const importsTs = `import { ${uniqueSqliteImports.join(
        ", "
      )} } from "drizzle-orm/sqlite-core"
  import { sql } from "drizzle-orm"

`;
      let decalrations = tableStatements.join("\n\n");
      decalrations += "\n\n";
      decalrations += viewsStatements.join("\n\n");
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing(it.name, casing2)).join(",")}
    }
  `;
      return { file, imports: importsTs, decalrations, schemaEntry };
    };
    isCyclic = (fk5) => {
      const key = `${fk5.tableFrom}-${fk5.tableTo}`;
      const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
      return relations.has(key) && relations.has(reverse);
    };
    isSelf = (fk5) => {
      return fk5.tableFrom === fk5.tableTo;
    };
    mapColumnDefault = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("(") && defaultValue.endsWith(")")) {
        return `sql\`${defaultValue}\``;
      }
      if (defaultValue === "NULL") {
        return `sql\`NULL\``;
      }
      if (typeof defaultValue === "string") {
        return defaultValue.substring(1, defaultValue.length - 1).replaceAll('"', '\\"').replaceAll("''", "'");
      }
      return defaultValue;
    };
    column6 = (type, name, defaultValue, autoincrement, casing2) => {
      let lowered = type;
      casing2 = casing2;
      if (lowered === "integer") {
        let out = `${withCasing(name, casing2)}: integer(${dbColumnName({ name, casing: casing2 })})`;
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${withCasing(name, casing2)}: real(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("text")) {
        const match2 = lowered.match(/\d+/);
        let out;
        if (match2) {
          out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2, withMode: true })}{ length: ${match2[0]} })`;
        } else {
          out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2 })})`;
        }
        out += defaultValue ? `.default("${mapColumnDefault(defaultValue)}")` : "";
        return out;
      }
      if (lowered === "blob") {
        let out = `${withCasing(name, casing2)}: blob(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered === "numeric") {
        let out = `${withCasing(name, casing2)}: numeric(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns = (columns, fks, casing2) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        statement += "	";
        statement += column6(it.type, it.name, it.default, it.autoincrement, casing2);
        statement += it.primaryKey ? `.primaryKey(${it.autoincrement ? "{ autoIncrement: true }" : ""})` : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(/`/g, "\\`").slice(1, -1)}\`, { mode: "${it.generated.type}" })` : "";
        const fks2 = fkByColumnName[it.name];
        if (fks2) {
          const fksStatement = fks2.map((it2) => {
            const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
            const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
            const params = { onDelete, onUpdate };
            const typeSuffix = isCyclic(it2) ? ": AnySQLiteColumn" : "";
            const paramsStr = objToStatement2(params);
            if (paramsStr) {
              return `.references(()${typeSuffix} => ${withCasing(
                it2.tableTo,
                casing2
              )}.${withCasing(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
            }
            return `.references(()${typeSuffix} => ${withCasing(
              it2.tableTo,
              casing2
            )}.${withCasing(it2.columnsTo[0], casing2)})`;
          }).join("");
          statement += fksStatement;
        }
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = withCasing(idxKey, casing2);
        const indexGeneratedName = indexName4(tableName, it.columns);
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        const idxKey = withCasing(it.name, casing2);
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableChecks = (checks, casing2) => {
      let statement = "";
      checks.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTablePKs = (pks, casing2) => {
      let statement = "";
      pks.forEach((it, i4) => {
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c3) => {
          return `table.${withCasing(c3, casing2)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += ")";
      });
      return statement;
    };
    createTableFKs = (fks, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const isSelf5 = it.tableTo === it.tableFrom;
        const tableTo = isSelf5 ? "table" : `${withCasing(it.tableTo, casing2)}`;
        statement += `
	`;
        statement += `foreignKey(() => ({
`;
        statement += `			columns: [${it.columnsFrom.map((i4) => `table.${withCasing(i4, casing2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing(i4, casing2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		}))`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/cli/commands/sqliteIntrospect.ts
var sqliteIntrospect_exports = {};
__export(sqliteIntrospect_exports, {
  sqliteIntrospect: () => sqliteIntrospect,
  sqlitePushIntrospect: () => sqlitePushIntrospect
});
var import_hanji12, sqliteIntrospect, sqlitePushIntrospect;
var init_sqliteIntrospect = __esm({
  "src/cli/commands/sqliteIntrospect.ts"() {
    "use strict";
    import_hanji12 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_introspect_sqlite();
    init_sqliteSerializer();
    init_views();
    sqliteIntrospect = async (credentials2, filters, casing2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToSQLite2(credentials2);
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress();
      const res = await (0, import_hanji12.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      return { schema: schema6, ts };
    };
    sqlitePushIntrospect = async (db, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji12.renderWithTask)(progress, fromDatabase3(db, filter2));
      const schema6 = { id: originUUID, prevId: "", ...res };
      return { schema: schema6 };
    };
  }
});

// src/cli/commands/push.ts
var push_exports = {};
__export(push_exports, {
  libSQLPush: () => libSQLPush,
  mysqlPush: () => mysqlPush,
  pgPush: () => pgPush,
  singlestorePush: () => singlestorePush,
  sqlitePush: () => sqlitePush
});
var import_crypto6, import_hanji13, mysqlPush, singlestorePush, pgPush, sqlitePush, libSQLPush;
var init_push = __esm({
  "src/cli/commands/push.ts"() {
    "use strict";
    init_source();
    import_crypto6 = require("crypto");
    import_hanji13 = __toESM(require_hanji());
    init_serializer();
    init_sqlgenerator();
    init_selector_ui();
    init_outputs();
    init_libSqlPushUtils();
    init_mysqlPushUtils();
    init_pgPushUtils();
    init_singlestorePushUtils();
    init_sqlitePushUtils();
    mysqlPush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
      const { db, database } = await connectToMySQL2(credentials2);
      const { schema: schema6 } = await mysqlPushIntrospect2(db, database, tablesFilter);
      const { prepareMySQLPush: prepareMySQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareMySQLPush2(schemaPath, schema6, casing2);
      const filteredStatements = filterStatements(
        statements.statements ?? [],
        statements.validatedCur,
        statements.validatedPrev
      );
      try {
        if (filteredStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            tablesToTruncate,
            infoToPrint
          } = await logSuggestionsAndReturn2(
            db,
            filteredStatements,
            statements.validatedCur
          );
          const filteredSqlStatements = fromJson(filteredStatements, "mysql");
          const uniqueSqlStatementsToExecute = [];
          statementsToExecute.forEach((ss) => {
            if (!uniqueSqlStatementsToExecute.includes(ss)) {
              uniqueSqlStatementsToExecute.push(ss);
            }
          });
          const uniqueFilteredSqlStatements = [];
          filteredSqlStatements.forEach((ss) => {
            if (!uniqueFilteredSqlStatements.includes(ss)) {
              uniqueFilteredSqlStatements.push(ss);
            }
          });
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(
              [...uniqueSqlStatementsToExecute, ...uniqueFilteredSqlStatements].map((s4) => source_default.blue(s4)).join("\n")
            );
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of uniqueSqlStatementsToExecute) {
            await db.query(dStmnt);
          }
          for (const statement of uniqueFilteredSqlStatements) {
            await db.query(statement);
          }
          if (filteredStatements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e4) {
        console.log(e4);
      }
    };
    singlestorePush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
      const { db, database } = await connectToSingleStore2(credentials2);
      const { schema: schema6 } = await singlestorePushIntrospect2(
        db,
        database,
        tablesFilter
      );
      const { prepareSingleStorePush: prepareSingleStorePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareSingleStorePush2(schemaPath, schema6, casing2);
      const filteredStatements = filterStatements2(
        statements.statements ?? [],
        statements.validatedCur,
        statements.validatedPrev
      );
      try {
        if (filteredStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            tablesToTruncate,
            infoToPrint,
            schemasToRemove
          } = await logSuggestionsAndReturn3(
            db,
            filteredStatements,
            statements.validatedCur,
            statements.validatedPrev
          );
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of statementsToExecute) {
            await db.query(dStmnt);
          }
          if (filteredStatements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e4) {
        console.log(e4);
      }
    };
    pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force, casing2) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
      const db = await preparePostgresDB2(credentials2);
      const serialized = await serializePg(schemaPath, casing2, schemasFilter);
      const { schema: schema6 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities, serialized);
      const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await preparePgPush2(
        { id: (0, import_crypto6.randomUUID)(), prevId: schema6.id, ...serialized },
        schema6
      );
      try {
        if (statements.sqlStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            matViewsToRemove,
            tablesToTruncate,
            infoToPrint,
            schemasToRemove
          } = await pgSuggestions(db, statements.statements);
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}${matViewsToRemove.length > 0 ? ` remove ${matViewsToRemove.length} ${matViewsToRemove.length > 1 ? "materialized views" : "materialize view"},` : " "}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of statementsToExecute) {
            await db.query(dStmnt);
          }
          if (statements.statements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e4) {
        console.error(e4);
      }
    };
    sqlitePush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
      const db = await connectToSQLite2(credentials2);
      const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
      const { prepareSQLitePush: prepareSQLitePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareSQLitePush2(schemaPath, schema6, casing2);
      if (statements.sqlStatements.length === 0) {
        (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
      } else {
        const {
          shouldAskForApprove,
          statementsToExecute,
          columnsToRemove,
          tablesToRemove,
          tablesToTruncate,
          infoToPrint,
          schemasToRemove
        } = await logSuggestionsAndReturn(
          db,
          statements.statements,
          statements.squashedPrev,
          statements.squashedCur,
          statements.meta
        );
        if (verbose && statementsToExecute.length > 0) {
          console.log();
          console.log(
            withStyle.warning("You are about to execute current statements:")
          );
          console.log();
          console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
          console.log();
        }
        if (!force && strict) {
          if (!shouldAskForApprove) {
            const { status, data } = await (0, import_hanji13.render)(
              new Select(["No, abort", `Yes, I want to execute all statements`])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
        }
        if (!force && shouldAskForApprove) {
          console.log(withStyle.warning("Found data-loss statements:"));
          console.log(infoToPrint.join("\n"));
          console.log();
          console.log(
            source_default.red.bold(
              "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
            )
          );
          console.log(source_default.white("Do you still want to push changes?"));
          const { status, data } = await (0, import_hanji13.render)(
            new Select([
              "No, abort",
              `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
            ])
          );
          if ((data == null ? void 0 : data.index) === 0) {
            (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
            process.exit(0);
          }
        }
        if (statementsToExecute.length === 0) {
          (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
        } else {
          const isNotD1 = !("driver" in credentials2 && credentials2.driver === "d1-http");
          isNotD1 ?? await db.run("begin");
          try {
            for (const dStmnt of statementsToExecute) {
              await db.run(dStmnt);
            }
            isNotD1 ?? await db.run("commit");
          } catch (e4) {
            console.error(e4);
            isNotD1 ?? await db.run("rollback");
            process.exit(1);
          }
          (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
        }
      }
    };
    libSQLPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
      const db = await connectToLibSQL2(credentials2);
      const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
      const { prepareLibSQLPush: prepareLibSQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareLibSQLPush2(schemaPath, schema6, casing2);
      if (statements.sqlStatements.length === 0) {
        (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
      } else {
        const {
          shouldAskForApprove,
          statementsToExecute,
          columnsToRemove,
          tablesToRemove,
          tablesToTruncate,
          infoToPrint
        } = await libSqlLogSuggestionsAndReturn(
          db,
          statements.statements,
          statements.squashedPrev,
          statements.squashedCur,
          statements.meta
        );
        if (verbose && statementsToExecute.length > 0) {
          console.log();
          console.log(
            withStyle.warning("You are about to execute current statements:")
          );
          console.log();
          console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
          console.log();
        }
        if (!force && strict) {
          if (!shouldAskForApprove) {
            const { status, data } = await (0, import_hanji13.render)(
              new Select(["No, abort", `Yes, I want to execute all statements`])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
        }
        if (!force && shouldAskForApprove) {
          console.log(withStyle.warning("Found data-loss statements:"));
          console.log(infoToPrint.join("\n"));
          console.log();
          console.log(
            source_default.red.bold(
              "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
            )
          );
          console.log(source_default.white("Do you still want to push changes?"));
          const { status, data } = await (0, import_hanji13.render)(
            new Select([
              "No, abort",
              `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
            ])
          );
          if ((data == null ? void 0 : data.index) === 0) {
            (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
            process.exit(0);
          }
        }
        if (statementsToExecute.length === 0) {
          (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
        } else {
          await db.batchWithPragma(statementsToExecute);
          (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js
var require_pluralize = __commonJS({
  "../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js"(exports2, module2) {
    (function(root, pluralize) {
      if (typeof require === "function" && typeof exports2 === "object" && typeof module2 === "object") {
        module2.exports = pluralize();
      } else if (typeof define === "function" && define.amd) {
        define(function() {
          return pluralize();
        });
      } else {
        root.pluralize = pluralize();
      }
    })(exports2, function() {
      var pluralRules = [];
      var singularRules = [];
      var uncountables = {};
      var irregularPlurals = {};
      var irregularSingles = {};
      function sanitizeRule(rule) {
        if (typeof rule === "string") {
          return new RegExp("^" + rule + "$", "i");
        }
        return rule;
      }
      function restoreCase(word, token) {
        if (word === token) return token;
        if (word === word.toLowerCase()) return token.toLowerCase();
        if (word === word.toUpperCase()) return token.toUpperCase();
        if (word[0] === word[0].toUpperCase()) {
          return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
        }
        return token.toLowerCase();
      }
      function interpolate(str, args) {
        return str.replace(/\$(\d{1,2})/g, function(match2, index6) {
          return args[index6] || "";
        });
      }
      function replace(word, rule) {
        return word.replace(rule[0], function(match2, index6) {
          var result = interpolate(rule[1], arguments);
          if (match2 === "") {
            return restoreCase(word[index6 - 1], result);
          }
          return restoreCase(match2, result);
        });
      }
      function sanitizeWord(token, word, rules) {
        if (!token.length || uncountables.hasOwnProperty(token)) {
          return word;
        }
        var len = rules.length;
        while (len--) {
          var rule = rules[len];
          if (rule[0].test(word)) return replace(word, rule);
        }
        return word;
      }
      function replaceWord(replaceMap, keepMap, rules) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token)) {
            return restoreCase(word, token);
          }
          if (replaceMap.hasOwnProperty(token)) {
            return restoreCase(word, replaceMap[token]);
          }
          return sanitizeWord(token, word, rules);
        };
      }
      function checkWord(replaceMap, keepMap, rules, bool) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token)) return true;
          if (replaceMap.hasOwnProperty(token)) return false;
          return sanitizeWord(token, token, rules) === token;
        };
      }
      function pluralize(word, count, inclusive) {
        var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word);
        return (inclusive ? count + " " : "") + pluralized;
      }
      pluralize.plural = replaceWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize.isPlural = checkWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize.singular = replaceWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize.isSingular = checkWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize.addPluralRule = function(rule, replacement) {
        pluralRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize.addSingularRule = function(rule, replacement) {
        singularRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize.addUncountableRule = function(word) {
        if (typeof word === "string") {
          uncountables[word.toLowerCase()] = true;
          return;
        }
        pluralize.addPluralRule(word, "$0");
        pluralize.addSingularRule(word, "$0");
      };
      pluralize.addIrregularRule = function(single, plural2) {
        plural2 = plural2.toLowerCase();
        single = single.toLowerCase();
        irregularSingles[single] = plural2;
        irregularPlurals[plural2] = single;
      };
      [
        // Pronouns.
        ["I", "we"],
        ["me", "us"],
        ["he", "they"],
        ["she", "they"],
        ["them", "them"],
        ["myself", "ourselves"],
        ["yourself", "yourselves"],
        ["itself", "themselves"],
        ["herself", "themselves"],
        ["himself", "themselves"],
        ["themself", "themselves"],
        ["is", "are"],
        ["was", "were"],
        ["has", "have"],
        ["this", "these"],
        ["that", "those"],
        // Words ending in with a consonant and `o`.
        ["echo", "echoes"],
        ["dingo", "dingoes"],
        ["volcano", "volcanoes"],
        ["tornado", "tornadoes"],
        ["torpedo", "torpedoes"],
        // Ends with `us`.
        ["genus", "genera"],
        ["viscus", "viscera"],
        // Ends with `ma`.
        ["stigma", "stigmata"],
        ["stoma", "stomata"],
        ["dogma", "dogmata"],
        ["lemma", "lemmata"],
        ["schema", "schemata"],
        ["anathema", "anathemata"],
        // Other irregular rules.
        ["ox", "oxen"],
        ["axe", "axes"],
        ["die", "dice"],
        ["yes", "yeses"],
        ["foot", "feet"],
        ["eave", "eaves"],
        ["goose", "geese"],
        ["tooth", "teeth"],
        ["quiz", "quizzes"],
        ["human", "humans"],
        ["proof", "proofs"],
        ["carve", "carves"],
        ["valve", "valves"],
        ["looey", "looies"],
        ["thief", "thieves"],
        ["groove", "grooves"],
        ["pickaxe", "pickaxes"],
        ["passerby", "passersby"]
      ].forEach(function(rule) {
        return pluralize.addIrregularRule(rule[0], rule[1]);
      });
      [
        [/s?$/i, "s"],
        [/[^\u0000-\u007F]$/i, "$0"],
        [/([^aeiou]ese)$/i, "$1"],
        [/(ax|test)is$/i, "$1es"],
        [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, "$1es"],
        [/(e[mn]u)s?$/i, "$1s"],
        [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, "$1"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1i"],
        [/(alumn|alg|vertebr)(?:a|ae)$/i, "$1ae"],
        [/(seraph|cherub)(?:im)?$/i, "$1im"],
        [/(her|at|gr)o$/i, "$1oes"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, "$1a"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, "$1a"],
        [/sis$/i, "ses"],
        [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, "$1$2ves"],
        [/([^aeiouy]|qu)y$/i, "$1ies"],
        [/([^ch][ieo][ln])ey$/i, "$1ies"],
        [/(x|ch|ss|sh|zz)$/i, "$1es"],
        [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, "$1ices"],
        [/\b((?:tit)?m|l)(?:ice|ouse)$/i, "$1ice"],
        [/(pe)(?:rson|ople)$/i, "$1ople"],
        [/(child)(?:ren)?$/i, "$1ren"],
        [/eaux$/i, "$0"],
        [/m[ae]n$/i, "men"],
        ["thou", "you"]
      ].forEach(function(rule) {
        return pluralize.addPluralRule(rule[0], rule[1]);
      });
      [
        [/s$/i, ""],
        [/(ss)$/i, "$1"],
        [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, "$1fe"],
        [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, "$1f"],
        [/ies$/i, "y"],
        [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, "$1ie"],
        [/\b(mon|smil)ies$/i, "$1ey"],
        [/\b((?:tit)?m|l)ice$/i, "$1ouse"],
        [/(seraph|cherub)im$/i, "$1"],
        [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, "$1"],
        [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, "$1sis"],
        [/(movie|twelve|abuse|e[mn]u)s$/i, "$1"],
        [/(test)(?:is|es)$/i, "$1is"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1us"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, "$1um"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, "$1on"],
        [/(alumn|alg|vertebr)ae$/i, "$1a"],
        [/(cod|mur|sil|vert|ind)ices$/i, "$1ex"],
        [/(matr|append)ices$/i, "$1ix"],
        [/(pe)(rson|ople)$/i, "$1rson"],
        [/(child)ren$/i, "$1"],
        [/(eau)x?$/i, "$1"],
        [/men$/i, "man"]
      ].forEach(function(rule) {
        return pluralize.addSingularRule(rule[0], rule[1]);
      });
      [
        // Singular words with no plurals.
        "adulthood",
        "advice",
        "agenda",
        "aid",
        "aircraft",
        "alcohol",
        "ammo",
        "analytics",
        "anime",
        "athletics",
        "audio",
        "bison",
        "blood",
        "bream",
        "buffalo",
        "butter",
        "carp",
        "cash",
        "chassis",
        "chess",
        "clothing",
        "cod",
        "commerce",
        "cooperation",
        "corps",
        "debris",
        "diabetes",
        "digestion",
        "elk",
        "energy",
        "equipment",
        "excretion",
        "expertise",
        "firmware",
        "flounder",
        "fun",
        "gallows",
        "garbage",
        "graffiti",
        "hardware",
        "headquarters",
        "health",
        "herpes",
        "highjinks",
        "homework",
        "housework",
        "information",
        "jeans",
        "justice",
        "kudos",
        "labour",
        "literature",
        "machinery",
        "mackerel",
        "mail",
        "media",
        "mews",
        "moose",
        "music",
        "mud",
        "manga",
        "news",
        "only",
        "personnel",
        "pike",
        "plankton",
        "pliers",
        "police",
        "pollution",
        "premises",
        "rain",
        "research",
        "rice",
        "salmon",
        "scissors",
        "series",
        "sewage",
        "shambles",
        "shrimp",
        "software",
        "species",
        "staff",
        "swine",
        "tennis",
        "traffic",
        "transportation",
        "trout",
        "tuna",
        "wealth",
        "welfare",
        "whiting",
        "wildebeest",
        "wildlife",
        "you",
        /pok[eé]mon$/i,
        // Regexes.
        /[^aeiou]ese$/i,
        // "chinese", "japanese"
        /deer$/i,
        // "deer", "reindeer"
        /fish$/i,
        // "fish", "blowfish", "angelfish"
        /measles$/i,
        /o[iu]s$/i,
        // "carnivorous"
        /pox$/i,
        // "chickpox", "smallpox"
        /sheep$/i
      ].forEach(pluralize.addUncountableRule);
      return pluralize;
    });
  }
});

// src/serializer/gelSerializer.ts
function stringFromDatabaseIdentityProperty2(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
}
var import_drizzle_orm9, import_gel_core, indexName5, trimChar2, fromDatabase5, defaultForColumn2, getColumnsInfoQuery2;
var init_gelSerializer = __esm({
  "src/serializer/gelSerializer.ts"() {
    "use strict";
    import_drizzle_orm9 = require("drizzle-orm");
    import_gel_core = require("drizzle-orm/gel-core");
    init_vector();
    init_outputs();
    init_utils2();
    init_utils4();
    indexName5 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    trimChar2 = (str, char) => {
      let start = 0;
      let end = str.length;
      while (start < end && str[start] === char) ++start;
      while (end > start && str[end - 1] === char) --end;
      return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
    };
    fromDatabase5 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
      const result = {};
      const policies = {};
      const internals = { tables: {} };
      const where = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
      const allTables = await db.query(
        `SELECT 
    n.nspname::text AS table_schema, 
    c.relname::text AS table_name, 
    CASE 
        WHEN c.relkind = 'r' THEN 'table'
        WHEN c.relkind = 'v' THEN 'view'
        WHEN c.relkind = 'm' THEN 'materialized_view'
    END AS type,
	c.relrowsecurity AS rls_enabled
FROM 
    pg_catalog.pg_class c
JOIN 
    pg_catalog.pg_namespace n ON n.oid::text = c.relnamespace::text
WHERE 
	c.relkind IN ('r', 'v', 'm') 
    ${where === "" ? "" : ` AND ${where}`};`
      );
      const schemas = new Set(allTables.map((it) => it.table_schema));
      const allSchemas = await db.query(`select s.nspname::text as table_schema
  from pg_catalog.pg_namespace s
  join pg_catalog.pg_user u on u.usesysid::text = s.nspowner::text
  where nspname not in ('information_schema', 'pg_catalog', 'public')
        and nspname::text not like 'pg_toast%'
        and nspname::text not like 'pg_temp_%'
  order by 1;`);
      allSchemas.forEach((item) => {
        if (schemaFilters.includes(item.table_schema)) {
          schemas.add(item.table_schema);
        }
      });
      let columnsCount = 0;
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let tableCount = 0;
      const sequencesToReturn = {};
      const all = allTables.filter((it) => it.type === "table").map((row) => {
        return new Promise(async (res, rej) => {
          var _a2, _b, _c, _d, _e, _f;
          const tableName = row.table_name;
          if (!tablesFilter(tableName)) return res("");
          tableCount += 1;
          const tableSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const indexToReturn = {};
            const foreignKeysToReturn = {};
            const primaryKeys = {};
            const tableResponse = await getColumnsInfoQuery2({ schema: tableSchema, table: tableName, db });
            columnsCount += tableResponse.length;
            if (progressCallback) {
              progressCallback("columns", columnsCount, "fetching");
            }
            const tableForeignKeys = await db.query(
              `SELECT
					    con.contype::text AS constraint_type,
					    nsp.nspname::text AS constraint_schema,
					    con.conname::text AS constraint_name,
					    rel.relname::text AS table_name,
					    att.attname::text AS column_name,
					    fnsp.nspname::text AS foreign_table_schema,
					    frel.relname::text AS foreign_table_name,
					    fatt.attname::text AS foreign_column_name,
					    CASE con.confupdtype
					      WHEN 'a' THEN 'NO ACTION'
					      WHEN 'r' THEN 'RESTRICT'
					      WHEN 'n' THEN 'SET NULL'
					      WHEN 'c' THEN 'CASCADE'
					      WHEN 'd' THEN 'SET DEFAULT'
					    END AS update_rule,
					    CASE con.confdeltype
					      WHEN 'a' THEN 'NO ACTION'
					      WHEN 'r' THEN 'RESTRICT'
					      WHEN 'n' THEN 'SET NULL'
					      WHEN 'c' THEN 'CASCADE'
					      WHEN 'd' THEN 'SET DEFAULT'
					    END AS delete_rule
					  FROM
					    pg_catalog.pg_constraint con
					    JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
					    JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
					    LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
					      AND att.attrelid = con.conrelid
					    LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
					    LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
					    LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
					      AND fatt.attrelid = con.confrelid
					  WHERE
					    nsp.nspname = '${tableSchema}'
					    AND rel.relname = '${tableName}'
					    AND con.contype IN ('f');`
            );
            foreignKeysCount += tableForeignKeys.length;
            if (progressCallback) {
              progressCallback("fks", foreignKeysCount, "fetching");
            }
            for (const fk5 of tableForeignKeys) {
              const columnFrom = fk5.column_name;
              const tableTo = fk5.foreign_table_name;
              const columnTo = fk5.foreign_column_name;
              const schemaTo = fk5.foreign_table_schema;
              const foreignKeyName = fk5.constraint_name;
              const onUpdate = (_a2 = fk5.update_rule) == null ? void 0 : _a2.toLowerCase();
              const onDelete = (_b = fk5.delete_rule) == null ? void 0 : _b.toLowerCase();
              if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
                foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
                foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
              } else {
                foreignKeysToReturn[foreignKeyName] = {
                  name: foreignKeyName,
                  tableFrom: tableName,
                  tableTo,
                  schemaTo,
                  columnsFrom: [columnFrom],
                  columnsTo: [columnTo],
                  onDelete,
                  onUpdate
                };
              }
              foreignKeysToReturn[foreignKeyName].columnsFrom = [
                ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
              ];
              foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
            }
            for (const columnResponse of tableResponse) {
              const columnName = columnResponse.column_name;
              if (columnName === "__type__") continue;
              const columnAdditionalDT = columnResponse.additional_dt;
              const columnDimensions = columnResponse.array_dimensions;
              const enumType2 = columnResponse.enum_name;
              let columnType = columnResponse.data_type;
              const defaultValueRes = columnResponse.column_default;
              const isGenerated = columnResponse.is_generated === "ALWAYS";
              const generationExpression = columnResponse.generation_expression;
              const isIdentity = columnResponse.is_identity === "YES";
              const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = columnResponse.identity_start;
              const identityIncrement = columnResponse.identity_increment;
              const identityMaximum = columnResponse.identity_maximum;
              const identityMinimum = columnResponse.identity_minimum;
              const identityCycle = columnResponse.identity_cycle === "YES";
              const identityName = columnResponse.seq_name;
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn2(columnResponse, internals, tableName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
                  columnTypeMapped += "[]";
                }
              }
              if (columnTypeMapped.includes("tuple<") || columnTypeMapped.includes("range")) continue;
              columnTypeMapped = trimChar2(columnTypeMapped, '"');
              columnTypeMapped = columnTypeMapped.replace("pg_catalog.", "");
              columnTypeMapped = columnTypeMapped.replace("float4[]", "real[]").replace("float8[]", "double precision[]").replace('"numeric"[]', "numeric[]").replace('"time"[]', "time without time zone[]").replace(
                "int2[]",
                "smallint[]"
              ).replace(
                "int4[]",
                "integer[]"
              ).replace(
                "int8[]",
                "bigint[]"
              ).replace(
                "bool[]",
                "boolean[]"
              );
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: void 0,
                // typeSchema: enumsToReturn[`${typeSchema}.${enumType}`] !== undefined
                // 	? enumsToReturn[`${typeSchema}.${enumType}`].schema
                // 	: undefined,
                primaryKey: columnName === "id",
                default: defaultValue,
                notNull: columnResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty2(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty2(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty2(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty2(identityStart),
                  cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
                  cycle: identityCycle,
                  schema: tableSchema
                } : void 0
              };
              if (identityName && typeof identityName === "string") {
                delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
            }
            const dbIndexes = await db.query(
              `SELECT  DISTINCT ON (t.relname, ic.relname, k.i) t.relname::text as table_name, ic.relname::text AS indexname,
        k.i AS index_order,
        i.indisunique as is_unique,
        am.amname::text as method,
        ic.reloptions as with,
        coalesce(a.attname,
                  (('{' || pg_get_expr(
                              i.indexprs,
                              i.indrelid
                          )
                        || '}')::text[]
                  )[k.i]
                )::text AS column_name,
          CASE
        WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
        ELSE 0
    END AS is_expression,
        i.indoption[k.i-1] & 1 = 1 AS descending,
        i.indoption[k.i-1] & 2 = 2 AS nulls_first,
        pg_get_expr(
                              i.indpred,
                              i.indrelid
                          ) as where,
         opc.opcname::text
      FROM pg_class t
          LEFT JOIN pg_index i ON t.oid = i.indrelid
          LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
		  CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
          LEFT JOIN pg_attribute AS a
            ON i.indrelid = a.attrelid AND k.attnum = a.attnum
          JOIN pg_namespace c on c.oid = t.relnamespace
        LEFT JOIN pg_am AS am ON ic.relam = am.oid
        JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
      WHERE
      c.nspname = '${tableSchema}' AND
      t.relname = '${tableName}';`
            );
            const dbIndexFromConstraint = await db.query(
              `SELECT
          idx.indexrelname::text AS index_name,
          idx.relname::text AS table_name,
          schemaname::text,
          CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
        FROM
          pg_stat_user_indexes idx
        LEFT JOIN
          pg_constraint con ON con.conindid = idx.indexrelid
        WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
        group by index_name, table_name,schemaname, generated_by_constraint;`
            );
            const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
              (it) => it.index_name
            );
            for (const dbIndex of dbIndexes) {
              const indexName6 = dbIndex.indexname;
              const indexColumnName = dbIndex.column_name;
              const indexIsUnique = dbIndex.is_unique;
              const indexMethod = dbIndex.method;
              const indexWith = dbIndex.with;
              const indexWhere = dbIndex.where;
              const opclass = dbIndex.opcname;
              const isExpression = dbIndex.is_expression === 1;
              const desc = dbIndex.descending;
              const nullsFirst = dbIndex.nulls_first;
              const mappedWith = {};
              if (indexWith !== null) {
                indexWith.forEach((it) => {
                  const splitted = it.split("=");
                  mappedWith[splitted[0]] = splitted[1];
                });
              }
              if (idxsInConsteraint.includes(indexName6)) continue;
              if (typeof indexToReturn[indexName6] !== "undefined") {
                indexToReturn[indexName6].columns.push({
                  expression: indexColumnName,
                  asc: !desc,
                  nulls: nullsFirst ? "first" : "last",
                  opclass,
                  isExpression
                });
              } else {
                indexToReturn[indexName6] = {
                  name: indexName6,
                  columns: [
                    {
                      expression: indexColumnName,
                      asc: !desc,
                      nulls: nullsFirst ? "first" : "last",
                      opclass,
                      isExpression
                    }
                  ],
                  isUnique: indexIsUnique,
                  // should not be a part of diff detects
                  concurrently: false,
                  method: indexMethod,
                  where: indexWhere === null ? void 0 : indexWhere,
                  with: mappedWith
                };
              }
            }
            indexesCount += Object.keys(indexToReturn).length;
            if (progressCallback) {
              progressCallback("indexes", indexesCount, "fetching");
            }
            result[`${tableSchema}.${tableName}`] = {
              name: tableName,
              schema: tableSchema !== "public" ? tableSchema : "",
              columns: columnToReturn,
              indexes: indexToReturn,
              foreignKeys: foreignKeysToReturn,
              compositePrimaryKeys: primaryKeys,
              uniqueConstraints: {},
              // uniqueConstrains,
              checkConstraints: {},
              // checkConstraints,
              policies: {},
              // policiesByTable[`${tableSchema}.${tableName}`] ?? {},
              isRLSEnabled: row.rls_enabled
            };
          } catch (e4) {
            rej(e4);
            return;
          }
          res("");
        });
      });
      if (progressCallback) {
        progressCallback("tables", tableCount, "done");
      }
      for await (const _3 of all) {
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("indexes", indexesCount, "done");
        progressCallback("fks", foreignKeysCount, "done");
      }
      const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
      return {
        version: "1",
        dialect: "gel",
        tables: result,
        enums: {},
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: {},
        // rolesToReturn,
        policies,
        views: {},
        // views,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
    defaultForColumn2 = (column11, internals, tableName) => {
      var _a2, _b;
      const columnName = column11.column_name;
      const isArray = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
      if (column11.column_default === null || column11.column_default === void 0) return void 0;
      if (column11.column_default.endsWith("[]")) {
        column11.column_default = column11.column_default.slice(0, -2);
      }
      column11.column_default = column11.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
      const columnDefaultAsString = column11.column_default.toString();
      if (isArray) {
        return columnDefaultAsString;
      }
      if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type)) {
        if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
          return Number(columnDefaultAsString);
        } else {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
          return columnDefaultAsString;
        }
      } else if (column11.data_type.includes("numeric")) {
        return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
      } else if (column11.data_type === "json" || column11.data_type === "jsonb") {
        return `'${columnDefaultAsString}'`;
      } else if (column11.data_type === "boolean") {
        return column11.column_default === "true";
      } else if (columnDefaultAsString === "NULL") {
        return `NULL`;
      } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
        return columnDefaultAsString;
      } else {
        return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
      }
    };
    getColumnsInfoQuery2 = ({ schema: schema6, table: table6, db }) => {
      return db.query(
        `SELECT 
    a.attrelid::regclass::text AS table_name,  -- Table, view, or materialized view name
    a.attname::text AS column_name,   -- Column name
    CASE 
        WHEN NOT a.attisdropped THEN 
            CASE 
                WHEN a.attnotnull THEN 'NO'
                ELSE 'YES'
            END 
        ELSE NULL 
    END AS is_nullable,  -- NULL or NOT NULL constraint
    a.attndims AS array_dimensions,  -- Array dimensions
    CASE 
        WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) 
        AND EXISTS (
            SELECT FROM pg_attrdef ad
            WHERE ad.adrelid = a.attrelid 
            AND ad.adnum = a.attnum 
            AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' 
                || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
        )
        THEN CASE a.atttypid
            WHEN 'int'::regtype THEN 'serial'
            WHEN 'int8'::regtype THEN 'bigserial'
            WHEN 'int2'::regtype THEN 'smallserial'
        END
        ELSE format_type(a.atttypid, a.atttypmod)
    END AS data_type,  -- Column data type
--    ns.nspname AS type_schema,  -- Schema name
    c.column_default::text,  -- Column default value
    c.data_type::text AS additional_dt,  -- Data type from information_schema
    c.udt_name::text AS enum_name,  -- Enum type (if applicable)
    c.is_generated::text,  -- Is it a generated column?
    c.generation_expression::text,  -- Generation expression (if generated)
    c.is_identity::text,  -- Is it an identity column?
    c.identity_generation::text,  -- Identity generation strategy (ALWAYS or BY DEFAULT)
    c.identity_start::text,  -- Start value of identity column
    c.identity_increment::text,  -- Increment for identity column
    c.identity_maximum::text,  -- Maximum value for identity column
    c.identity_minimum::text,  -- Minimum value for identity column
    c.identity_cycle::text,  -- Does the identity column cycle?
    ns.nspname::text AS type_schema  -- Schema of the enum type
FROM 
    pg_attribute a
JOIN 
    pg_class cls ON cls.oid = a.attrelid  -- Join pg_class to get table/view/materialized view info
JOIN 
    pg_namespace ns ON ns.oid = cls.relnamespace  -- Join namespace to get schema info
LEFT JOIN 
    information_schema.columns c ON c.column_name = a.attname 
        AND c.table_schema = ns.nspname 
        AND c.table_name = cls.relname  -- Match schema and table/view name
LEFT JOIN 
    pg_type enum_t ON enum_t.oid = a.atttypid  -- Join to get the type info
LEFT JOIN 
    pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace  -- Join to get the enum schema
WHERE 
    a.attnum > 0  -- Valid column numbers only
    AND NOT a.attisdropped  -- Skip dropped columns
    AND cls.relkind IN ('r', 'v', 'm')  -- Include regular tables ('r'), views ('v'), and materialized views ('m')
    AND ns.nspname::text = '${schema6}'  -- Filter by schema
    AND cls.relname::text = '${table6}'  -- Filter by table name
ORDER BY 
    a.attnum;  -- Order by column number`
      );
    };
  }
});

// src/introspect-gel.ts
function generateIdentityParams(identity) {
  let paramsObj = `{ name: "${identity.name}"`;
  if (identity == null ? void 0 : identity.startWith) {
    paramsObj += `, startWith: ${identity.startWith}`;
  }
  if (identity == null ? void 0 : identity.increment) {
    paramsObj += `, increment: ${identity.increment}`;
  }
  if (identity == null ? void 0 : identity.minValue) {
    paramsObj += `, minValue: ${identity.minValue}`;
  }
  if (identity == null ? void 0 : identity.maxValue) {
    paramsObj += `, maxValue: ${identity.maxValue}`;
  }
  if (identity == null ? void 0 : identity.cache) {
    paramsObj += `, cache: ${identity.cache}`;
  }
  if (identity == null ? void 0 : identity.cycle) {
    paramsObj += `, cycle: true`;
  }
  paramsObj += " }";
  if ((identity == null ? void 0 : identity.type) === "always") {
    return `.generatedAlwaysAsIdentity(${paramsObj})`;
  }
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
}
var import_casing3, gelImportsList, mapColumnDefault2, relations2, escapeColumnKey2, withCasing2, dbColumnName2, paramNameFor, schemaToTypeScript2, isCyclic2, isSelf2, buildArrayDefault, mapDefault, column7, dimensionsInArray, createTableColumns2, createTableIndexes2, createTablePKs2, createTablePolicies, createTableUniques2, createTableChecks2, createTableFKs2;
var init_introspect_gel = __esm({
  "src/introspect-gel.ts"() {
    "use strict";
    init_utils();
    import_casing3 = require("drizzle-orm/casing");
    init_global();
    init_gelSerializer();
    init_utils2();
    gelImportsList = /* @__PURE__ */ new Set([
      "gelTable",
      "smallint",
      "integer",
      "bigint",
      "bigintT",
      "boolean",
      "bytes",
      "dateDuration",
      "decimal",
      "doublePrecision",
      "duration",
      "json",
      "localDate",
      "localTime",
      "real",
      "relDuration",
      "text",
      "timestamp",
      "timestamptz",
      "uuid",
      "time"
    ]);
    mapColumnDefault2 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    relations2 = /* @__PURE__ */ new Set();
    escapeColumnKey2 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    withCasing2 = (value, casing2) => {
      if (casing2 === "preserve") {
        return escapeColumnKey2(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey2(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName2 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing3.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    paramNameFor = (name, schema6) => {
      const schemaSuffix = schema6 && schema6 !== "public" ? `In${schema6.capitalise()}` : "";
      return `${name}${schemaSuffix}`;
    };
    schemaToTypeScript2 = (schema6, casing2) => {
      Object.values(schema6.tables).forEach((table6) => {
        Object.values(table6.foreignKeys).forEach((fk5) => {
          const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
          relations2.add(relation);
        });
      });
      const schemas = Object.fromEntries(
        Object.entries(schema6.schemas).map((it) => {
          return [it[0], withCasing2(it[1].replace("::", ""), casing2)];
        })
      );
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          if (Object.values(it.foreignKeys).some((it2) => isCyclic2(it2) && !isSelf2(it2))) {
            res.gel.push("type AnyGelColumn");
          }
          const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
          const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
          const checkImports = Object.values(it.checkConstraints).map(
            (it2) => "check"
          );
          const policiesImports = Object.values(it.policies).map(
            (it2) => "gelPolicy"
          );
          if (it.schema && it.schema !== "public" && it.schema !== "") {
            res.gel.push("gelSchema");
          }
          res.gel.push(...idxImports);
          res.gel.push(...fkImpots);
          res.gel.push(...pkImports);
          res.gel.push(...uniqueImports);
          res.gel.push(...policiesImports);
          res.gel.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            var _a2;
            let patched = ((_a2 = col.type) == null ? void 0 : _a2.replace("[]", "")) ?? "";
            patched = patched.startsWith("time without time zone") ? "localTime" : patched;
            patched = patched === "double precision" ? "doublePrecision" : patched;
            patched = patched.startsWith("edgedbt.bigint_t") ? "bigintT" : patched;
            patched = patched.startsWith("jsonb") ? "json" : patched;
            patched = patched.startsWith("edgedbt.timestamptz_t") ? "timestamptz" : patched;
            patched = patched.startsWith("edgedbt.timestamp_t") ? "timestamp" : patched;
            patched = patched.startsWith("edgedbt.relative_duration_t") ? "relDuration" : patched;
            patched = patched.startsWith("bytea") ? "bytes" : patched;
            patched = patched.startsWith("numeric") ? "decimal" : patched;
            patched = patched.startsWith("edgedbt.duration_t") ? "duration" : patched;
            patched = patched.startsWith("edgedbt.date_t") ? "localDate" : patched;
            patched = patched.startsWith("edgedbt.date_duration_t") ? "dateDuration" : patched;
            return patched;
          }).filter((type) => {
            return gelImportsList.has(type);
          });
          res.gel.push(...columnImports);
          return res;
        },
        { gel: [] }
      );
      if (Object.keys(schema6.roles).length > 0) {
        imports.gel.push("gelRole");
      }
      const schemaStatements = Object.entries(schemas).filter((it) => it[0] !== "public").map((it) => {
        return `export const ${it[1].replace("::", "").camelCase()} = gelSchema("${it[0]}");
`;
      }).join("");
      const rolesNameToTsKey = {};
      const rolesStatements = Object.entries(schema6.roles).map((it) => {
        const fields = it[1];
        rolesNameToTsKey[fields.name] = it[0];
        return `export const ${withCasing2(it[0], casing2)} = gelRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
`;
      }).join("");
      const tableStatements = Object.values(schema6.tables).map((table6) => {
        const tableSchema = schemas[table6.schema];
        const paramName = paramNameFor(table6.name, tableSchema);
        const func = tableSchema ? `${tableSchema}.table` : "gelTable";
        let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${table6.name}", {
`;
        statement += createTableColumns2(
          table6.name,
          Object.values(table6.columns),
          Object.values(table6.foreignKeys),
          // enumTypes,
          /* @__PURE__ */ new Set(),
          schemas,
          casing2,
          schema6.internal
        );
        statement += "}";
        if (Object.keys(table6.indexes).length > 0 || Object.values(table6.foreignKeys).length > 0 || Object.values(table6.policies).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
          statement += ", ";
          statement += "(table) => [";
          statement += createTableIndexes2(table6.name, Object.values(table6.indexes), casing2);
          statement += createTableFKs2(Object.values(table6.foreignKeys), schemas, casing2);
          statement += createTablePKs2(
            Object.values(table6.compositePrimaryKeys),
            casing2
          );
          statement += createTableUniques2(
            Object.values(table6.uniqueConstraints),
            casing2
          );
          statement += createTablePolicies(
            Object.values(table6.policies),
            casing2,
            rolesNameToTsKey
          );
          statement += createTableChecks2(
            Object.values(table6.checkConstraints),
            casing2
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const uniqueGelImports = ["gelTable", ...new Set(imports.gel)];
      const importsTs = `import { ${uniqueGelImports.join(
        ", "
      )} } from "drizzle-orm/gel-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = schemaStatements;
      decalrations += rolesStatements;
      decalrations += "\n";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing2(it.name, casing2)).join(",\n")}
    }
  `;
      return { file, imports: importsTs, decalrations, schemaEntry };
    };
    isCyclic2 = (fk5) => {
      const key = `${fk5.tableFrom}-${fk5.tableTo}`;
      const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
      return relations2.has(key) && relations2.has(reverse);
    };
    isSelf2 = (fk5) => {
      return fk5.tableFrom === fk5.tableTo;
    };
    buildArrayDefault = (defaultValue, typeName) => {
      if (typeof defaultValue === "string" && !(defaultValue.startsWith("_nullif_array_nulls(ARRAY[") || defaultValue.startsWith("ARRAY["))) {
        return `sql\`${defaultValue}\``;
      }
      const regex = /ARRAY\[(.*)\]/;
      const match2 = defaultValue.match(regex);
      if (!match2) {
        return `sql\`${defaultValue}\``;
      }
      defaultValue = match2[1];
      return `sql\`[${defaultValue}]\``;
    };
    mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
      var _a2, _b, _c, _d;
      const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const isArray = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (name === "id") {
        return `.default(sql\`uuid_generate_v4()\`)`;
      }
      if (isArray) {
        return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
      }
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("integer")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
      }
      if (lowered.startsWith("smallint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
      }
      if (lowered.startsWith("bigint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
      }
      if (lowered.startsWith("edgedbt.bigint_t")) {
        return typeof defaultValue !== "undefined" ? `.default(BigInt(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)}))` : "";
      }
      if (lowered.startsWith("boolean")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("double precision")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("edgedbt.date_duration_t")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
      }
      if (lowered.startsWith("real")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("uuid")) {
        const res = defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
        return res;
      }
      if (lowered.startsWith("numeric")) {
        defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
        return defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("edgedbt.timestamptz_t")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("time without time zone")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("edgedbt.duration_t")) {
        return defaultValue ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
      }
      if (lowered === "edgedbt.date_t") {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) ? `.default(${defaultValue})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("edgedbt.relative_duration_t")) {
        return defaultValue ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
      }
      if (lowered.startsWith("text")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("json")) {
        const def = typeof defaultValue !== "undefined" ? defaultValue : null;
        return defaultValue ? `.default(sql\`${def}\`)` : "";
      }
      if (lowered.startsWith("bytea")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
      }
      return "";
    };
    column7 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
      var _a2, _b;
      const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        let out = `${withCasing2(name, casing2)}: ${withCasing2(paramNameFor(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("integer")) {
        let out = `${withCasing2(name, casing2)}: integer(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("smallint")) {
        let out = `${withCasing2(name, casing2)}: smallint(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("bigint")) {
        let out = `${withCasing2(name, casing2)}: bigint(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.bigint_t")) {
        let out = `${withCasing2(name, casing2)}: bigintT(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("boolean")) {
        let out = `${withCasing2(name, casing2)}: boolean(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("double precision")) {
        let out = `${withCasing2(name, casing2)}: doublePrecision(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.date_duration_t")) {
        let out = `${withCasing2(name, casing2)}: dateDuration(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("real")) {
        let out = `${withCasing2(name, casing2)}: real(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("uuid")) {
        let out = `${withCasing2(name, casing2)}: uuid(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("numeric")) {
        let out = `${withCasing2(name, casing2)}: decimal(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.timestamptz_t")) {
        let out = `${withCasing2(name, casing2)}: timestamptz(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.timestamp_t")) {
        let out = `${withCasing2(name, casing2)}: timestamp(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.date_t")) {
        let out = `${withCasing2(name, casing2)}: localDate(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.duration_t")) {
        let out = `${withCasing2(name, casing2)}: duration(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("edgedbt.relative_duration_t")) {
        let out = `${withCasing2(name, casing2)}: relDuration(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("text")) {
        let out = `${withCasing2(name, casing2)}: text(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("jsonb")) {
        let out = `${withCasing2(name, casing2)}: json(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("time without time zone")) {
        let out = `${withCasing2(name, casing2)}: localTime(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("bytea")) {
        let out = `${withCasing2(name, casing2)}: bytes(${dbColumnName2({ name, casing: casing2 })})`;
        return out;
      }
      let unknown = `// TODO: failed to parse database type '${type}'
`;
      unknown += `	${withCasing2(name, casing2)}: unknown("${name}")`;
      return unknown;
    };
    dimensionsInArray = (size) => {
      let res = "";
      if (typeof size === "undefined") return res;
      for (let i4 = 0; i4 < size; i4++) {
        res += ".array()";
      }
      return res;
    };
    createTableColumns2 = (tableName, columns, fks, enumTypes, schemas, casing2, internals) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf2(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        var _a2, _b, _c, _d;
        const columnStatement = column7(
          tableName,
          it.type,
          it.name,
          enumTypes,
          it.typeSchema ?? "public",
          casing2,
          it.default,
          internals
        );
        statement += "	";
        statement += columnStatement;
        if ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[it.name]) == null ? void 0 : _b.isArray) {
          statement += dimensionsInArray((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
        }
        statement += mapDefault(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull && !it.identity ? ".notNull()" : "";
        statement += it.identity ? generateIdentityParams(it.identity) : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes2 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = withCasing2(idxKey, casing2);
        const indexGeneratedName = indexName5(
          tableName,
          it.columns.map((it2) => it2.expression)
        );
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `${it.concurrently ? `.concurrently()` : ""}`;
        statement += `.using("${it.method}", ${it.columns.map((it2) => {
          if (it2.isExpression) {
            return `sql\`${it2.expression}\``;
          } else {
            return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass ? `.op("${it2.opclass}")` : ""}`;
          }
        }).join(", ")})`;
        statement += it.where ? `.where(sql\`${it.where}\`)` : "";
        function reverseLogic(mappedWith) {
          let reversedString = "{";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}: "${mappedWith[key]}",`;
            }
          }
          reversedString = reversedString.length > 1 ? reversedString.slice(0, reversedString.length - 1) : reversedString;
          return `${reversedString}}`;
        }
        statement += it.with && Object.keys(it.with).length > 0 ? `.with(${reverseLogic(it.with)})` : "";
        statement += `,`;
      });
      return statement;
    };
    createTablePKs2 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c3) => {
          return `table.${withCasing2(c3, casing2)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += ")";
        statement += `,`;
      });
      return statement;
    };
    createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
      let statement = "";
      policies.forEach((it) => {
        var _a2, _b, _c;
        const idxKey = withCasing2(it.name, casing2);
        const mappedItTo = (_a2 = it.to) == null ? void 0 : _a2.map((v6) => {
          return rolesNameToTsKey[v6] ? withCasing2(rolesNameToTsKey[v6], casing2) : `"${v6}"`;
        });
        statement += `
	`;
        statement += "gelPolicy(";
        statement += `"${it.name}", { `;
        statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
        statement += ` }),`;
      });
      return statement;
    };
    createTableUniques2 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing2(it2, casing2)}`).join(", ")})`;
        statement += it.nullsNotDistinct ? `.nullsNotDistinct()` : "";
        statement += `,`;
      });
      return statement;
    };
    createTableChecks2 = (checkConstraints, casing2) => {
      let statement = "";
      checkConstraints.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTableFKs2 = (fks, schemas, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const tableSchema = schemas[it.schemaTo || ""];
        const paramName = paramNameFor(it.tableTo, tableSchema);
        const isSelf5 = it.tableTo === it.tableFrom;
        const tableTo = isSelf5 ? "table" : `${withCasing2(paramName, casing2)}`;
        statement += `
	`;
        statement += `foreignKey({
`;
        statement += `			columns: [${it.columnsFrom.map((i4) => `table.${withCasing2(i4, casing2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing2(i4, casing2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		})`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/introspect-mysql.ts
var import_casing4, mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations3, escapeColumnKey3, prepareCasing, dbColumnName3, schemaToTypeScript3, isCyclic3, isSelf3, mapColumnDefault3, mapColumnDefaultForJson, column8, createTableColumns3, createTableIndexes3, createTableUniques3, createTableChecks3, createTablePKs3, createTableFKs3;
var init_introspect_mysql = __esm({
  "src/introspect-mysql.ts"() {
    "use strict";
    import_casing4 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    init_utils2();
    mysqlImportsList = /* @__PURE__ */ new Set([
      "mysqlTable",
      "mysqlEnum",
      "bigint",
      "binary",
      "boolean",
      "char",
      "date",
      "datetime",
      "decimal",
      "double",
      "float",
      "int",
      "json",
      "mediumint",
      "real",
      "serial",
      "smallint",
      "text",
      "tinytext",
      "mediumtext",
      "longtext",
      "time",
      "timestamp",
      "tinyint",
      "varbinary",
      "varchar",
      "year",
      "enum"
    ]);
    objToStatement22 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
      statement += " }";
      return statement;
    };
    timeConfig = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    binaryConfig = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    importsPatch = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp"
    };
    relations3 = /* @__PURE__ */ new Set();
    escapeColumnKey3 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    prepareCasing = (casing2) => (value) => {
      if (casing2 === "preserve") {
        return escapeColumnKey3(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey3(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName3 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing4.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript3 = (schema6, casing2) => {
      const withCasing5 = prepareCasing(casing2);
      Object.values(schema6.tables).forEach((table6) => {
        Object.values(table6.foreignKeys).forEach((fk5) => {
          const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
          relations3.add(relation);
        });
      });
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          const checkImports = Object.values(it.checkConstraint).map(
            (it2) => "check"
          );
          res.mysql.push(...idxImports);
          res.mysql.push(...fkImpots);
          res.mysql.push(...pkImports);
          res.mysql.push(...uniqueImports);
          res.mysql.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = importsPatch[col.type] ?? col.type;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("binary(") ? "binary" : patched;
            patched = patched.startsWith("decimal(") ? "decimal" : patched;
            patched = patched.startsWith("smallint(") ? "smallint" : patched;
            patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
            patched = patched.startsWith("datetime(") ? "datetime" : patched;
            patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
            patched = patched.startsWith("int(") ? "int" : patched;
            patched = patched.startsWith("double(") ? "double" : patched;
            patched = patched.startsWith("float(") ? "float" : patched;
            patched = patched.startsWith("int unsigned") ? "int" : patched;
            patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
            patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
            patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
            patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
            return patched;
          }).filter((type) => {
            return mysqlImportsList.has(type);
          });
          res.mysql.push(...columnImports);
          return res;
        },
        { mysql: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        imports.mysql.push("mysqlView");
        const columnImports = Object.values(it.columns).map((col) => {
          let patched = importsPatch[col.type] ?? col.type;
          patched = patched.startsWith("varchar(") ? "varchar" : patched;
          patched = patched.startsWith("char(") ? "char" : patched;
          patched = patched.startsWith("binary(") ? "binary" : patched;
          patched = patched.startsWith("decimal(") ? "decimal" : patched;
          patched = patched.startsWith("smallint(") ? "smallint" : patched;
          patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
          patched = patched.startsWith("datetime(") ? "datetime" : patched;
          patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
          patched = patched.startsWith("int(") ? "int" : patched;
          patched = patched.startsWith("double(") ? "double" : patched;
          patched = patched.startsWith("float(") ? "float" : patched;
          patched = patched.startsWith("int unsigned") ? "int" : patched;
          patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
          patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
          patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
          patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
          return patched;
        }).filter((type) => {
          return mysqlImportsList.has(type);
        });
        imports.mysql.push(...columnImports);
      });
      const tableStatements = Object.values(schema6.tables).map((table6) => {
        const func = "mysqlTable";
        let statement = "";
        if (imports.mysql.includes(withCasing5(table6.name))) {
          statement = `// Table name is in conflict with ${withCasing5(
            table6.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing5(table6.name)} = ${func}("${table6.name}", {
`;
        statement += createTableColumns3(
          Object.values(table6.columns),
          Object.values(table6.foreignKeys),
          withCasing5,
          casing2,
          table6.name,
          schema6
        );
        statement += "}";
        const filteredFKs = Object.values(table6.foreignKeys).filter((it) => {
          return it.columnsFrom.length > 1 || isSelf3(it);
        });
        if (Object.keys(table6.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraint).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes3(
            table6.name,
            Object.values(table6.indexes),
            withCasing5
          );
          statement += createTableFKs3(Object.values(filteredFKs), withCasing5);
          statement += createTablePKs3(
            Object.values(table6.compositePrimaryKeys),
            withCasing5
          );
          statement += createTableUniques3(
            Object.values(table6.uniqueConstraints),
            withCasing5
          );
          statement += createTableChecks3(
            Object.values(table6.checkConstraint),
            withCasing5
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((view5) => {
        const { columns, name, algorithm, definition, sqlSecurity, withCheckOption } = view5;
        const func = "mysqlView";
        let statement = "";
        if (imports.mysql.includes(withCasing5(name))) {
          statement = `// Table name is in conflict with ${withCasing5(
            view5.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing5(name)} = ${func}("${name}", {
`;
        statement += createTableColumns3(
          Object.values(columns),
          [],
          withCasing5,
          casing2,
          name,
          schema6
        );
        statement += "})";
        statement += algorithm ? `.algorithm("${algorithm}")` : "";
        statement += sqlSecurity ? `.sqlSecurity("${sqlSecurity}")` : "";
        statement += withCheckOption ? `.withCheckOption("${withCheckOption}")` : "";
        statement += `.as(sql\`${definition == null ? void 0 : definition.replaceAll("`", "\\`")}\`);`;
        return statement;
      });
      const uniqueMySqlImports = [
        "mysqlTable",
        "mysqlSchema",
        "AnyMySqlColumn",
        ...new Set(imports.mysql)
      ];
      const importsTs = `import { ${uniqueMySqlImports.join(
        ", "
      )} } from "drizzle-orm/mysql-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = "";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      decalrations += viewsStatements.join("\n\n");
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing5(it.name)).join(",")}
    }
  `;
      return {
        file,
        // backward compatible, print to file
        imports: importsTs,
        decalrations,
        schemaEntry
      };
    };
    isCyclic3 = (fk5) => {
      const key = `${fk5.tableFrom}-${fk5.tableTo}`;
      const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
      return relations3.has(key) && relations3.has(reverse);
    };
    isSelf3 = (fk5) => {
      return fk5.tableFrom === fk5.tableTo;
    };
    mapColumnDefault3 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    mapColumnDefaultForJson = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
        return defaultValue.substring(2, defaultValue.length - 2);
      }
      return defaultValue;
    };
    column8 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
      let lowered = type;
      if (!type.startsWith("enum(")) {
        lowered = type.toLowerCase();
      }
      if (lowered === "serial") {
        return `${casing2(name)}: serial(${dbColumnName3({ name, casing: rawCasing })})`;
      }
      if (lowered.startsWith("int")) {
        const isUnsigned = lowered.startsWith("int unsigned");
        const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("tinyint")) {
        const isUnsigned = lowered.startsWith("tinyint unsigned");
        const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("smallint")) {
        const isUnsigned = lowered.startsWith("smallint unsigned");
        const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("mediumint")) {
        const isUnsigned = lowered.startsWith("mediumint unsigned");
        const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("bigint")) {
        const isUnsigned = lowered.startsWith("bigint unsigned");
        let out = `${casing2(name)}: bigint(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "boolean") {
        let out = `${casing2(name)}: boolean(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("double")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
          const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig(params) : void 0;
        let out = params ? `${casing2(name)}: double(${dbColumnName3({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig(params)})` : `${casing2(name)}: double(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("float")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
          const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        let out = `${casing2(name)}: float(${dbColumnName3({ name, casing: rawCasing })}${params ? timeConfig(params) : ""})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${casing2(name)}: real(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const keyLength = "timestamp".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig({ fsp, mode: "'string'" });
        let out = params ? `${casing2(name)}: timestamp(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName3({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" || defaultValue === "(CURRENT_TIMESTAMP)" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
        out += onUpdateNow;
        return out;
      }
      if (lowered.startsWith("time")) {
        const keyLength = "time".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig({ fsp });
        let out = params ? `${casing2(name)}: time(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName3({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "date") {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	${casing2(
          name
        )}: date(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "text") {
        let out = `${casing2(name)}: text(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "tinytext") {
        let out = `${casing2(name)}: tinytext(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "mediumtext") {
        let out = `${casing2(name)}: mediumtext(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "longtext") {
        let out = `${casing2(name)}: longtext(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "year") {
        let out = `${casing2(name)}: year(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "json") {
        let out = `${casing2(name)}: json(${dbColumnName3({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefaultForJson(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out = `${casing2(
          name
        )}: varchar(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "varchar".length + 1,
          lowered.length - 1
        )} })`;
        const mappedDefaultValue = mapColumnDefault3(defaultValue, isExpression);
        out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
        return out;
      }
      if (lowered.startsWith("char")) {
        let out = `${casing2(
          name
        )}: char(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "char".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("datetime")) {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	`;
        const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
        out = fsp ? `${casing2(
          name
        )}: datetime(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
          "datetime".length + 1,
          lowered.length - 1
        )} })` : `${casing2(name)}: datetime(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("decimal")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
          const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig(params) : void 0;
        let out = params ? `${casing2(name)}: decimal(${dbColumnName3({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName3({ name, casing: rawCasing })})`;
        defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("binary")) {
        const keyLength = "binary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig({ length });
        let out = params ? `${casing2(name)}: binary(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName3({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("enum")) {
        const values = lowered.substring("enum".length + 1, lowered.length - 1).split(",").map((v6) => unescapeSingleQuotes(v6, true)).join(",");
        let out = `${casing2(name)}: mysqlEnum(${dbColumnName3({ name, casing: rawCasing, withMode: true })}[${values}])`;
        const mappedDefaultValue = mapColumnDefault3(defaultValue, isExpression);
        out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
        return out;
      }
      if (lowered.startsWith("varbinary")) {
        const keyLength = "varbinary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig({ length });
        let out = params ? `${casing2(name)}: varbinary(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName3({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      console.log("uknown", type);
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns3 = (columns, fks, casing2, rawCasing, tableName, schema6) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf3(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        var _a2, _b, _c;
        statement += "	";
        statement += column8(
          it.type,
          it.name,
          casing2,
          rawCasing,
          it.default,
          it.autoincrement,
          it.onUpdate,
          ((_c = (_b = (_a2 = schema6.internal) == null ? void 0 : _a2.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
        );
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
          /`/g,
          "\\`"
        )}\`, { mode: "${it.generated.type}" })` : "";
        const fks2 = fkByColumnName[it.name];
        if (fks2) {
          const fksStatement = fks2.map((it2) => {
            const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
            const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
            const params = { onDelete, onUpdate };
            const typeSuffix = isCyclic3(it2) ? ": AnyMySqlColumn" : "";
            const paramsStr = objToStatement22(params);
            if (paramsStr) {
              return `.references(()${typeSuffix} => ${casing2(
                it2.tableTo
              )}.${casing2(it2.columnsTo[0])}, ${paramsStr} )`;
            }
            return `.references(()${typeSuffix} => ${casing2(it2.tableTo)}.${casing2(
              it2.columnsTo[0]
            )})`;
          }).join("");
          statement += fksStatement;
        }
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes3 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = casing2(idxKey);
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques3 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        const idxKey = casing2(it.name);
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableChecks3 = (checks, casing2) => {
      let statement = "";
      checks.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value.replace(/`/g, "\\`")}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTablePKs3 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        let idxKey = casing2(it.name);
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c3) => {
          return `table.${casing2(c3)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += "),";
      });
      return statement;
    };
    createTableFKs3 = (fks, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const isSelf5 = it.tableTo === it.tableFrom;
        const tableTo = isSelf5 ? "table" : `${casing2(it.tableTo)}`;
        statement += `
	`;
        statement += `foreignKey({
`;
        statement += `			columns: [${it.columnsFrom.map((i4) => `table.${casing2(i4)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${casing2(i4)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		})`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/introspect-pg.ts
function generateIdentityParams2(identity) {
  let paramsObj = `{ name: "${identity.name}"`;
  if (identity == null ? void 0 : identity.startWith) {
    paramsObj += `, startWith: ${identity.startWith}`;
  }
  if (identity == null ? void 0 : identity.increment) {
    paramsObj += `, increment: ${identity.increment}`;
  }
  if (identity == null ? void 0 : identity.minValue) {
    paramsObj += `, minValue: ${identity.minValue}`;
  }
  if (identity == null ? void 0 : identity.maxValue) {
    paramsObj += `, maxValue: ${identity.maxValue}`;
  }
  if (identity == null ? void 0 : identity.cache) {
    paramsObj += `, cache: ${identity.cache}`;
  }
  if (identity == null ? void 0 : identity.cycle) {
    paramsObj += `, cycle: true`;
  }
  paramsObj += " }";
  if ((identity == null ? void 0 : identity.type) === "always") {
    return `.generatedAlwaysAsIdentity(${paramsObj})`;
  }
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
}
var import_drizzle_orm10, import_relations, import_casing5, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault4, importsPatch2, relations4, escapeColumnKey4, withCasing3, dbColumnName4, paramNameFor2, schemaToTypeScript4, isCyclic4, isSelf4, buildArrayDefault2, mapDefault2, column9, dimensionsInArray2, createTableColumns4, createTableIndexes4, createTablePKs4, createTablePolicies2, createTableUniques4, createTableChecks4, createTableFKs4;
var init_introspect_pg = __esm({
  "src/introspect-pg.ts"() {
    "use strict";
    import_drizzle_orm10 = require("drizzle-orm");
    import_relations = require("drizzle-orm/relations");
    init_utils();
    import_casing5 = require("drizzle-orm/casing");
    init_global();
    init_pgSerializer();
    init_utils2();
    pgImportsList = /* @__PURE__ */ new Set([
      "pgTable",
      "pgEnum",
      "smallint",
      "integer",
      "bigint",
      "boolean",
      "text",
      "varchar",
      "char",
      "serial",
      "smallserial",
      "bigserial",
      "decimal",
      "numeric",
      "real",
      "json",
      "jsonb",
      "time",
      "timestamp",
      "date",
      "interval",
      "cidr",
      "inet",
      "macaddr",
      "macaddr8",
      "bigint",
      "doublePrecision",
      "uuid",
      "vector",
      "point",
      "line",
      "geometry"
    ]);
    timeConfig2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    possibleIntervals = [
      "year",
      "month",
      "day",
      "hour",
      "minute",
      "second",
      "year to month",
      "day to hour",
      "day to minute",
      "day to second",
      "hour to minute",
      "hour to second",
      "minute to second"
    ];
    intervalStrToObj = (str) => {
      if (str.startsWith("interval(")) {
        return {
          precision: Number(str.substring("interval(".length, str.length - 1))
        };
      }
      const splitted = str.split(" ");
      if (splitted.length === 1) {
        return {};
      }
      const rest = splitted.slice(1, splitted.length).join(" ");
      if (possibleIntervals.includes(rest)) {
        return { fields: `"${rest}"` };
      }
      for (const s4 of possibleIntervals) {
        if (rest.startsWith(`${s4}(`)) {
          return {
            fields: `"${s4}"`,
            precision: Number(rest.substring(s4.length + 1, rest.length - 1))
          };
        }
      }
      return {};
    };
    intervalConfig = (str) => {
      const json = intervalStrToObj(str);
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    mapColumnDefault4 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    importsPatch2 = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp",
      "timestamp with time zone": "timestamp",
      "time without time zone": "time",
      "time with time zone": "time"
    };
    relations4 = /* @__PURE__ */ new Set();
    escapeColumnKey4 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    withCasing3 = (value, casing2) => {
      if (casing2 === "preserve") {
        return escapeColumnKey4(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey4(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName4 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing5.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    paramNameFor2 = (name, schema6) => {
      const schemaSuffix = schema6 && schema6 !== "public" ? `In${schema6.capitalise()}` : "";
      return `${name}${schemaSuffix}`;
    };
    schemaToTypeScript4 = (schema6, casing2) => {
      Object.values(schema6.tables).forEach((table6) => {
        Object.values(table6.foreignKeys).forEach((fk5) => {
          const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
          relations4.add(relation);
        });
      });
      const schemas = Object.fromEntries(
        Object.entries(schema6.schemas).map((it) => {
          return [it[0], withCasing3(it[1], casing2)];
        })
      );
      const enumTypes = Object.values(schema6.enums).reduce((acc, cur) => {
        acc.add(`${cur.schema}.${cur.name}`);
        return acc;
      }, /* @__PURE__ */ new Set());
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          if (Object.values(it.foreignKeys).some((it2) => isCyclic4(it2) && !isSelf4(it2))) {
            res.pg.push("type AnyPgColumn");
          }
          const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
          const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
          const checkImports = Object.values(it.checkConstraints).map(
            (it2) => "check"
          );
          const policiesImports = Object.values(it.policies).map(
            (it2) => "pgPolicy"
          );
          if (it.schema && it.schema !== "public" && it.schema !== "") {
            res.pg.push("pgSchema");
          }
          res.pg.push(...idxImports);
          res.pg.push(...fkImpots);
          res.pg.push(...pkImports);
          res.pg.push(...uniqueImports);
          res.pg.push(...policiesImports);
          res.pg.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
            patched = patched === "double precision" ? "doublePrecision" : patched;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("numeric(") ? "numeric" : patched;
            patched = patched.startsWith("time(") ? "time" : patched;
            patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
            patched = patched.startsWith("vector(") ? "vector" : patched;
            patched = patched.startsWith("geometry(") ? "geometry" : patched;
            return patched;
          }).filter((type) => {
            return pgImportsList.has(type);
          });
          res.pg.push(...columnImports);
          return res;
        },
        { pg: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          it.materialized ? imports.pg.push("pgMaterializedView") : imports.pg.push("pgView");
        }
        Object.values(it.columns).forEach(() => {
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
            patched = patched === "double precision" ? "doublePrecision" : patched;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("numeric(") ? "numeric" : patched;
            patched = patched.startsWith("time(") ? "time" : patched;
            patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
            patched = patched.startsWith("vector(") ? "vector" : patched;
            patched = patched.startsWith("geometry(") ? "geometry" : patched;
            return patched;
          }).filter((type) => {
            return pgImportsList.has(type);
          });
          imports.pg.push(...columnImports);
        });
      });
      Object.values(schema6.sequences).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          imports.pg.push("pgSequence");
        }
      });
      Object.values(schema6.enums).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          imports.pg.push("pgEnum");
        }
      });
      if (Object.keys(schema6.roles).length > 0) {
        imports.pg.push("pgRole");
      }
      const enumStatements = Object.values(schema6.enums).map((it) => {
        const enumSchema4 = schemas[it.schema];
        const paramName = paramNameFor2(it.name, enumSchema4);
        const func = enumSchema4 ? `${enumSchema4}.enum` : "pgEnum";
        const values = Object.values(it.values).map((it2) => `'${unescapeSingleQuotes(it2, false)}'`).join(", ");
        return `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}", [${values}])
`;
      }).join("").concat("\n");
      const sequencesStatements = Object.values(schema6.sequences).map((it) => {
        const seqSchema = schemas[it.schema];
        const paramName = paramNameFor2(it.name, seqSchema);
        const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
        let params = "";
        if (it.startWith) {
          params += `, startWith: "${it.startWith}"`;
        }
        if (it.increment) {
          params += `, increment: "${it.increment}"`;
        }
        if (it.minValue) {
          params += `, minValue: "${it.minValue}"`;
        }
        if (it.maxValue) {
          params += `, maxValue: "${it.maxValue}"`;
        }
        if (it.cache) {
          params += `, cache: "${it.cache}"`;
        }
        if (it.cycle) {
          params += `, cycle: true`;
        } else {
          params += `, cycle: false`;
        }
        return `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
`;
      }).join("").concat("");
      const schemaStatements = Object.entries(schemas).map((it) => {
        return `export const ${it[1]} = pgSchema("${it[0]}");
`;
      }).join("");
      const rolesNameToTsKey = {};
      const rolesStatements = Object.entries(schema6.roles).map((it) => {
        const fields = it[1];
        rolesNameToTsKey[fields.name] = it[0];
        return `export const ${withCasing3(it[0], casing2)} = pgRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
`;
      }).join("");
      const tableStatements = Object.values(schema6.tables).map((table6) => {
        const tableSchema = schemas[table6.schema];
        const paramName = paramNameFor2(table6.name, tableSchema);
        const func = tableSchema ? `${tableSchema}.table` : "pgTable";
        let statement = `export const ${withCasing3(paramName, casing2)} = ${func}("${table6.name}", {
`;
        statement += createTableColumns4(
          table6.name,
          Object.values(table6.columns),
          Object.values(table6.foreignKeys),
          enumTypes,
          schemas,
          casing2,
          schema6.internal
        );
        statement += "}";
        if (Object.keys(table6.indexes).length > 0 || Object.values(table6.foreignKeys).length > 0 || Object.values(table6.policies).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
          statement += ", ";
          statement += "(table) => [";
          statement += createTableIndexes4(table6.name, Object.values(table6.indexes), casing2);
          statement += createTableFKs4(Object.values(table6.foreignKeys), schemas, casing2);
          statement += createTablePKs4(
            Object.values(table6.compositePrimaryKeys),
            casing2
          );
          statement += createTableUniques4(
            Object.values(table6.uniqueConstraints),
            casing2
          );
          statement += createTablePolicies2(
            Object.values(table6.policies),
            casing2,
            rolesNameToTsKey
          );
          statement += createTableChecks4(
            Object.values(table6.checkConstraints),
            casing2
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((it) => {
        const viewSchema = schemas[it.schema];
        const paramName = paramNameFor2(it.name, viewSchema);
        const func = viewSchema ? it.materialized ? `${viewSchema}.materializedView` : `${viewSchema}.view` : it.materialized ? "pgMaterializedView" : "pgView";
        const withOption = it.with ?? "";
        const as = `sql\`${it.definition}\``;
        const tablespace = it.tablespace ?? "";
        const columns = createTableColumns4(
          "",
          Object.values(it.columns),
          [],
          enumTypes,
          schemas,
          casing2,
          schema6.internal
        );
        let statement = `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}", {${columns}})`;
        statement += tablespace ? `.tablespace("${tablespace}")` : "";
        statement += withOption ? `.with(${JSON.stringify(withOption)})` : "";
        statement += `.as(${as});`;
        return statement;
      }).join("\n\n");
      const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
      const importsTs = `import { ${uniquePgImports.join(
        ", "
      )} } from "drizzle-orm/pg-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = schemaStatements;
      decalrations += rolesStatements;
      decalrations += enumStatements;
      decalrations += sequencesStatements;
      decalrations += "\n";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      decalrations += viewsStatements;
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing3(it.name, casing2)).join(",\n")}
    }
  `;
      return { file, imports: importsTs, decalrations, schemaEntry };
    };
    isCyclic4 = (fk5) => {
      const key = `${fk5.tableFrom}-${fk5.tableTo}`;
      const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
      return relations4.has(key) && relations4.has(reverse);
    };
    isSelf4 = (fk5) => {
      return fk5.tableFrom === fk5.tableTo;
    };
    buildArrayDefault2 = (defaultValue, typeName) => {
      if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
        return `sql\`${defaultValue}\``;
      }
      defaultValue = defaultValue.substring(2, defaultValue.length - 2);
      return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
        if (typeName === "json" || typeName === "jsonb") {
          return value.substring(1, value.length - 1).replaceAll("\\", "");
        }
        return value;
      }).join(", ")}]`;
    };
    mapDefault2 = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
      var _a2, _b, _c, _d;
      const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const isArray = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (isArray) {
        return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault2(defaultValue, lowered)})` : "";
      }
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("integer")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("smallint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("bigint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("boolean")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("double precision")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("real")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("uuid")) {
        return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("numeric")) {
        defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
        return defaultValue ? `.default('${mapColumnDefault4(defaultValue, isExpression)}')` : "";
      }
      if (lowered.startsWith("timestamp")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("time")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("interval")) {
        return defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered === "date") {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) ? `.default(${defaultValue})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("text")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("jsonb")) {
        const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
        return defaultValue ? `.default(${def})` : "";
      }
      if (lowered.startsWith("json")) {
        const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
        return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
      }
      if (lowered.startsWith("inet")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("cidr")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("macaddr8")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("macaddr")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("varchar")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("point")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("line")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("geometry")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("vector")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("char")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      return "";
    };
    column9 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
      var _a2, _b;
      const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        let out = `${withCasing3(name, casing2)}: ${withCasing3(paramNameFor2(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("serial")) {
        return `${withCasing3(name, casing2)}: serial(${dbColumnName4({ name, casing: casing2 })})`;
      }
      if (lowered.startsWith("smallserial")) {
        return `${withCasing3(name, casing2)}: smallserial(${dbColumnName4({ name, casing: casing2 })})`;
      }
      if (lowered.startsWith("bigserial")) {
        return `${withCasing3(name, casing2)}: bigserial(${dbColumnName4({ name, casing: casing2, withMode: true })}{ mode: "bigint" })`;
      }
      if (lowered.startsWith("integer")) {
        let out = `${withCasing3(name, casing2)}: integer(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("smallint")) {
        let out = `${withCasing3(name, casing2)}: smallint(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("bigint")) {
        let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
	`;
        out += `${withCasing3(name, casing2)}: bigint(${dbColumnName4({ name, casing: casing2, withMode: true })}{ mode: "number" })`;
        return out;
      }
      if (lowered.startsWith("boolean")) {
        let out = `${withCasing3(name, casing2)}: boolean(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("double precision")) {
        let out = `${withCasing3(name, casing2)}: doublePrecision(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("real")) {
        let out = `${withCasing3(name, casing2)}: real(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("uuid")) {
        let out = `${withCasing3(name, casing2)}: uuid(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("numeric")) {
        let params;
        if (lowered.length > 7) {
          const [precision, scale] = lowered.slice(8, lowered.length - 1).split(",");
          params = { precision, scale };
        }
        let out = params ? `${withCasing3(name, casing2)}: numeric(${dbColumnName4({ name, casing: casing2, withMode: true })}${timeConfig2(params)})` : `${withCasing3(name, casing2)}: numeric(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const withTimezone = lowered.includes("with time zone");
        let precision = lowered.startsWith("timestamp(") ? Number(lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)) : null;
        precision = precision ? precision : null;
        const params = timeConfig2({
          precision,
          withTimezone,
          mode: "'string'"
        });
        let out = params ? `${withCasing3(name, casing2)}: timestamp(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: timestamp(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("time")) {
        const withTimezone = lowered.includes("with time zone");
        let precision = lowered.startsWith("time(") ? Number(lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)) : null;
        precision = precision ? precision : null;
        const params = timeConfig2({ precision, withTimezone });
        let out = params ? `${withCasing3(name, casing2)}: time(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: time(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("interval")) {
        const params = intervalConfig(lowered);
        let out = params ? `${withCasing3(name, casing2)}: interval(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: interval(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered === "date") {
        let out = `${withCasing3(name, casing2)}: date(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("text")) {
        let out = `${withCasing3(name, casing2)}: text(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("jsonb")) {
        let out = `${withCasing3(name, casing2)}: jsonb(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("json")) {
        let out = `${withCasing3(name, casing2)}: json(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("inet")) {
        let out = `${withCasing3(name, casing2)}: inet(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("cidr")) {
        let out = `${withCasing3(name, casing2)}: cidr(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("macaddr8")) {
        let out = `${withCasing3(name, casing2)}: macaddr8(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("macaddr")) {
        let out = `${withCasing3(name, casing2)}: macaddr(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out;
        if (lowered.length !== 7) {
          out = `${withCasing3(name, casing2)}: varchar(${dbColumnName4({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(8, lowered.length - 1)} })`;
        } else {
          out = `${withCasing3(name, casing2)}: varchar(${dbColumnName4({ name, casing: casing2 })})`;
        }
        return out;
      }
      if (lowered.startsWith("point")) {
        let out = `${withCasing3(name, casing2)}: point(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("line")) {
        let out = `${withCasing3(name, casing2)}: point(${dbColumnName4({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("geometry")) {
        let out = "";
        let isGeoUnknown = false;
        if (lowered.length !== 8) {
          const geometryOptions = lowered.slice(9, -1).split(",");
          if (geometryOptions.length === 1 && geometryOptions[0] !== "") {
            out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}" })`;
          } else if (geometryOptions.length === 2) {
            out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}", srid: ${geometryOptions[1]} })`;
          } else {
            isGeoUnknown = true;
          }
        } else {
          out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2 })})`;
        }
        if (isGeoUnknown) {
          let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
// Introspect is currently supporting only type and srid options
`;
          unknown2 += `	${withCasing3(name, casing2)}: unknown("${name}")`;
          return unknown2;
        }
        return out;
      }
      if (lowered.startsWith("vector")) {
        let out;
        if (lowered.length !== 6) {
          out = `${withCasing3(name, casing2)}: vector(${dbColumnName4({ name, casing: casing2, withMode: true })}{ dimensions: ${lowered.substring(7, lowered.length - 1)} })`;
        } else {
          out = `${withCasing3(name, casing2)}: vector(${dbColumnName4({ name, casing: casing2 })})`;
        }
        return out;
      }
      if (lowered.startsWith("char")) {
        let out;
        if (lowered.length !== 4) {
          out = `${withCasing3(name, casing2)}: char(${dbColumnName4({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(5, lowered.length - 1)} })`;
        } else {
          out = `${withCasing3(name, casing2)}: char(${dbColumnName4({ name, casing: casing2 })})`;
        }
        return out;
      }
      let unknown = `// TODO: failed to parse database type '${type}'
`;
      unknown += `	${withCasing3(name, casing2)}: unknown("${name}")`;
      return unknown;
    };
    dimensionsInArray2 = (size) => {
      let res = "";
      if (typeof size === "undefined") return res;
      for (let i4 = 0; i4 < size; i4++) {
        res += ".array()";
      }
      return res;
    };
    createTableColumns4 = (tableName, columns, fks, enumTypes, schemas, casing2, internals) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf4(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        var _a2, _b, _c, _d;
        const columnStatement = column9(
          tableName,
          it.type,
          it.name,
          enumTypes,
          it.typeSchema ?? "public",
          casing2,
          it.default,
          internals
        );
        statement += "	";
        statement += columnStatement;
        if ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[it.name]) == null ? void 0 : _b.isArray) {
          statement += dimensionsInArray2((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
        }
        statement += mapDefault2(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull && !it.identity ? ".notNull()" : "";
        statement += it.identity ? generateIdentityParams2(it.identity) : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes4 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = withCasing3(idxKey, casing2);
        const indexGeneratedName = indexName2(
          tableName,
          it.columns.map((it2) => it2.expression)
        );
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `${it.concurrently ? `.concurrently()` : ""}`;
        statement += `.using("${it.method}", ${it.columns.map((it2) => {
          if (it2.isExpression) {
            return `sql\`${it2.expression}\``;
          } else {
            return `table.${withCasing3(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass ? `.op("${it2.opclass}")` : ""}`;
          }
        }).join(", ")})`;
        statement += it.where ? `.where(sql\`${it.where}\`)` : "";
        function reverseLogic(mappedWith) {
          let reversedString = "{";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}: "${mappedWith[key]}",`;
            }
          }
          reversedString = reversedString.length > 1 ? reversedString.slice(0, reversedString.length - 1) : reversedString;
          return `${reversedString}}`;
        }
        statement += it.with && Object.keys(it.with).length > 0 ? `.with(${reverseLogic(it.with)})` : "";
        statement += `,`;
      });
      return statement;
    };
    createTablePKs4 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c3) => {
          return `table.${withCasing3(c3, casing2)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += ")";
        statement += `,`;
      });
      return statement;
    };
    createTablePolicies2 = (policies, casing2, rolesNameToTsKey = {}) => {
      let statement = "";
      policies.forEach((it) => {
        var _a2, _b, _c;
        const idxKey = withCasing3(it.name, casing2);
        const mappedItTo = (_a2 = it.to) == null ? void 0 : _a2.map((v6) => {
          return rolesNameToTsKey[v6] ? withCasing3(rolesNameToTsKey[v6], casing2) : `"${v6}"`;
        });
        statement += `
	`;
        statement += "pgPolicy(";
        statement += `"${it.name}", { `;
        statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
        statement += ` }),`;
      });
      return statement;
    };
    createTableUniques4 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing3(it2, casing2)}`).join(", ")})`;
        statement += it.nullsNotDistinct ? `.nullsNotDistinct()` : "";
        statement += `,`;
      });
      return statement;
    };
    createTableChecks4 = (checkConstraints, casing2) => {
      let statement = "";
      checkConstraints.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTableFKs4 = (fks, schemas, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const tableSchema = schemas[it.schemaTo || ""];
        const paramName = paramNameFor2(it.tableTo, tableSchema);
        const isSelf5 = it.tableTo === it.tableFrom;
        const tableTo = isSelf5 ? "table" : `${withCasing3(paramName, casing2)}`;
        statement += `
	`;
        statement += `foreignKey({
`;
        statement += `			columns: [${it.columnsFrom.map((i4) => `table.${withCasing3(i4, casing2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing3(i4, casing2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		})`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/introspect-singlestore.ts
var import_casing6, singlestoreImportsList, timeConfig3, binaryConfig2, importsPatch3, escapeColumnKey5, prepareCasing2, dbColumnName5, schemaToTypeScript5, mapColumnDefault5, mapColumnDefaultForJson2, column10, createTableColumns5, createTableIndexes5, createTableUniques5, createTablePKs5;
var init_introspect_singlestore = __esm({
  "src/introspect-singlestore.ts"() {
    "use strict";
    import_casing6 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    init_singlestoreSerializer();
    singlestoreImportsList = /* @__PURE__ */ new Set([
      "singlestoreTable",
      "singlestoreEnum",
      "bigint",
      "binary",
      "boolean",
      "char",
      "date",
      "datetime",
      "decimal",
      "double",
      "float",
      "int",
      "json",
      // TODO: add new type BSON
      // TODO: add new type Blob
      // TODO: add new type UUID
      // TODO: add new type GUID
      // TODO: add new type Vector
      // TODO: add new type GeoPoint
      "mediumint",
      "real",
      "serial",
      "smallint",
      "text",
      "tinytext",
      "mediumtext",
      "longtext",
      "time",
      "timestamp",
      "tinyint",
      "varbinary",
      "varchar",
      "vector",
      "year",
      "enum"
    ]);
    timeConfig3 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    binaryConfig2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0) return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    importsPatch3 = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp"
    };
    escapeColumnKey5 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    prepareCasing2 = (casing2) => (value) => {
      if (casing2 === "preserve") {
        return escapeColumnKey5(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey5(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName5 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing6.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript5 = (schema6, casing2) => {
      const withCasing5 = prepareCasing2(casing2);
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          res.singlestore.push(...idxImports);
          res.singlestore.push(...pkImports);
          res.singlestore.push(...uniqueImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = importsPatch3[col.type] ?? col.type;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("binary(") ? "binary" : patched;
            patched = patched.startsWith("decimal(") ? "decimal" : patched;
            patched = patched.startsWith("smallint(") ? "smallint" : patched;
            patched = patched.startsWith("enum(") ? "singlestoreEnum" : patched;
            patched = patched.startsWith("datetime(") ? "datetime" : patched;
            patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
            patched = patched.startsWith("int(") ? "int" : patched;
            patched = patched.startsWith("double(") ? "double" : patched;
            patched = patched.startsWith("float(") ? "float" : patched;
            patched = patched.startsWith("int unsigned") ? "int" : patched;
            patched = patched.startsWith("tinyint(") ? "tinyint" : patched;
            patched = patched.startsWith("mediumint(") ? "mediumint" : patched;
            patched = patched.startsWith("bigint(") ? "bigint" : patched;
            patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
            patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
            patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
            patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
            return patched;
          }).filter((type) => {
            return singlestoreImportsList.has(type);
          });
          res.singlestore.push(...columnImports);
          return res;
        },
        { singlestore: [] }
      );
      const tableStatements = Object.values(schema6.tables).map((table6) => {
        const func = "singlestoreTable";
        let statement = "";
        if (imports.singlestore.includes(withCasing5(table6.name))) {
          statement = `// Table name is in conflict with ${withCasing5(
            table6.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing5(table6.name)} = ${func}("${table6.name}", {
`;
        statement += createTableColumns5(
          Object.values(table6.columns),
          withCasing5,
          casing2,
          table6.name,
          schema6
        );
        statement += "}";
        if (Object.keys(table6.indexes).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes5(
            table6.name,
            Object.values(table6.indexes),
            withCasing5
          );
          statement += createTablePKs5(
            Object.values(table6.compositePrimaryKeys),
            withCasing5
          );
          statement += createTableUniques5(
            Object.values(table6.uniqueConstraints),
            withCasing5
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const uniqueSingleStoreImports = [
        "singlestoreTable",
        "singlestoreSchema",
        "AnySingleStoreColumn",
        ...new Set(imports.singlestore)
      ];
      const importsTs = `import { ${uniqueSingleStoreImports.join(
        ", "
      )} } from "drizzle-orm/singlestore-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = "";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing5(it.name)).join(",")}
    }
  `;
      return {
        file,
        // backward compatible, print to file
        imports: importsTs,
        decalrations,
        schemaEntry
      };
    };
    mapColumnDefault5 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    mapColumnDefaultForJson2 = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
        return defaultValue.substring(2, defaultValue.length - 2);
      }
      return defaultValue;
    };
    column10 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
      let lowered = type;
      if (!type.startsWith("enum(")) {
        lowered = type.toLowerCase();
      }
      if (lowered === "serial") {
        return `${casing2(name)}: serial(${dbColumnName5({ name, casing: rawCasing })})`;
      }
      if (lowered.startsWith("int")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("tinyint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("smallint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("mediumint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("bigint")) {
        const isUnsigned = lowered.includes("unsigned");
        let out = `${casing2(name)}: bigint(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "boolean") {
        let out = `${casing2(name)}: boolean(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("double")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
          const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig3(params) : void 0;
        let out = params ? `${casing2(name)}: double(${dbColumnName5({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig3(params)})` : `${casing2(name)}: double(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("float")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
          const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        let out = `${casing2(name)}: float(${dbColumnName5({ name, casing: rawCasing })}${params ? timeConfig3(params) : ""})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${casing2(name)}: real(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const keyLength = "timestamp".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig3({ fsp, mode: "'string'" });
        let out = params ? `${casing2(name)}: timestamp(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName5({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
        out += onUpdateNow;
        return out;
      }
      if (lowered.startsWith("time")) {
        const keyLength = "time".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig3({ fsp });
        let out = params ? `${casing2(name)}: time(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName5({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "date") {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	${casing2(
          name
        )}: date(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "text") {
        let out = `${casing2(name)}: text(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "tinytext") {
        let out = `${casing2(name)}: tinytext(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "mediumtext") {
        let out = `${casing2(name)}: mediumtext(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "longtext") {
        let out = `${casing2(name)}: longtext(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "year") {
        let out = `${casing2(name)}: year(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "json") {
        let out = `${casing2(name)}: json(${dbColumnName5({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefaultForJson2(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out = `${casing2(
          name
        )}: varchar(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "varchar".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("char")) {
        let out = `${casing2(
          name
        )}: char(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "char".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("datetime")) {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	`;
        const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
        out = fsp ? `${casing2(
          name
        )}: datetime(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
          "datetime".length + 1,
          lowered.length - 1
        )} })` : `${casing2(name)}: datetime(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("decimal")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
          const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig3(params) : void 0;
        let out = params ? `${casing2(name)}: decimal(${dbColumnName5({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName5({ name, casing: rawCasing })})`;
        defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("binary")) {
        const keyLength = "binary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig2({ length });
        let out = params ? `${casing2(name)}: binary(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName5({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("enum")) {
        const values = lowered.substring("enum".length + 1, lowered.length - 1);
        let out = `${casing2(name)}: singlestoreEnum(${dbColumnName5({ name, casing: rawCasing, withMode: true })}[${values}])`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("varbinary")) {
        const keyLength = "varbinary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig2({ length });
        let out = params ? `${casing2(name)}: varbinary(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName5({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("vector")) {
        const [dimensions, elementType] = lowered.substring("vector".length + 1, lowered.length - 1).split(",");
        let out = `${casing2(name)}: vector(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ dimensions: ${dimensions}, elementType: ${elementType} })`;
        out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
        return out;
      }
      console.log("uknown", type);
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns5 = (columns, casing2, rawCasing, tableName, schema6) => {
      let statement = "";
      columns.forEach((it) => {
        var _a2, _b, _c;
        statement += "	";
        statement += column10(
          it.type,
          it.name,
          casing2,
          rawCasing,
          it.default,
          it.autoincrement,
          it.onUpdate,
          ((_c = (_b = (_a2 = schema6.internal) == null ? void 0 : _a2.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
        );
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
          /`/g,
          "\\`"
        )}\`, { mode: "${it.generated.type}" })` : "";
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes5 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = casing2(idxKey);
        const indexGeneratedName = indexName3(tableName, it.columns);
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques5 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTablePKs5 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        let idxKey = casing2(it.name);
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c3) => {
          return `table.${casing2(c3)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += "),";
      });
      return statement;
    };
  }
});

// src/cli/commands/introspect.ts
var introspect_exports = {};
__export(introspect_exports, {
  introspectGel: () => introspectGel,
  introspectLibSQL: () => introspectLibSQL,
  introspectMysql: () => introspectMysql,
  introspectPostgres: () => introspectPostgres,
  introspectSingleStore: () => introspectSingleStore,
  introspectSqlite: () => introspectSqlite,
  relationsToTypeScript: () => relationsToTypeScript
});
var import_fs11, import_hanji14, import_path7, import_pluralize, introspectPostgres, introspectGel, introspectMysql, introspectSingleStore, introspectSqlite, introspectLibSQL, withCasing4, relationsToTypeScript;
var init_introspect = __esm({
  "src/cli/commands/introspect.ts"() {
    "use strict";
    init_source();
    import_fs11 = require("fs");
    import_hanji14 = __toESM(require_hanji());
    init_mjs();
    import_path7 = require("path");
    import_pluralize = __toESM(require_pluralize());
    init_singlestoreSchema();
    init_global();
    init_introspect_gel();
    init_introspect_mysql();
    init_introspect_pg();
    init_introspect_singlestore();
    init_introspect_sqlite();
    init_gelSerializer();
    init_mysqlSchema();
    init_mysqlSerializer();
    init_pgSchema();
    init_pgSerializer();
    init_singlestoreSerializer();
    init_sqliteSchema();
    init_sqliteSerializer();
    init_snapshotsDiffer();
    init_utils2();
    init_views();
    init_migrate();
    introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await preparePostgresDB2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress(true);
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase2(
          db,
          filter2,
          schemasFilter,
          entities,
          (stage, count, status) => {
            progress.update(stage, count, status);
          }
        )
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript4(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "postgresql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
          squashPgScheme(dryPg),
          squashPgScheme(schema6),
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          dryPg,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectGel = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
      const { prepareGelDB: prepareGelDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await prepareGelDB2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress(true);
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase5(
          db,
          filter2,
          schemasFilter,
          entities,
          (stage, count, status) => {
            progress.update(stage, count, status);
          }
        )
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript2(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectMysql = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { db, database } = await connectToMySQL2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase(db, database, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript3(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "mysql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyMysqlSnapshotsDiff(
          squashMysqlScheme(dryMySql),
          squashMysqlScheme(schema6),
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          dryMySql,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectSingleStore = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { db, database } = await connectToSingleStore2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase4(db, database, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript5(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "postgresql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashSingleStoreScheme(drySingleStore),
          squashSingleStoreScheme(schema6),
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          drySingleStore,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      process.exit(0);
    };
    introspectSqlite = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToSQLite2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "sqlite");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashSqliteScheme(drySQLite),
          squashSqliteScheme(schema6),
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          drySQLite,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectLibSQL = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToLibSQL2(credentials2);
      const matchers = tablesFilter.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "sqlite");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashSqliteScheme(drySQLite),
          squashSqliteScheme(schema6),
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          drySQLite,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    withCasing4 = (value, casing2) => {
      if (casing2 === "preserve") {
        return value;
      }
      if (casing2 === "camel") {
        return value.camelCase();
      }
      assertUnreachable(casing2);
    };
    relationsToTypeScript = (schema6, casing2) => {
      const imports = [];
      const tableRelations = {};
      Object.values(schema6.tables).forEach((table6) => {
        Object.values(table6.foreignKeys).forEach((fk5) => {
          const tableNameFrom = paramNameFor2(fk5.tableFrom, table6.schema);
          const tableNameTo = paramNameFor2(fk5.tableTo, fk5.schemaTo);
          const tableFrom = withCasing4(tableNameFrom.replace(/:+/g, ""), casing2);
          const tableTo = withCasing4(tableNameTo.replace(/:+/g, ""), casing2);
          const columnFrom = withCasing4(fk5.columnsFrom[0], casing2);
          const columnTo = withCasing4(fk5.columnsTo[0], casing2);
          imports.push(tableTo, tableFrom);
          const keyFrom = tableFrom;
          if (!tableRelations[keyFrom]) {
            tableRelations[keyFrom] = [];
          }
          tableRelations[keyFrom].push({
            name: (0, import_pluralize.singular)(tableTo),
            type: "one",
            tableFrom,
            columnFrom,
            tableTo,
            columnTo
          });
          const keyTo = tableTo;
          if (!tableRelations[keyTo]) {
            tableRelations[keyTo] = [];
          }
          tableRelations[keyTo].push({
            name: (0, import_pluralize.plural)(tableFrom),
            type: "many",
            tableFrom: tableTo,
            columnFrom: columnTo,
            tableTo: tableFrom,
            columnTo: columnFrom
          });
        });
      });
      const uniqueImports = [...new Set(imports)];
      const importsTs = `import { relations } from "drizzle-orm/relations";
import { ${uniqueImports.join(
        ", "
      )} } from "./schema";

`;
      const relationStatements = Object.entries(tableRelations).map(
        ([table6, relations5]) => {
          const hasOne = relations5.some((it) => it.type === "one");
          const hasMany = relations5.some((it) => it.type === "many");
          const preparedRelations = relations5.map(
            (relation, relationIndex, originArray) => {
              let name = relation.name;
              let relationName;
              const hasMultipleRelations = originArray.some(
                (it, originIndex) => relationIndex !== originIndex && it.tableTo === relation.tableTo
              );
              if (hasMultipleRelations) {
                relationName = relation.type === "one" ? `${relation.tableFrom}_${relation.columnFrom}_${relation.tableTo}_${relation.columnTo}` : `${relation.tableTo}_${relation.columnTo}_${relation.tableFrom}_${relation.columnFrom}`;
              }
              const hasDuplicatedRelation = originArray.some(
                (it, originIndex) => relationIndex !== originIndex && it.name === relation.name
              );
              if (hasDuplicatedRelation) {
                name = `${relation.name}_${relation.type === "one" ? relation.columnFrom : relation.columnTo}`;
              }
              return {
                ...relation,
                name,
                relationName
              };
            }
          );
          const fields = preparedRelations.map((relation) => {
            if (relation.type === "one") {
              return `	${relation.name}: one(${relation.tableTo}, {
		fields: [${relation.tableFrom}.${relation.columnFrom}],
		references: [${relation.tableTo}.${relation.columnTo}]${relation.relationName ? `,
		relationName: "${relation.relationName}"` : ""}
	}),`;
            } else {
              return `	${relation.name}: many(${relation.tableTo}${relation.relationName ? `, {
		relationName: "${relation.relationName}"
	}` : ""}),`;
            }
          });
          return `export const ${table6}Relations = relations(${table6}, ({${hasOne ? "one" : ""}${hasOne && hasMany ? ", " : ""}${hasMany ? "many" : ""}}) => ({
${fields.join("\n")}
}));`;
        }
      );
      return {
        file: importsTs + relationStatements.join("\n\n")
      };
    };
  }
});

// ../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs
function writeFromReadableStream(stream, writable) {
  if (stream.locked) {
    throw new TypeError("ReadableStream is locked.");
  } else if (writable.destroyed) {
    stream.cancel();
    return;
  }
  const reader = stream.getReader();
  writable.on("close", cancel);
  writable.on("error", cancel);
  reader.read().then(flow, cancel);
  return reader.closed.finally(() => {
    writable.off("close", cancel);
    writable.off("error", cancel);
  });
  function cancel(error2) {
    reader.cancel(error2).catch(() => {
    });
    if (error2) {
      writable.destroy(error2);
    }
  }
  function onDrain() {
    reader.read().then(flow, cancel);
  }
  function flow({ done, value }) {
    try {
      if (done) {
        writable.end();
      } else if (!writable.write(value)) {
        writable.once("drain", onDrain);
      } else {
        return reader.read().then(flow, cancel);
      }
    } catch (e4) {
      cancel(e4);
    }
  }
}
var import_http, import_http2, import_stream2, import_crypto7, RequestError, toRequestError, GlobalRequest, Request3, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response22, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
var init_dist2 = __esm({
  "../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs"() {
    import_http = require("http");
    import_http2 = require("http2");
    import_stream2 = require("stream");
    import_crypto7 = __toESM(require("crypto"), 1);
    RequestError = class extends Error {
      constructor(message, options) {
        super(message, options);
        this.name = "RequestError";
      }
    };
    toRequestError = (e4) => {
      if (e4 instanceof RequestError) {
        return e4;
      }
      return new RequestError(e4.message, { cause: e4 });
    };
    GlobalRequest = global.Request;
    Request3 = class extends GlobalRequest {
      constructor(input, options) {
        var _a2;
        if (typeof input === "object" && getRequestCache in input) {
          input = input[getRequestCache]();
        }
        if (typeof ((_a2 = options == null ? void 0 : options.body) == null ? void 0 : _a2.getReader) !== "undefined") {
          ;
          options.duplex ??= "half";
        }
        super(input, options);
      }
    };
    newRequestFromIncoming = (method, url, incoming, abortController) => {
      const headerRecord = [];
      const rawHeaders = incoming.rawHeaders;
      for (let i4 = 0; i4 < rawHeaders.length; i4 += 2) {
        const { [i4]: key, [i4 + 1]: value } = rawHeaders;
        if (key.charCodeAt(0) !== /*:*/
        58) {
          headerRecord.push([key, value]);
        }
      }
      const init2 = {
        method,
        headers: headerRecord,
        signal: abortController.signal
      };
      if (method === "TRACE") {
        init2.method = "GET";
        const req = new Request3(url, init2);
        Object.defineProperty(req, "method", {
          get() {
            return "TRACE";
          }
        });
        return req;
      }
      if (!(method === "GET" || method === "HEAD")) {
        if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
          init2.body = new ReadableStream({
            start(controller) {
              controller.enqueue(incoming.rawBody);
              controller.close();
            }
          });
        } else {
          init2.body = import_stream2.Readable.toWeb(incoming);
        }
      }
      return new Request3(url, init2);
    };
    getRequestCache = Symbol("getRequestCache");
    requestCache = Symbol("requestCache");
    incomingKey = Symbol("incomingKey");
    urlKey = Symbol("urlKey");
    abortControllerKey = Symbol("abortControllerKey");
    getAbortController = Symbol("getAbortController");
    requestPrototype = {
      get method() {
        return this[incomingKey].method || "GET";
      },
      get url() {
        return this[urlKey];
      },
      [getAbortController]() {
        this[getRequestCache]();
        return this[abortControllerKey];
      },
      [getRequestCache]() {
        this[abortControllerKey] ||= new AbortController();
        return this[requestCache] ||= newRequestFromIncoming(
          this.method,
          this[urlKey],
          this[incomingKey],
          this[abortControllerKey]
        );
      }
    };
    [
      "body",
      "bodyUsed",
      "cache",
      "credentials",
      "destination",
      "headers",
      "integrity",
      "mode",
      "redirect",
      "referrer",
      "referrerPolicy",
      "signal",
      "keepalive"
    ].forEach((k3) => {
      Object.defineProperty(requestPrototype, k3, {
        get() {
          return this[getRequestCache]()[k3];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k3) => {
      Object.defineProperty(requestPrototype, k3, {
        value: function() {
          return this[getRequestCache]()[k3]();
        }
      });
    });
    Object.setPrototypeOf(requestPrototype, Request3.prototype);
    newRequest = (incoming, defaultHostname) => {
      const req = Object.create(requestPrototype);
      req[incomingKey] = incoming;
      const incomingUrl = incoming.url || "";
      if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
      (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
        if (incoming instanceof import_http2.Http2ServerRequest) {
          throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
        }
        try {
          const url2 = new URL(incomingUrl);
          req[urlKey] = url2.href;
        } catch (e4) {
          throw new RequestError("Invalid absolute URL", { cause: e4 });
        }
        return req;
      }
      const host = (incoming instanceof import_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
      if (!host) {
        throw new RequestError("Missing host header");
      }
      let scheme;
      if (incoming instanceof import_http2.Http2ServerRequest) {
        scheme = incoming.scheme;
        if (!(scheme === "http" || scheme === "https")) {
          throw new RequestError("Unsupported scheme");
        }
      } else {
        scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
      }
      const url = new URL(`${scheme}://${host}${incomingUrl}`);
      if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
        throw new RequestError("Invalid host header");
      }
      req[urlKey] = url.href;
      return req;
    };
    responseCache = Symbol("responseCache");
    getResponseCache = Symbol("getResponseCache");
    cacheKey = Symbol("cache");
    GlobalResponse = global.Response;
    Response22 = class _Response {
      #body;
      #init;
      [getResponseCache]() {
        delete this[cacheKey];
        return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
      }
      constructor(body, init2) {
        let headers;
        this.#body = body;
        if (init2 instanceof _Response) {
          const cachedGlobalResponse = init2[responseCache];
          if (cachedGlobalResponse) {
            this.#init = cachedGlobalResponse;
            this[getResponseCache]();
            return;
          } else {
            this.#init = init2.#init;
            headers = new Headers(init2.#init.headers);
          }
        } else {
          this.#init = init2;
        }
        if (typeof body === "string" || typeof (body == null ? void 0 : body.getReader) !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
          headers ||= (init2 == null ? void 0 : init2.headers) || { "content-type": "text/plain; charset=UTF-8" };
          this[cacheKey] = [(init2 == null ? void 0 : init2.status) || 200, body, headers];
        }
      }
      get headers() {
        const cache3 = this[cacheKey];
        if (cache3) {
          if (!(cache3[2] instanceof Headers)) {
            cache3[2] = new Headers(cache3[2]);
          }
          return cache3[2];
        }
        return this[getResponseCache]().headers;
      }
      get status() {
        var _a2;
        return ((_a2 = this[cacheKey]) == null ? void 0 : _a2[0]) ?? this[getResponseCache]().status;
      }
      get ok() {
        const status = this.status;
        return status >= 200 && status < 300;
      }
    };
    ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k3) => {
      Object.defineProperty(Response22.prototype, k3, {
        get() {
          return this[getResponseCache]()[k3];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k3) => {
      Object.defineProperty(Response22.prototype, k3, {
        value: function() {
          return this[getResponseCache]()[k3]();
        }
      });
    });
    Object.setPrototypeOf(Response22, GlobalResponse);
    Object.setPrototypeOf(Response22.prototype, GlobalResponse.prototype);
    buildOutgoingHttpHeaders = (headers) => {
      const res = {};
      if (!(headers instanceof Headers)) {
        headers = new Headers(headers ?? void 0);
      }
      const cookies = [];
      for (const [k3, v6] of headers) {
        if (k3 === "set-cookie") {
          cookies.push(v6);
        } else {
          res[k3] = v6;
        }
      }
      if (cookies.length > 0) {
        res["set-cookie"] = cookies;
      }
      res["content-type"] ??= "text/plain; charset=UTF-8";
      return res;
    };
    X_ALREADY_SENT = "x-hono-already-sent";
    webFetch = global.fetch;
    if (typeof global.crypto === "undefined") {
      global.crypto = import_crypto7.default;
    }
    global.fetch = (info2, init2) => {
      init2 = {
        // Disable compression handling so people can return the result of a fetch
        // directly in the loader without messing with the Content-Encoding header.
        compress: false,
        ...init2
      };
      return webFetch(info2, init2);
    };
    regBuffer = /^no$/i;
    regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
    handleRequestError = () => new Response(null, {
      status: 400
    });
    handleFetchError = (e4) => new Response(null, {
      status: e4 instanceof Error && (e4.name === "TimeoutError" || e4.constructor.name === "TimeoutError") ? 504 : 500
    });
    handleResponseError = (e4, outgoing) => {
      const err2 = e4 instanceof Error ? e4 : new Error("unknown error", { cause: e4 });
      if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
        console.info("The user aborted a request.");
      } else {
        console.error(e4);
        if (!outgoing.headersSent) {
          outgoing.writeHead(500, { "Content-Type": "text/plain" });
        }
        outgoing.end(`Error: ${err2.message}`);
        outgoing.destroy(err2);
      }
    };
    responseViaCache = async (res, outgoing) => {
      var _a2;
      let [status, body, header] = res[cacheKey];
      if (header instanceof Headers) {
        header = buildOutgoingHttpHeaders(header);
      }
      if (typeof body === "string") {
        header["Content-Length"] = Buffer.byteLength(body);
      } else if (body instanceof Uint8Array) {
        header["Content-Length"] = body.byteLength;
      } else if (body instanceof Blob) {
        header["Content-Length"] = body.size;
      }
      outgoing.writeHead(status, header);
      if (typeof body === "string" || body instanceof Uint8Array) {
        outgoing.end(body);
      } else if (body instanceof Blob) {
        outgoing.end(new Uint8Array(await body.arrayBuffer()));
      } else {
        return (_a2 = writeFromReadableStream(body, outgoing)) == null ? void 0 : _a2.catch(
          (e4) => handleResponseError(e4, outgoing)
        );
      }
    };
    responseViaResponseObject = async (res, outgoing, options = {}) => {
      if (res instanceof Promise) {
        if (options.errorHandler) {
          try {
            res = await res;
          } catch (err2) {
            const errRes = await options.errorHandler(err2);
            if (!errRes) {
              return;
            }
            res = errRes;
          }
        } else {
          res = await res.catch(handleFetchError);
        }
      }
      if (cacheKey in res) {
        return responseViaCache(res, outgoing);
      }
      const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
      if (res.body) {
        const {
          "transfer-encoding": transferEncoding,
          "content-encoding": contentEncoding,
          "content-length": contentLength,
          "x-accel-buffering": accelBuffering,
          "content-type": contentType
        } = resHeaderRecord;
        if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
        accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
          outgoing.writeHead(res.status, resHeaderRecord);
          await writeFromReadableStream(res.body, outgoing);
        } else {
          const buffer = await res.arrayBuffer();
          resHeaderRecord["content-length"] = buffer.byteLength;
          outgoing.writeHead(res.status, resHeaderRecord);
          outgoing.end(new Uint8Array(buffer));
        }
      } else if (resHeaderRecord[X_ALREADY_SENT]) {
      } else {
        outgoing.writeHead(res.status, resHeaderRecord);
        outgoing.end();
      }
    };
    getRequestListener = (fetchCallback, options = {}) => {
      if (options.overrideGlobalObjects !== false && global.Request !== Request3) {
        Object.defineProperty(global, "Request", {
          value: Request3
        });
        Object.defineProperty(global, "Response", {
          value: Response22
        });
      }
      return async (incoming, outgoing) => {
        let res, req;
        try {
          req = newRequest(incoming, options.hostname);
          outgoing.on("close", () => {
            const abortController = req[abortControllerKey];
            if (!abortController) {
              return;
            }
            if (incoming.errored) {
              req[abortControllerKey].abort(incoming.errored.toString());
            } else if (!outgoing.writableFinished) {
              req[abortControllerKey].abort("Client connection prematurely closed.");
            }
          });
          res = fetchCallback(req, { incoming, outgoing });
          if (cacheKey in res) {
            return responseViaCache(res, outgoing);
          }
        } catch (e4) {
          if (!res) {
            if (options.errorHandler) {
              res = await options.errorHandler(req ? e4 : toRequestError(e4));
              if (!res) {
                return;
              }
            } else if (!req) {
              res = handleRequestError();
            } else {
              res = handleFetchError(e4);
            }
          } else {
            return handleResponseError(e4, outgoing);
          }
        }
        try {
          return await responseViaResponseObject(res, outgoing, options);
        } catch (e4) {
          return handleResponseError(e4, outgoing);
        }
      };
    };
    createAdaptorServer = (options) => {
      const fetchCallback = options.fetch;
      const requestListener = getRequestListener(fetchCallback, {
        hostname: options.hostname,
        overrideGlobalObjects: options.overrideGlobalObjects
      });
      const createServer2 = options.createServer || import_http.createServer;
      const server = createServer2(options.serverOptions || {}, requestListener);
      return server;
    };
    serve = (options, listeningListener) => {
      const server = createAdaptorServer(options);
      server.listen((options == null ? void 0 : options.port) ?? 3e3, options.hostname, () => {
        const serverInfo = server.address();
        listeningListener && listeningListener(serverInfo);
      });
      return server;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js
var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecode, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_;
var init_url = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js"() {
    splitPath = (path4) => {
      const paths = path4.split("/");
      if (paths[0] === "") {
        paths.shift();
      }
      return paths;
    };
    splitRoutingPath = (routePath) => {
      const { groups, path: path4 } = extractGroupsFromPath(routePath);
      const paths = splitPath(path4);
      return replaceGroupMarks(paths, groups);
    };
    extractGroupsFromPath = (path4) => {
      const groups = [];
      path4 = path4.replace(/\{[^}]+\}/g, (match2, index6) => {
        const mark = `@${index6}`;
        groups.push([mark, match2]);
        return mark;
      });
      return { groups, path: path4 };
    };
    replaceGroupMarks = (paths, groups) => {
      for (let i4 = groups.length - 1; i4 >= 0; i4--) {
        const [mark] = groups[i4];
        for (let j3 = paths.length - 1; j3 >= 0; j3--) {
          if (paths[j3].includes(mark)) {
            paths[j3] = paths[j3].replace(mark, groups[i4][1]);
            break;
          }
        }
      }
      return paths;
    };
    patternCache = {};
    getPattern = (label, next) => {
      if (label === "*") {
        return "*";
      }
      const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
      if (match2) {
        const cacheKey2 = `${label}#${next}`;
        if (!patternCache[cacheKey2]) {
          if (match2[2]) {
            patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
          } else {
            patternCache[cacheKey2] = [label, match2[1], true];
          }
        }
        return patternCache[cacheKey2];
      }
      return null;
    };
    tryDecode = (str, decoder) => {
      try {
        return decoder(str);
      } catch {
        return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
          try {
            return decoder(match2);
          } catch {
            return match2;
          }
        });
      }
    };
    tryDecodeURI = (str) => tryDecode(str, decodeURI);
    getPath = (request) => {
      const url = request.url;
      const start = url.indexOf("/", 8);
      let i4 = start;
      for (; i4 < url.length; i4++) {
        const charCode = url.charCodeAt(i4);
        if (charCode === 37) {
          const queryIndex = url.indexOf("?", i4);
          const path4 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
          return tryDecodeURI(path4.includes("%25") ? path4.replace(/%25/g, "%2525") : path4);
        } else if (charCode === 63) {
          break;
        }
      }
      return url.slice(start, i4);
    };
    getPathNoStrict = (request) => {
      const result = getPath(request);
      return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
    };
    mergePath = (base, sub, ...rest) => {
      if (rest.length) {
        sub = mergePath(sub, ...rest);
      }
      return `${(base == null ? void 0 : base[0]) === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${(base == null ? void 0 : base.at(-1)) === "/" ? "" : "/"}${(sub == null ? void 0 : sub[0]) === "/" ? sub.slice(1) : sub}`}`;
    };
    checkOptionalParameter = (path4) => {
      if (path4.charCodeAt(path4.length - 1) !== 63 || !path4.includes(":")) {
        return null;
      }
      const segments = path4.split("/");
      const results = [];
      let basePath = "";
      segments.forEach((segment) => {
        if (segment !== "" && !/\:/.test(segment)) {
          basePath += "/" + segment;
        } else if (/\:/.test(segment)) {
          if (/\?/.test(segment)) {
            if (results.length === 0 && basePath === "") {
              results.push("/");
            } else {
              results.push(basePath);
            }
            const optionalSegment = segment.replace("?", "");
            basePath += "/" + optionalSegment;
            results.push(basePath);
          } else {
            basePath += "/" + segment;
          }
        }
      });
      return results.filter((v6, i4, a3) => a3.indexOf(v6) === i4);
    };
    _decodeURI = (value) => {
      if (!/[%+]/.test(value)) {
        return value;
      }
      if (value.indexOf("+") !== -1) {
        value = value.replace(/\+/g, " ");
      }
      return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
    };
    _getQueryParam = (url, key, multiple) => {
      let encoded;
      if (!multiple && key && !/[%+]/.test(key)) {
        let keyIndex2 = url.indexOf(`?${key}`, 8);
        if (keyIndex2 === -1) {
          keyIndex2 = url.indexOf(`&${key}`, 8);
        }
        while (keyIndex2 !== -1) {
          const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
          if (trailingKeyCode === 61) {
            const valueIndex = keyIndex2 + key.length + 2;
            const endIndex = url.indexOf("&", valueIndex);
            return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
          } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
            return "";
          }
          keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
        }
        encoded = /[%+]/.test(url);
        if (!encoded) {
          return void 0;
        }
      }
      const results = {};
      encoded ??= /[%+]/.test(url);
      let keyIndex = url.indexOf("?", 8);
      while (keyIndex !== -1) {
        const nextKeyIndex = url.indexOf("&", keyIndex + 1);
        let valueIndex = url.indexOf("=", keyIndex);
        if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
          valueIndex = -1;
        }
        let name = url.slice(
          keyIndex + 1,
          valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
        );
        if (encoded) {
          name = _decodeURI(name);
        }
        keyIndex = nextKeyIndex;
        if (name === "") {
          continue;
        }
        let value;
        if (valueIndex === -1) {
          value = "";
        } else {
          value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
          if (encoded) {
            value = _decodeURI(value);
          }
        }
        if (multiple) {
          if (!(results[name] && Array.isArray(results[name]))) {
            results[name] = [];
          }
          ;
          results[name].push(value);
        } else {
          results[name] ??= value;
        }
      }
      return key ? results[key] : results;
    };
    getQueryParam = _getQueryParam;
    getQueryParams = (url, key) => {
      return _getQueryParam(url, key, true);
    };
    decodeURIComponent_ = decodeURIComponent;
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js
var validCookieNameRegEx, validCookieValueRegEx, parse3;
var init_cookie = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js"() {
    init_url();
    validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
    validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
    parse3 = (cookie, name) => {
      if (name && cookie.indexOf(name) === -1) {
        return {};
      }
      const pairs = cookie.trim().split(";");
      const parsedCookie = {};
      for (let pairStr of pairs) {
        pairStr = pairStr.trim();
        const valueStartPos = pairStr.indexOf("=");
        if (valueStartPos === -1) {
          continue;
        }
        const cookieName = pairStr.substring(0, valueStartPos).trim();
        if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
          continue;
        }
        let cookieValue = pairStr.substring(valueStartPos + 1).trim();
        if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
          cookieValue = cookieValue.slice(1, -1);
        }
        if (validCookieValueRegEx.test(cookieValue)) {
          parsedCookie[cookieName] = decodeURIComponent_(cookieValue);
          if (name) {
            break;
          }
        }
      }
      return parsedCookie;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js
var getCookie;
var init_cookie2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js"() {
    init_cookie();
    getCookie = (c3, key, prefix2) => {
      const cookie = c3.req.raw.headers.get("Cookie");
      if (typeof key === "string") {
        if (!cookie) {
          return void 0;
        }
        let finalKey = key;
        if (prefix2 === "secure") {
          finalKey = "__Secure-" + key;
        } else if (prefix2 === "host") {
          finalKey = "__Host-" + key;
        }
        const obj2 = parse3(cookie, finalKey);
        return obj2[finalKey];
      }
      if (!cookie) {
        return {};
      }
      const obj = parse3(cookie);
      return obj;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js
var HTTPException;
var init_http_exception = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js"() {
    HTTPException = class extends Error {
      res;
      status;
      constructor(status = 500, options) {
        super(options == null ? void 0 : options.message, { cause: options == null ? void 0 : options.cause });
        this.res = options == null ? void 0 : options.res;
        this.status = status;
      }
      getResponse() {
        if (this.res) {
          const newResponse = new Response(this.res.body, {
            status: this.status,
            headers: this.res.headers
          });
          return newResponse;
        }
        return new Response(this.message, {
          status: this.status
        });
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js
var init_crypto = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js"() {
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js
var bufferToFormData;
var init_buffer = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js"() {
    init_crypto();
    bufferToFormData = (arrayBuffer, contentType) => {
      const response = new Response(arrayBuffer, {
        headers: {
          "Content-Type": contentType
        }
      });
      return response.formData();
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js
var jsonRegex, multipartRegex, urlencodedRegex, validator;
var init_validator = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js"() {
    init_cookie2();
    init_http_exception();
    init_buffer();
    jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
    multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
    urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
    validator = (target, validationFunc) => {
      return async (c3, next) => {
        let value = {};
        const contentType = c3.req.header("Content-Type");
        switch (target) {
          case "json":
            if (!contentType || !jsonRegex.test(contentType)) {
              break;
            }
            try {
              value = await c3.req.json();
            } catch {
              const message = "Malformed JSON in request body";
              throw new HTTPException(400, { message });
            }
            break;
          case "form": {
            if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
              break;
            }
            let formData;
            if (c3.req.bodyCache.formData) {
              formData = await c3.req.bodyCache.formData;
            } else {
              try {
                const arrayBuffer = await c3.req.arrayBuffer();
                formData = await bufferToFormData(arrayBuffer, contentType);
                c3.req.bodyCache.formData = formData;
              } catch (e4) {
                let message = "Malformed FormData request.";
                message += e4 instanceof Error ? ` ${e4.message}` : ` ${String(e4)}`;
                throw new HTTPException(400, { message });
              }
            }
            const form = {};
            formData.forEach((value2, key) => {
              if (key.endsWith("[]")) {
                ;
                (form[key] ??= []).push(value2);
              } else if (Array.isArray(form[key])) {
                ;
                form[key].push(value2);
              } else if (key in form) {
                form[key] = [form[key], value2];
              } else {
                form[key] = value2;
              }
            });
            value = form;
            break;
          }
          case "query":
            value = Object.fromEntries(
              Object.entries(c3.req.queries()).map(([k3, v6]) => {
                return v6.length === 1 ? [k3, v6[0]] : [k3, v6];
              })
            );
            break;
          case "param":
            value = c3.req.param();
            break;
          case "header":
            value = c3.req.header();
            break;
          case "cookie":
            value = getCookie(c3);
            break;
        }
        const res = await validationFunc(value, c3);
        if (res instanceof Response) {
          return res;
        }
        c3.req.addValidatedData(target, res);
        await next();
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js
var init_validator2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js"() {
    init_validator();
  }
});

// ../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js
var zValidator;
var init_esm2 = __esm({
  "../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js"() {
    init_validator2();
    zValidator = (target, schema6, hook) => (
      // @ts-expect-error not typed well
      validator(target, async (value, c3) => {
        const result = await schema6.safeParseAsync(value);
        if (hook) {
          const hookResult = await hook({ data: value, ...result }, c3);
          if (hookResult) {
            if (hookResult instanceof Response) {
              return hookResult;
            }
            if ("response" in hookResult) {
              return hookResult.response;
            }
          }
        }
        if (!result.success) {
          return c3.json(result, 400);
        }
        return result.data;
      })
    );
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js
var compose;
var init_compose = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js"() {
    compose = (middleware, onError, onNotFound) => {
      return (context, next) => {
        let index6 = -1;
        return dispatch(0);
        async function dispatch(i4) {
          if (i4 <= index6) {
            throw new Error("next() called multiple times");
          }
          index6 = i4;
          let res;
          let isError = false;
          let handler;
          if (middleware[i4]) {
            handler = middleware[i4][0][0];
            context.req.routeIndex = i4;
          } else {
            handler = i4 === middleware.length && next || void 0;
          }
          if (handler) {
            try {
              res = await handler(context, () => dispatch(i4 + 1));
            } catch (err2) {
              if (err2 instanceof Error && onError) {
                context.error = err2;
                res = await onError(err2, context);
                isError = true;
              } else {
                throw err2;
              }
            }
          } else {
            if (context.finalized === false && onNotFound) {
              res = await onNotFound(context);
            }
          }
          if (res && (context.finalized === false || isError)) {
            context.res = res;
          }
          return context;
        }
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js
async function parseFormData(request, options) {
  const formData = await request.formData();
  if (formData) {
    return convertFormDataToBodyData(formData, options);
  }
  return {};
}
function convertFormDataToBodyData(formData, options) {
  const form = /* @__PURE__ */ Object.create(null);
  formData.forEach((value, key) => {
    const shouldParseAllValues = options.all || key.endsWith("[]");
    if (!shouldParseAllValues) {
      form[key] = value;
    } else {
      handleParsingAllValues(form, key, value);
    }
  });
  if (options.dot) {
    Object.entries(form).forEach(([key, value]) => {
      const shouldParseDotValues = key.includes(".");
      if (shouldParseDotValues) {
        handleParsingNestedValues(form, key, value);
        delete form[key];
      }
    });
  }
  return form;
}
var parseBody, handleParsingAllValues, handleParsingNestedValues;
var init_body2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js"() {
    init_request2();
    parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
      const { all = false, dot = false } = options;
      const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
      const contentType = headers.get("Content-Type");
      if ((contentType == null ? void 0 : contentType.startsWith("multipart/form-data")) || (contentType == null ? void 0 : contentType.startsWith("application/x-www-form-urlencoded"))) {
        return parseFormData(request, { all, dot });
      }
      return {};
    };
    handleParsingAllValues = (form, key, value) => {
      if (form[key] !== void 0) {
        if (Array.isArray(form[key])) {
          ;
          form[key].push(value);
        } else {
          form[key] = [form[key], value];
        }
      } else {
        form[key] = value;
      }
    };
    handleParsingNestedValues = (form, key, value) => {
      let nestedForm = form;
      const keys = key.split(".");
      keys.forEach((key2, index6) => {
        if (index6 === keys.length - 1) {
          nestedForm[key2] = value;
        } else {
          if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
            nestedForm[key2] = /* @__PURE__ */ Object.create(null);
          }
          nestedForm = nestedForm[key2];
        }
      });
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js
var tryDecodeURIComponent, HonoRequest;
var init_request2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js"() {
    init_body2();
    init_url();
    tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
    HonoRequest = class {
      raw;
      #validatedData;
      #matchResult;
      routeIndex = 0;
      path;
      bodyCache = {};
      constructor(request, path4 = "/", matchResult = [[]]) {
        this.raw = request;
        this.path = path4;
        this.#matchResult = matchResult;
        this.#validatedData = {};
      }
      param(key) {
        return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
      }
      #getDecodedParam(key) {
        const paramKey = this.#matchResult[0][this.routeIndex][1][key];
        const param = this.#getParamValue(paramKey);
        return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
      }
      #getAllDecodedParams() {
        const decoded = {};
        const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
        for (const key of keys) {
          const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
          if (value && typeof value === "string") {
            decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
          }
        }
        return decoded;
      }
      #getParamValue(paramKey) {
        return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
      }
      query(key) {
        return getQueryParam(this.url, key);
      }
      queries(key) {
        return getQueryParams(this.url, key);
      }
      header(name) {
        if (name) {
          return this.raw.headers.get(name) ?? void 0;
        }
        const headerData = {};
        this.raw.headers.forEach((value, key) => {
          headerData[key] = value;
        });
        return headerData;
      }
      async parseBody(options) {
        return this.bodyCache.parsedBody ??= await parseBody(this, options);
      }
      #cachedBody = (key) => {
        const { bodyCache, raw: raw2 } = this;
        const cachedBody = bodyCache[key];
        if (cachedBody) {
          return cachedBody;
        }
        const anyCachedKey = Object.keys(bodyCache)[0];
        if (anyCachedKey) {
          return bodyCache[anyCachedKey].then((body) => {
            if (anyCachedKey === "json") {
              body = JSON.stringify(body);
            }
            return new Response(body)[key]();
          });
        }
        return bodyCache[key] = raw2[key]();
      };
      json() {
        return this.#cachedBody("json");
      }
      text() {
        return this.#cachedBody("text");
      }
      arrayBuffer() {
        return this.#cachedBody("arrayBuffer");
      }
      blob() {
        return this.#cachedBody("blob");
      }
      formData() {
        return this.#cachedBody("formData");
      }
      addValidatedData(target, data) {
        this.#validatedData[target] = data;
      }
      valid(target) {
        return this.#validatedData[target];
      }
      get url() {
        return this.raw.url;
      }
      get method() {
        return this.raw.method;
      }
      get matchedRoutes() {
        return this.#matchResult[0].map(([[, route]]) => route);
      }
      get routePath() {
        return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase, raw, resolveCallback;
var init_html = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js"() {
    HtmlEscapedCallbackPhase = {
      Stringify: 1,
      BeforeStream: 2,
      Stream: 3
    };
    raw = (value, callbacks) => {
      const escapedString = new String(value);
      escapedString.isEscaped = true;
      escapedString.callbacks = callbacks;
      return escapedString;
    };
    resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
      if (typeof str === "object" && !(str instanceof String)) {
        if (!(str instanceof Promise)) {
          str = str.toString();
        }
        if (str instanceof Promise) {
          str = await str;
        }
      }
      const callbacks = str.callbacks;
      if (!(callbacks == null ? void 0 : callbacks.length)) {
        return Promise.resolve(str);
      }
      if (buffer) {
        buffer[0] += str;
      } else {
        buffer = [str];
      }
      const resStr = Promise.all(callbacks.map((c3) => c3({ phase, buffer, context }))).then(
        (res) => Promise.all(
          res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
        ).then(() => buffer[0])
      );
      if (preserveCallbacks) {
        return raw(await resStr, callbacks);
      } else {
        return resStr;
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js
var TEXT_PLAIN, setHeaders, Context;
var init_context = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js"() {
    init_request2();
    init_html();
    TEXT_PLAIN = "text/plain; charset=UTF-8";
    setHeaders = (headers, map2 = {}) => {
      for (const key of Object.keys(map2)) {
        headers.set(key, map2[key]);
      }
      return headers;
    };
    Context = class {
      #rawRequest;
      #req;
      env = {};
      #var;
      finalized = false;
      error;
      #status = 200;
      #executionCtx;
      #headers;
      #preparedHeaders;
      #res;
      #isFresh = true;
      #layout;
      #renderer;
      #notFoundHandler;
      #matchResult;
      #path;
      constructor(req, options) {
        this.#rawRequest = req;
        if (options) {
          this.#executionCtx = options.executionCtx;
          this.env = options.env;
          this.#notFoundHandler = options.notFoundHandler;
          this.#path = options.path;
          this.#matchResult = options.matchResult;
        }
      }
      get req() {
        this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
        return this.#req;
      }
      get event() {
        if (this.#executionCtx && "respondWith" in this.#executionCtx) {
          return this.#executionCtx;
        } else {
          throw Error("This context has no FetchEvent");
        }
      }
      get executionCtx() {
        if (this.#executionCtx) {
          return this.#executionCtx;
        } else {
          throw Error("This context has no ExecutionContext");
        }
      }
      get res() {
        this.#isFresh = false;
        return this.#res ||= new Response("404 Not Found", { status: 404 });
      }
      set res(_res) {
        this.#isFresh = false;
        if (this.#res && _res) {
          _res = new Response(_res.body, _res);
          for (const [k3, v6] of this.#res.headers.entries()) {
            if (k3 === "content-type") {
              continue;
            }
            if (k3 === "set-cookie") {
              const cookies = this.#res.headers.getSetCookie();
              _res.headers.delete("set-cookie");
              for (const cookie of cookies) {
                _res.headers.append("set-cookie", cookie);
              }
            } else {
              _res.headers.set(k3, v6);
            }
          }
        }
        this.#res = _res;
        this.finalized = true;
      }
      render = (...args) => {
        this.#renderer ??= (content) => this.html(content);
        return this.#renderer(...args);
      };
      setLayout = (layout) => this.#layout = layout;
      getLayout = () => this.#layout;
      setRenderer = (renderer) => {
        this.#renderer = renderer;
      };
      header = (name, value, options) => {
        if (this.finalized) {
          this.#res = new Response(this.#res.body, this.#res);
        }
        if (value === void 0) {
          if (this.#headers) {
            this.#headers.delete(name);
          } else if (this.#preparedHeaders) {
            delete this.#preparedHeaders[name.toLocaleLowerCase()];
          }
          if (this.finalized) {
            this.res.headers.delete(name);
          }
          return;
        }
        if (options == null ? void 0 : options.append) {
          if (!this.#headers) {
            this.#isFresh = false;
            this.#headers = new Headers(this.#preparedHeaders);
            this.#preparedHeaders = {};
          }
          this.#headers.append(name, value);
        } else {
          if (this.#headers) {
            this.#headers.set(name, value);
          } else {
            this.#preparedHeaders ??= {};
            this.#preparedHeaders[name.toLowerCase()] = value;
          }
        }
        if (this.finalized) {
          if (options == null ? void 0 : options.append) {
            this.res.headers.append(name, value);
          } else {
            this.res.headers.set(name, value);
          }
        }
      };
      status = (status) => {
        this.#isFresh = false;
        this.#status = status;
      };
      set = (key, value) => {
        this.#var ??= /* @__PURE__ */ new Map();
        this.#var.set(key, value);
      };
      get = (key) => {
        return this.#var ? this.#var.get(key) : void 0;
      };
      get var() {
        if (!this.#var) {
          return {};
        }
        return Object.fromEntries(this.#var);
      }
      #newResponse(data, arg, headers) {
        if (this.#isFresh && !headers && !arg && this.#status === 200) {
          return new Response(data, {
            headers: this.#preparedHeaders
          });
        }
        if (arg && typeof arg !== "number") {
          const header = new Headers(arg.headers);
          if (this.#headers) {
            this.#headers.forEach((v6, k3) => {
              if (k3 === "set-cookie") {
                header.append(k3, v6);
              } else {
                header.set(k3, v6);
              }
            });
          }
          const headers2 = setHeaders(header, this.#preparedHeaders);
          return new Response(data, {
            headers: headers2,
            status: arg.status ?? this.#status
          });
        }
        const status = typeof arg === "number" ? arg : this.#status;
        this.#preparedHeaders ??= {};
        this.#headers ??= new Headers();
        setHeaders(this.#headers, this.#preparedHeaders);
        if (this.#res) {
          this.#res.headers.forEach((v6, k3) => {
            var _a2, _b;
            if (k3 === "set-cookie") {
              (_a2 = this.#headers) == null ? void 0 : _a2.append(k3, v6);
            } else {
              (_b = this.#headers) == null ? void 0 : _b.set(k3, v6);
            }
          });
          setHeaders(this.#headers, this.#preparedHeaders);
        }
        headers ??= {};
        for (const [k3, v6] of Object.entries(headers)) {
          if (typeof v6 === "string") {
            this.#headers.set(k3, v6);
          } else {
            this.#headers.delete(k3);
            for (const v22 of v6) {
              this.#headers.append(k3, v22);
            }
          }
        }
        return new Response(data, {
          status,
          headers: this.#headers
        });
      }
      newResponse = (...args) => this.#newResponse(...args);
      body = (data, arg, headers) => {
        return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
      };
      text = (text, arg, headers) => {
        if (!this.#preparedHeaders) {
          if (this.#isFresh && !headers && !arg) {
            return new Response(text);
          }
          this.#preparedHeaders = {};
        }
        this.#preparedHeaders["content-type"] = TEXT_PLAIN;
        if (typeof arg === "number") {
          return this.#newResponse(text, arg, headers);
        }
        return this.#newResponse(text, arg);
      };
      json = (object, arg, headers) => {
        const body = JSON.stringify(object);
        this.#preparedHeaders ??= {};
        this.#preparedHeaders["content-type"] = "application/json";
        return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
      };
      html = (html, arg, headers) => {
        this.#preparedHeaders ??= {};
        this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
        if (typeof html === "object") {
          return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
            return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
          });
        }
        return typeof arg === "number" ? this.#newResponse(html, arg, headers) : this.#newResponse(html, arg);
      };
      redirect = (location, status) => {
        this.#headers ??= new Headers();
        this.#headers.set("Location", String(location));
        return this.newResponse(null, status ?? 302);
      };
      notFound = () => {
        this.#notFoundHandler ??= () => new Response();
        return this.#notFoundHandler(this);
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js
var METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS, MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError;
var init_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js"() {
    METHOD_NAME_ALL = "ALL";
    METHOD_NAME_ALL_LOWERCASE = "all";
    METHODS = ["get", "post", "put", "delete", "options", "patch"];
    MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
    UnsupportedPathError = class extends Error {
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js
var COMPOSED_HANDLER;
var init_constants = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js"() {
    COMPOSED_HANDLER = "__COMPOSED_HANDLER";
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js
var notFoundHandler, errorHandler, Hono;
var init_hono_base = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js"() {
    init_compose();
    init_context();
    init_router();
    init_constants();
    init_url();
    notFoundHandler = (c3) => {
      return c3.text("404 Not Found", 404);
    };
    errorHandler = (err2, c3) => {
      if ("getResponse" in err2) {
        return err2.getResponse();
      }
      console.error(err2);
      return c3.text("Internal Server Error", 500);
    };
    Hono = class {
      get;
      post;
      put;
      delete;
      options;
      patch;
      all;
      on;
      use;
      router;
      getPath;
      _basePath = "/";
      #path = "/";
      routes = [];
      constructor(options = {}) {
        const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
        allMethods.forEach((method) => {
          this[method] = (args1, ...args) => {
            if (typeof args1 === "string") {
              this.#path = args1;
            } else {
              this.#addRoute(method, this.#path, args1);
            }
            args.forEach((handler) => {
              this.#addRoute(method, this.#path, handler);
            });
            return this;
          };
        });
        this.on = (method, path4, ...handlers) => {
          for (const p3 of [path4].flat()) {
            this.#path = p3;
            for (const m4 of [method].flat()) {
              handlers.map((handler) => {
                this.#addRoute(m4.toUpperCase(), this.#path, handler);
              });
            }
          }
          return this;
        };
        this.use = (arg1, ...handlers) => {
          if (typeof arg1 === "string") {
            this.#path = arg1;
          } else {
            this.#path = "*";
            handlers.unshift(arg1);
          }
          handlers.forEach((handler) => {
            this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
          });
          return this;
        };
        const { strict, ...optionsWithoutStrict } = options;
        Object.assign(this, optionsWithoutStrict);
        this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
      }
      #clone() {
        const clone2 = new Hono({
          router: this.router,
          getPath: this.getPath
        });
        clone2.errorHandler = this.errorHandler;
        clone2.#notFoundHandler = this.#notFoundHandler;
        clone2.routes = this.routes;
        return clone2;
      }
      #notFoundHandler = notFoundHandler;
      errorHandler = errorHandler;
      route(path4, app) {
        const subApp = this.basePath(path4);
        app.routes.map((r4) => {
          let handler;
          if (app.errorHandler === errorHandler) {
            handler = r4.handler;
          } else {
            handler = async (c3, next) => (await compose([], app.errorHandler)(c3, () => r4.handler(c3, next))).res;
            handler[COMPOSED_HANDLER] = r4.handler;
          }
          subApp.#addRoute(r4.method, r4.path, handler);
        });
        return this;
      }
      basePath(path4) {
        const subApp = this.#clone();
        subApp._basePath = mergePath(this._basePath, path4);
        return subApp;
      }
      onError = (handler) => {
        this.errorHandler = handler;
        return this;
      };
      notFound = (handler) => {
        this.#notFoundHandler = handler;
        return this;
      };
      mount(path4, applicationHandler, options) {
        let replaceRequest;
        let optionHandler;
        if (options) {
          if (typeof options === "function") {
            optionHandler = options;
          } else {
            optionHandler = options.optionHandler;
            if (options.replaceRequest === false) {
              replaceRequest = (request) => request;
            } else {
              replaceRequest = options.replaceRequest;
            }
          }
        }
        const getOptions = optionHandler ? (c3) => {
          const options2 = optionHandler(c3);
          return Array.isArray(options2) ? options2 : [options2];
        } : (c3) => {
          let executionContext = void 0;
          try {
            executionContext = c3.executionCtx;
          } catch {
          }
          return [c3.env, executionContext];
        };
        replaceRequest ||= (() => {
          const mergedPath = mergePath(this._basePath, path4);
          const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
          return (request) => {
            const url = new URL(request.url);
            url.pathname = url.pathname.slice(pathPrefixLength) || "/";
            return new Request(url, request);
          };
        })();
        const handler = async (c3, next) => {
          const res = await applicationHandler(replaceRequest(c3.req.raw), ...getOptions(c3));
          if (res) {
            return res;
          }
          await next();
        };
        this.#addRoute(METHOD_NAME_ALL, mergePath(path4, "*"), handler);
        return this;
      }
      #addRoute(method, path4, handler) {
        method = method.toUpperCase();
        path4 = mergePath(this._basePath, path4);
        const r4 = { path: path4, method, handler };
        this.router.add(method, path4, [handler, r4]);
        this.routes.push(r4);
      }
      #handleError(err2, c3) {
        if (err2 instanceof Error) {
          return this.errorHandler(err2, c3);
        }
        throw err2;
      }
      #dispatch(request, executionCtx, env3, method) {
        if (method === "HEAD") {
          return (async () => new Response(null, await this.#dispatch(request, executionCtx, env3, "GET")))();
        }
        const path4 = this.getPath(request, { env: env3 });
        const matchResult = this.router.match(method, path4);
        const c3 = new Context(request, {
          path: path4,
          matchResult,
          env: env3,
          executionCtx,
          notFoundHandler: this.#notFoundHandler
        });
        if (matchResult[0].length === 1) {
          let res;
          try {
            res = matchResult[0][0][0][0](c3, async () => {
              c3.res = await this.#notFoundHandler(c3);
            });
          } catch (err2) {
            return this.#handleError(err2, c3);
          }
          return res instanceof Promise ? res.then(
            (resolved) => resolved || (c3.finalized ? c3.res : this.#notFoundHandler(c3))
          ).catch((err2) => this.#handleError(err2, c3)) : res ?? this.#notFoundHandler(c3);
        }
        const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
        return (async () => {
          try {
            const context = await composed(c3);
            if (!context.finalized) {
              throw new Error(
                "Context is not finalized. Did you forget to return a Response object or `await next()`?"
              );
            }
            return context.res;
          } catch (err2) {
            return this.#handleError(err2, c3);
          }
        })();
      }
      fetch = (request, ...rest) => {
        return this.#dispatch(request, rest[1], rest[0], request.method);
      };
      request = (input, requestInit, Env, executionCtx) => {
        if (input instanceof Request) {
          return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
        }
        input = input.toString();
        return this.fetch(
          new Request(
            /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
            requestInit
          ),
          Env,
          executionCtx
        );
      };
      fire = () => {
        addEventListener("fetch", (event) => {
          event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
        });
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js
function compareKey(a3, b3) {
  if (a3.length === 1) {
    return b3.length === 1 ? a3 < b3 ? -1 : 1 : -1;
  }
  if (b3.length === 1) {
    return 1;
  }
  if (a3 === ONLY_WILDCARD_REG_EXP_STR || a3 === TAIL_WILDCARD_REG_EXP_STR) {
    return 1;
  } else if (b3 === ONLY_WILDCARD_REG_EXP_STR || b3 === TAIL_WILDCARD_REG_EXP_STR) {
    return -1;
  }
  if (a3 === LABEL_REG_EXP_STR) {
    return 1;
  } else if (b3 === LABEL_REG_EXP_STR) {
    return -1;
  }
  return a3.length === b3.length ? a3 < b3 ? -1 : 1 : b3.length - a3.length;
}
var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, Node;
var init_node = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js"() {
    LABEL_REG_EXP_STR = "[^/]+";
    ONLY_WILDCARD_REG_EXP_STR = ".*";
    TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
    PATH_ERROR = Symbol();
    regExpMetaChars = new Set(".\\+*[^]$()");
    Node = class {
      #index;
      #varIndex;
      #children = /* @__PURE__ */ Object.create(null);
      insert(tokens, index6, paramMap, context, pathErrorCheckOnly) {
        if (tokens.length === 0) {
          if (this.#index !== void 0) {
            throw PATH_ERROR;
          }
          if (pathErrorCheckOnly) {
            return;
          }
          this.#index = index6;
          return;
        }
        const [token, ...restTokens] = tokens;
        const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
        let node;
        if (pattern) {
          const name = pattern[1];
          let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
          if (name && pattern[2]) {
            regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
            if (/\((?!\?:)/.test(regexpStr)) {
              throw PATH_ERROR;
            }
          }
          node = this.#children[regexpStr];
          if (!node) {
            if (Object.keys(this.#children).some(
              (k3) => k3 !== ONLY_WILDCARD_REG_EXP_STR && k3 !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = this.#children[regexpStr] = new Node();
            if (name !== "") {
              node.#varIndex = context.varIndex++;
            }
          }
          if (!pathErrorCheckOnly && name !== "") {
            paramMap.push([name, node.#varIndex]);
          }
        } else {
          node = this.#children[token];
          if (!node) {
            if (Object.keys(this.#children).some(
              (k3) => k3.length > 1 && k3 !== ONLY_WILDCARD_REG_EXP_STR && k3 !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = this.#children[token] = new Node();
          }
        }
        node.insert(restTokens, index6, paramMap, context, pathErrorCheckOnly);
      }
      buildRegExpStr() {
        const childKeys = Object.keys(this.#children).sort(compareKey);
        const strList = childKeys.map((k3) => {
          const c3 = this.#children[k3];
          return (typeof c3.#varIndex === "number" ? `(${k3})@${c3.#varIndex}` : regExpMetaChars.has(k3) ? `\\${k3}` : k3) + c3.buildRegExpStr();
        });
        if (typeof this.#index === "number") {
          strList.unshift(`#${this.#index}`);
        }
        if (strList.length === 0) {
          return "";
        }
        if (strList.length === 1) {
          return strList[0];
        }
        return "(?:" + strList.join("|") + ")";
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js
var Trie;
var init_trie = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js"() {
    init_node();
    Trie = class {
      #context = { varIndex: 0 };
      #root = new Node();
      insert(path4, index6, pathErrorCheckOnly) {
        const paramAssoc = [];
        const groups = [];
        for (let i4 = 0; ; ) {
          let replaced = false;
          path4 = path4.replace(/\{[^}]+\}/g, (m4) => {
            const mark = `@\\${i4}`;
            groups[i4] = [mark, m4];
            i4++;
            replaced = true;
            return mark;
          });
          if (!replaced) {
            break;
          }
        }
        const tokens = path4.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
        for (let i4 = groups.length - 1; i4 >= 0; i4--) {
          const [mark] = groups[i4];
          for (let j3 = tokens.length - 1; j3 >= 0; j3--) {
            if (tokens[j3].indexOf(mark) !== -1) {
              tokens[j3] = tokens[j3].replace(mark, groups[i4][1]);
              break;
            }
          }
        }
        this.#root.insert(tokens, index6, paramAssoc, this.#context, pathErrorCheckOnly);
        return paramAssoc;
      }
      buildRegExp() {
        let regexp = this.#root.buildRegExpStr();
        if (regexp === "") {
          return [/^$/, [], []];
        }
        let captureIndex = 0;
        const indexReplacementMap = [];
        const paramReplacementMap = [];
        regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_3, handlerIndex, paramIndex) => {
          if (handlerIndex !== void 0) {
            indexReplacementMap[++captureIndex] = Number(handlerIndex);
            return "$()";
          }
          if (paramIndex !== void 0) {
            paramReplacementMap[Number(paramIndex)] = ++captureIndex;
            return "";
          }
          return "";
        });
        return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js
function buildWildcardRegExp(path4) {
  return wildcardRegExpCache[path4] ??= new RegExp(
    path4 === "*" ? "" : `^${path4.replace(
      /\/\*$|([.\\+*[^\]$()])/g,
      (_3, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
    )}$`
  );
}
function clearWildcardRegExpCache() {
  wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
function buildMatcherFromPreprocessedRoutes(routes) {
  var _a2;
  const trie = new Trie();
  const handlerData = [];
  if (routes.length === 0) {
    return nullMatcher;
  }
  const routesWithStaticPathFlag = routes.map(
    (route) => [!/\*|\/:/.test(route[0]), ...route]
  ).sort(
    ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
  );
  const staticMap = /* @__PURE__ */ Object.create(null);
  for (let i4 = 0, j3 = -1, len = routesWithStaticPathFlag.length; i4 < len; i4++) {
    const [pathErrorCheckOnly, path4, handlers] = routesWithStaticPathFlag[i4];
    if (pathErrorCheckOnly) {
      staticMap[path4] = [handlers.map(([h4]) => [h4, /* @__PURE__ */ Object.create(null)]), emptyParam];
    } else {
      j3++;
    }
    let paramAssoc;
    try {
      paramAssoc = trie.insert(path4, j3, pathErrorCheckOnly);
    } catch (e4) {
      throw e4 === PATH_ERROR ? new UnsupportedPathError(path4) : e4;
    }
    if (pathErrorCheckOnly) {
      continue;
    }
    handlerData[j3] = handlers.map(([h4, paramCount]) => {
      const paramIndexMap = /* @__PURE__ */ Object.create(null);
      paramCount -= 1;
      for (; paramCount >= 0; paramCount--) {
        const [key, value] = paramAssoc[paramCount];
        paramIndexMap[key] = value;
      }
      return [h4, paramIndexMap];
    });
  }
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  for (let i4 = 0, len = handlerData.length; i4 < len; i4++) {
    for (let j3 = 0, len2 = handlerData[i4].length; j3 < len2; j3++) {
      const map2 = (_a2 = handlerData[i4][j3]) == null ? void 0 : _a2[1];
      if (!map2) {
        continue;
      }
      const keys = Object.keys(map2);
      for (let k3 = 0, len3 = keys.length; k3 < len3; k3++) {
        map2[keys[k3]] = paramReplacementMap[map2[keys[k3]]];
      }
    }
  }
  const handlerMap = [];
  for (const i4 in indexReplacementMap) {
    handlerMap[i4] = handlerData[indexReplacementMap[i4]];
  }
  return [regexp, handlerMap, staticMap];
}
function findMiddleware(middleware, path4) {
  if (!middleware) {
    return void 0;
  }
  for (const k3 of Object.keys(middleware).sort((a3, b3) => b3.length - a3.length)) {
    if (buildWildcardRegExp(k3).test(path4)) {
      return [...middleware[k3]];
    }
  }
  return void 0;
}
var emptyParam, nullMatcher, wildcardRegExpCache, RegExpRouter;
var init_router2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js"() {
    init_router();
    init_url();
    init_node();
    init_trie();
    emptyParam = [];
    nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
    wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
    RegExpRouter = class {
      name = "RegExpRouter";
      #middleware;
      #routes;
      constructor() {
        this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
        this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
      }
      add(method, path4, handler) {
        const middleware = this.#middleware;
        const routes = this.#routes;
        if (!middleware || !routes) {
          throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
        }
        if (!middleware[method]) {
          ;
          [middleware, routes].forEach((handlerMap) => {
            handlerMap[method] = /* @__PURE__ */ Object.create(null);
            Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p3) => {
              handlerMap[method][p3] = [...handlerMap[METHOD_NAME_ALL][p3]];
            });
          });
        }
        if (path4 === "/*") {
          path4 = "*";
        }
        const paramCount = (path4.match(/\/:/g) || []).length;
        if (/\*$/.test(path4)) {
          const re = buildWildcardRegExp(path4);
          if (method === METHOD_NAME_ALL) {
            Object.keys(middleware).forEach((m4) => {
              middleware[m4][path4] ||= findMiddleware(middleware[m4], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
            });
          } else {
            middleware[method][path4] ||= findMiddleware(middleware[method], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
          }
          Object.keys(middleware).forEach((m4) => {
            if (method === METHOD_NAME_ALL || method === m4) {
              Object.keys(middleware[m4]).forEach((p3) => {
                re.test(p3) && middleware[m4][p3].push([handler, paramCount]);
              });
            }
          });
          Object.keys(routes).forEach((m4) => {
            if (method === METHOD_NAME_ALL || method === m4) {
              Object.keys(routes[m4]).forEach(
                (p3) => re.test(p3) && routes[m4][p3].push([handler, paramCount])
              );
            }
          });
          return;
        }
        const paths = checkOptionalParameter(path4) || [path4];
        for (let i4 = 0, len = paths.length; i4 < len; i4++) {
          const path22 = paths[i4];
          Object.keys(routes).forEach((m4) => {
            if (method === METHOD_NAME_ALL || method === m4) {
              routes[m4][path22] ||= [
                ...findMiddleware(middleware[m4], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
              ];
              routes[m4][path22].push([handler, paramCount - len + i4 + 1]);
            }
          });
        }
      }
      match(method, path4) {
        clearWildcardRegExpCache();
        const matchers = this.#buildAllMatchers();
        this.match = (method2, path22) => {
          const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
          const staticMatch = matcher[2][path22];
          if (staticMatch) {
            return staticMatch;
          }
          const match2 = path22.match(matcher[0]);
          if (!match2) {
            return [[], emptyParam];
          }
          const index6 = match2.indexOf("", 1);
          return [matcher[1][index6], match2];
        };
        return this.match(method, path4);
      }
      #buildAllMatchers() {
        const matchers = /* @__PURE__ */ Object.create(null);
        Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
          matchers[method] ||= this.#buildMatcher(method);
        });
        this.#middleware = this.#routes = void 0;
        return matchers;
      }
      #buildMatcher(method) {
        const routes = [];
        let hasOwnRoute = method === METHOD_NAME_ALL;
        [this.#middleware, this.#routes].forEach((r4) => {
          const ownRoute = r4[method] ? Object.keys(r4[method]).map((path4) => [path4, r4[method][path4]]) : [];
          if (ownRoute.length !== 0) {
            hasOwnRoute ||= true;
            routes.push(...ownRoute);
          } else if (method !== METHOD_NAME_ALL) {
            routes.push(
              ...Object.keys(r4[METHOD_NAME_ALL]).map((path4) => [path4, r4[METHOD_NAME_ALL][path4]])
            );
          }
        });
        if (!hasOwnRoute) {
          return null;
        } else {
          return buildMatcherFromPreprocessedRoutes(routes);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js
var init_reg_exp_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js"() {
    init_router2();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js
var SmartRouter;
var init_router3 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js"() {
    init_router();
    SmartRouter = class {
      name = "SmartRouter";
      #routers = [];
      #routes = [];
      constructor(init2) {
        this.#routers = init2.routers;
      }
      add(method, path4, handler) {
        if (!this.#routes) {
          throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
        }
        this.#routes.push([method, path4, handler]);
      }
      match(method, path4) {
        if (!this.#routes) {
          throw new Error("Fatal error");
        }
        const routers = this.#routers;
        const routes = this.#routes;
        const len = routers.length;
        let i4 = 0;
        let res;
        for (; i4 < len; i4++) {
          const router = routers[i4];
          try {
            for (let i22 = 0, len2 = routes.length; i22 < len2; i22++) {
              router.add(...routes[i22]);
            }
            res = router.match(method, path4);
          } catch (e4) {
            if (e4 instanceof UnsupportedPathError) {
              continue;
            }
            throw e4;
          }
          this.match = router.match.bind(router);
          this.#routers = [router];
          this.#routes = void 0;
          break;
        }
        if (i4 === len) {
          throw new Error("Fatal error");
        }
        this.name = `SmartRouter + ${this.activeRouter.name}`;
        return res;
      }
      get activeRouter() {
        if (this.#routes || this.#routers.length !== 1) {
          throw new Error("No active router has been determined yet.");
        }
        return this.#routers[0];
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js
var init_smart_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js"() {
    init_router3();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js
var emptyParams, Node2;
var init_node2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js"() {
    init_router();
    init_url();
    emptyParams = /* @__PURE__ */ Object.create(null);
    Node2 = class {
      #methods;
      #children;
      #patterns;
      #order = 0;
      #params = emptyParams;
      constructor(method, handler, children) {
        this.#children = children || /* @__PURE__ */ Object.create(null);
        this.#methods = [];
        if (method && handler) {
          const m4 = /* @__PURE__ */ Object.create(null);
          m4[method] = { handler, possibleKeys: [], score: 0 };
          this.#methods = [m4];
        }
        this.#patterns = [];
      }
      insert(method, path4, handler) {
        this.#order = ++this.#order;
        let curNode = this;
        const parts = splitRoutingPath(path4);
        const possibleKeys = [];
        for (let i4 = 0, len = parts.length; i4 < len; i4++) {
          const p3 = parts[i4];
          const nextP = parts[i4 + 1];
          const pattern = getPattern(p3, nextP);
          const key = Array.isArray(pattern) ? pattern[0] : p3;
          if (Object.keys(curNode.#children).includes(key)) {
            curNode = curNode.#children[key];
            const pattern2 = getPattern(p3, nextP);
            if (pattern2) {
              possibleKeys.push(pattern2[1]);
            }
            continue;
          }
          curNode.#children[key] = new Node2();
          if (pattern) {
            curNode.#patterns.push(pattern);
            possibleKeys.push(pattern[1]);
          }
          curNode = curNode.#children[key];
        }
        const m4 = /* @__PURE__ */ Object.create(null);
        const handlerSet = {
          handler,
          possibleKeys: possibleKeys.filter((v6, i4, a3) => a3.indexOf(v6) === i4),
          score: this.#order
        };
        m4[method] = handlerSet;
        curNode.#methods.push(m4);
        return curNode;
      }
      #getHandlerSets(node, method, nodeParams, params) {
        const handlerSets = [];
        for (let i4 = 0, len = node.#methods.length; i4 < len; i4++) {
          const m4 = node.#methods[i4];
          const handlerSet = m4[method] || m4[METHOD_NAME_ALL];
          const processedSet = {};
          if (handlerSet !== void 0) {
            handlerSet.params = /* @__PURE__ */ Object.create(null);
            handlerSets.push(handlerSet);
            if (nodeParams !== emptyParams || params && params !== emptyParams) {
              for (let i22 = 0, len2 = handlerSet.possibleKeys.length; i22 < len2; i22++) {
                const key = handlerSet.possibleKeys[i22];
                const processed = processedSet[handlerSet.score];
                handlerSet.params[key] = (params == null ? void 0 : params[key]) && !processed ? params[key] : nodeParams[key] ?? (params == null ? void 0 : params[key]);
                processedSet[handlerSet.score] = true;
              }
            }
          }
        }
        return handlerSets;
      }
      search(method, path4) {
        var _a2;
        const handlerSets = [];
        this.#params = emptyParams;
        const curNode = this;
        let curNodes = [curNode];
        const parts = splitPath(path4);
        const curNodesQueue = [];
        for (let i4 = 0, len = parts.length; i4 < len; i4++) {
          const part = parts[i4];
          const isLast = i4 === len - 1;
          const tempNodes = [];
          for (let j3 = 0, len2 = curNodes.length; j3 < len2; j3++) {
            const node = curNodes[j3];
            const nextNode = node.#children[part];
            if (nextNode) {
              nextNode.#params = node.#params;
              if (isLast) {
                if (nextNode.#children["*"]) {
                  handlerSets.push(
                    ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
                  );
                }
                handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
              } else {
                tempNodes.push(nextNode);
              }
            }
            for (let k3 = 0, len3 = node.#patterns.length; k3 < len3; k3++) {
              const pattern = node.#patterns[k3];
              const params = node.#params === emptyParams ? {} : { ...node.#params };
              if (pattern === "*") {
                const astNode = node.#children["*"];
                if (astNode) {
                  handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
                  astNode.#params = params;
                  tempNodes.push(astNode);
                }
                continue;
              }
              if (part === "") {
                continue;
              }
              const [key, name, matcher] = pattern;
              const child = node.#children[key];
              const restPathString = parts.slice(i4).join("/");
              if (matcher instanceof RegExp) {
                const m4 = matcher.exec(restPathString);
                if (m4) {
                  params[name] = m4[0];
                  handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
                  if (Object.keys(child.#children).length) {
                    child.#params = params;
                    const componentCount = ((_a2 = m4[0].match(/\//)) == null ? void 0 : _a2.length) ?? 0;
                    const targetCurNodes = curNodesQueue[componentCount] ||= [];
                    targetCurNodes.push(child);
                  }
                  continue;
                }
              }
              if (matcher === true || matcher.test(part)) {
                params[name] = part;
                if (isLast) {
                  handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
                  if (child.#children["*"]) {
                    handlerSets.push(
                      ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
                    );
                  }
                } else {
                  child.#params = params;
                  tempNodes.push(child);
                }
              }
            }
          }
          curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
        }
        if (handlerSets.length > 1) {
          handlerSets.sort((a3, b3) => {
            return a3.score - b3.score;
          });
        }
        return [handlerSets.map(({ handler, params }) => [handler, params])];
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js
var TrieRouter;
var init_router4 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js"() {
    init_url();
    init_node2();
    TrieRouter = class {
      name = "TrieRouter";
      #node;
      constructor() {
        this.#node = new Node2();
      }
      add(method, path4, handler) {
        const results = checkOptionalParameter(path4);
        if (results) {
          for (let i4 = 0, len = results.length; i4 < len; i4++) {
            this.#node.insert(method, results[i4], handler);
          }
          return;
        }
        this.#node.insert(method, path4, handler);
      }
      match(method, path4) {
        return this.#node.search(method, path4);
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js
var init_trie_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js"() {
    init_router4();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js
var Hono2;
var init_hono = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js"() {
    init_hono_base();
    init_reg_exp_router();
    init_smart_router();
    init_trie_router();
    Hono2 = class extends Hono {
      constructor(options = {}) {
        super(options);
        this.router = options.router ?? new SmartRouter({
          routers: [new RegExpRouter(), new TrieRouter()]
        });
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js
var init_dist3 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js"() {
    init_hono();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js
var COMPRESSIBLE_CONTENT_TYPE_REGEX;
var init_compress = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js"() {
    COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js
var ENCODING_TYPES, cacheControlNoTransformRegExp, compress, shouldCompress, shouldTransform;
var init_compress2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js"() {
    init_compress();
    ENCODING_TYPES = ["gzip", "deflate"];
    cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
    compress = (options) => {
      const threshold = (options == null ? void 0 : options.threshold) ?? 1024;
      return async function compress2(ctx, next) {
        await next();
        const contentLength = ctx.res.headers.get("Content-Length");
        if (ctx.res.headers.has("Content-Encoding") || ctx.res.headers.has("Transfer-Encoding") || ctx.req.method === "HEAD" || contentLength && Number(contentLength) < threshold || !shouldCompress(ctx.res) || !shouldTransform(ctx.res)) {
          return;
        }
        const accepted = ctx.req.header("Accept-Encoding");
        const encoding = (options == null ? void 0 : options.encoding) ?? ENCODING_TYPES.find((encoding2) => accepted == null ? void 0 : accepted.includes(encoding2));
        if (!encoding || !ctx.res.body) {
          return;
        }
        const stream = new CompressionStream(encoding);
        ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
        ctx.res.headers.delete("Content-Length");
        ctx.res.headers.set("Content-Encoding", encoding);
      };
    };
    shouldCompress = (res) => {
      const type = res.headers.get("Content-Type");
      return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
    };
    shouldTransform = (res) => {
      const cacheControl = res.headers.get("Cache-Control");
      return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js
var cors;
var init_cors = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js"() {
    cors = (options) => {
      const defaults2 = {
        origin: "*",
        allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
        allowHeaders: [],
        exposeHeaders: []
      };
      const opts = {
        ...defaults2,
        ...options
      };
      const findAllowOrigin = ((optsOrigin) => {
        if (typeof optsOrigin === "string") {
          if (optsOrigin === "*") {
            return () => optsOrigin;
          } else {
            return (origin) => optsOrigin === origin ? origin : null;
          }
        } else if (typeof optsOrigin === "function") {
          return optsOrigin;
        } else {
          return (origin) => optsOrigin.includes(origin) ? origin : null;
        }
      })(opts.origin);
      return async function cors2(c3, next) {
        var _a2, _b;
        function set(key, value) {
          c3.res.headers.set(key, value);
        }
        const allowOrigin = findAllowOrigin(c3.req.header("origin") || "", c3);
        if (allowOrigin) {
          set("Access-Control-Allow-Origin", allowOrigin);
        }
        if (opts.origin !== "*") {
          const existingVary = c3.req.header("Vary");
          if (existingVary) {
            set("Vary", existingVary);
          } else {
            set("Vary", "Origin");
          }
        }
        if (opts.credentials) {
          set("Access-Control-Allow-Credentials", "true");
        }
        if ((_a2 = opts.exposeHeaders) == null ? void 0 : _a2.length) {
          set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
        }
        if (c3.req.method === "OPTIONS") {
          if (opts.maxAge != null) {
            set("Access-Control-Max-Age", opts.maxAge.toString());
          }
          if ((_b = opts.allowMethods) == null ? void 0 : _b.length) {
            set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
          }
          let headers = opts.allowHeaders;
          if (!(headers == null ? void 0 : headers.length)) {
            const requestHeaders = c3.req.header("Access-Control-Request-Headers");
            if (requestHeaders) {
              headers = requestHeaders.split(/\s*,\s*/);
            }
          }
          if (headers == null ? void 0 : headers.length) {
            set("Access-Control-Allow-Headers", headers.join(","));
            c3.res.headers.append("Vary", "Access-Control-Request-Headers");
          }
          c3.res.headers.delete("Content-Length");
          c3.res.headers.delete("Content-Type");
          return new Response(null, {
            headers: c3.res.headers,
            status: 204,
            statusText: "No Content"
          });
        }
        await next();
      };
    };
  }
});

// src/serializer/studio.ts
var studio_exports = {};
__export(studio_exports, {
  drizzleForLibSQL: () => drizzleForLibSQL,
  drizzleForMySQL: () => drizzleForMySQL,
  drizzleForPostgres: () => drizzleForPostgres,
  drizzleForSQLite: () => drizzleForSQLite,
  drizzleForSingleStore: () => drizzleForSingleStore,
  extractRelations: () => extractRelations,
  prepareMySqlSchema: () => prepareMySqlSchema,
  preparePgSchema: () => preparePgSchema,
  prepareSQLiteSchema: () => prepareSQLiteSchema,
  prepareServer: () => prepareServer,
  prepareSingleStoreSchema: () => prepareSingleStoreSchema
});
var import_crypto9, import_drizzle_orm11, import_drizzle_orm12, import_mysql_core3, import_pg_core3, import_singlestore_core3, import_sqlite_core3, import_fs12, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, prepareSingleStoreSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, drizzleForSingleStore, extractRelations, init, proxySchema, transactionProxySchema, defaultsSchema, schema5, jsonStringify, prepareServer;
var init_studio2 = __esm({
  "src/serializer/studio.ts"() {
    "use strict";
    init_dist2();
    init_esm2();
    import_crypto9 = require("crypto");
    import_drizzle_orm11 = require("drizzle-orm");
    import_drizzle_orm12 = require("drizzle-orm");
    import_mysql_core3 = require("drizzle-orm/mysql-core");
    import_pg_core3 = require("drizzle-orm/pg-core");
    import_singlestore_core3 = require("drizzle-orm/singlestore-core");
    import_sqlite_core3 = require("drizzle-orm/sqlite-core");
    import_fs12 = __toESM(require("fs"));
    init_dist3();
    init_compress2();
    init_cors();
    import_node_https2 = require("node:https");
    init_global();
    init_esm();
    init_utils3();
    init_serializer();
    preparePgSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const pgSchema2 = {};
      const relations5 = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k3, t4]) => {
          if ((0, import_drizzle_orm11.is)(t4, import_pg_core3.PgTable)) {
            const schema6 = (0, import_pg_core3.getTableConfig)(t4).schema || "public";
            pgSchema2[schema6] = pgSchema2[schema6] || {};
            pgSchema2[schema6][k3] = t4;
          }
          if ((0, import_drizzle_orm11.is)(t4, import_drizzle_orm12.Relations)) {
            relations5[k3] = t4;
          }
        });
      }
      unregister();
      return { schema: pgSchema2, relations: relations5, files };
    };
    prepareMySqlSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const mysqlSchema3 = {
        public: {}
      };
      const relations5 = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k3, t4]) => {
          if ((0, import_drizzle_orm11.is)(t4, import_mysql_core3.MySqlTable)) {
            const schema6 = (0, import_mysql_core3.getTableConfig)(t4).schema || "public";
            mysqlSchema3[schema6][k3] = t4;
          }
          if ((0, import_drizzle_orm11.is)(t4, import_drizzle_orm12.Relations)) {
            relations5[k3] = t4;
          }
        });
      }
      unregister();
      return { schema: mysqlSchema3, relations: relations5, files };
    };
    prepareSQLiteSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const sqliteSchema2 = {
        public: {}
      };
      const relations5 = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k3, t4]) => {
          if ((0, import_drizzle_orm11.is)(t4, import_sqlite_core3.SQLiteTable)) {
            const schema6 = "public";
            sqliteSchema2[schema6][k3] = t4;
          }
          if ((0, import_drizzle_orm11.is)(t4, import_drizzle_orm12.Relations)) {
            relations5[k3] = t4;
          }
        });
      }
      unregister();
      return { schema: sqliteSchema2, relations: relations5, files };
    };
    prepareSingleStoreSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const singlestoreSchema2 = {
        public: {}
      };
      const relations5 = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i4 = 0; i4 < imports.length; i4++) {
        const it = imports[i4];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k3, t4]) => {
          if ((0, import_drizzle_orm11.is)(t4, import_singlestore_core3.SingleStoreTable)) {
            const schema6 = (0, import_singlestore_core3.getTableConfig)(t4).schema || "public";
            singlestoreSchema2[schema6][k3] = t4;
          }
          if ((0, import_drizzle_orm11.is)(t4, import_drizzle_orm12.Relations)) {
            relations5[k3] = t4;
          }
        });
      }
      unregister();
      return { schema: singlestoreSchema2, relations: relations5, files };
    };
    getCustomDefaults = (schema6) => {
      const customDefaults = [];
      Object.entries(schema6).map(([schema7, tables]) => {
        Object.entries(tables).map(([, table6]) => {
          let tableConfig;
          if ((0, import_drizzle_orm11.is)(table6, import_pg_core3.PgTable)) {
            tableConfig = (0, import_pg_core3.getTableConfig)(table6);
          } else if ((0, import_drizzle_orm11.is)(table6, import_mysql_core3.MySqlTable)) {
            tableConfig = (0, import_mysql_core3.getTableConfig)(table6);
          } else if ((0, import_drizzle_orm11.is)(table6, import_sqlite_core3.SQLiteTable)) {
            tableConfig = (0, import_sqlite_core3.getTableConfig)(table6);
          } else {
            tableConfig = (0, import_singlestore_core3.getTableConfig)(table6);
          }
          tableConfig.columns.map((column11) => {
            if (column11.defaultFn) {
              customDefaults.push({
                schema: schema7,
                table: tableConfig.name,
                column: column11.name,
                func: column11.defaultFn
              });
            }
          });
        });
      });
      return customDefaults;
    };
    drizzleForPostgres = async (credentials2, pgSchema2, relations5, schemaFiles) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await preparePostgresDB2(credentials2);
      const customDefaults = getCustomDefaults(pgSchema2);
      let dbUrl;
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "aws-data-api") {
          dbUrl = `aws-data-api://${credentials2.database}/${credentials2.secretArn}/${credentials2.resourceArn}`;
        } else if (driver2 === "pglite") {
          dbUrl = credentials2.url;
        } else {
          assertUnreachable(driver2);
        }
      } else if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `postgresql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "postgresql",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        packageName: db.packageName,
        proxy: db.proxy,
        transactionProxy: db.transactionProxy,
        customDefaults,
        schema: pgSchema2,
        relations: relations5,
        schemaFiles
      };
    };
    drizzleForMySQL = async (credentials2, mysqlSchema3, relations5, schemaFiles) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy, transactionProxy, database, packageName } = await connectToMySQL2(credentials2);
      const customDefaults = getCustomDefaults(mysqlSchema3);
      let dbUrl;
      if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `mysql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "mysql",
        packageName,
        databaseName: database,
        proxy,
        transactionProxy,
        customDefaults,
        schema: mysqlSchema3,
        relations: relations5,
        schemaFiles
      };
    };
    drizzleForSQLite = async (credentials2, sqliteSchema2, relations5, schemaFiles) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToSQLite2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2);
      let dbUrl;
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "d1-http") {
          dbUrl = `d1-http://${credentials2.accountId}/${credentials2.databaseId}/${credentials2.token}`;
        } else {
          assertUnreachable(driver2);
        }
      } else {
        dbUrl = credentials2.url;
      }
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        packageName: sqliteDB.packageName,
        proxy: sqliteDB.proxy,
        transactionProxy: sqliteDB.transactionProxy,
        customDefaults,
        schema: sqliteSchema2,
        relations: relations5,
        schemaFiles
      };
    };
    drizzleForLibSQL = async (credentials2, sqliteSchema2, relations5, schemaFiles) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToLibSQL2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2);
      let dbUrl = `turso://${credentials2.url}/${credentials2.authToken}`;
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: void 0,
        packageName: sqliteDB.packageName,
        proxy: sqliteDB.proxy,
        transactionProxy: sqliteDB.transactionProxy,
        customDefaults,
        schema: sqliteSchema2,
        relations: relations5,
        schemaFiles
      };
    };
    drizzleForSingleStore = async (credentials2, singlestoreSchema2, relations5, schemaFiles) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy, transactionProxy, database, packageName } = await connectToSingleStore2(credentials2);
      const customDefaults = getCustomDefaults(singlestoreSchema2);
      let dbUrl;
      if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `singlestore://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "singlestore",
        databaseName: database,
        packageName,
        proxy,
        transactionProxy,
        customDefaults,
        schema: singlestoreSchema2,
        relations: relations5,
        schemaFiles
      };
    };
    extractRelations = (tablesConfig) => {
      const relations5 = Object.values(tablesConfig.tables).map(
        (it) => Object.entries(it.relations).map(([name, relation]) => {
          try {
            const normalized = (0, import_drizzle_orm12.normalizeRelation)(
              tablesConfig.tables,
              tablesConfig.tableNamesMap,
              relation
            );
            const rel = relation;
            const refTableName = rel.referencedTableName;
            const refTable = rel.referencedTable;
            const fields = normalized.fields.map((it2) => it2.name).flat();
            const refColumns = normalized.references.map((it2) => it2.name).flat();
            let refSchema;
            if ((0, import_drizzle_orm11.is)(refTable, import_pg_core3.PgTable)) {
              refSchema = (0, import_pg_core3.getTableConfig)(refTable).schema;
            } else if ((0, import_drizzle_orm11.is)(refTable, import_mysql_core3.MySqlTable)) {
              refSchema = (0, import_mysql_core3.getTableConfig)(refTable).schema;
            } else if ((0, import_drizzle_orm11.is)(refTable, import_sqlite_core3.SQLiteTable)) {
              refSchema = void 0;
            } else if ((0, import_drizzle_orm11.is)(refTable, import_singlestore_core3.SingleStoreTable)) {
              refSchema = (0, import_singlestore_core3.getTableConfig)(refTable).schema;
            } else {
              throw new Error("unsupported dialect");
            }
            let type;
            if ((0, import_drizzle_orm11.is)(rel, import_drizzle_orm12.One)) {
              type = "one";
            } else if ((0, import_drizzle_orm11.is)(rel, import_drizzle_orm12.Many)) {
              type = "many";
            } else {
              throw new Error("unsupported relation type");
            }
            return {
              name,
              type,
              table: it.dbName,
              schema: it.schema || "public",
              columns: fields,
              refTable: refTableName,
              refSchema: refSchema || "public",
              refColumns
            };
          } catch (error2) {
            throw new Error(
              `Invalid relation "${relation.fieldName}" for table "${it.schema ? `${it.schema}.${it.dbName}` : it.dbName}"`
            );
          }
        })
      ).flat();
      return relations5;
    };
    init = external_exports.object({
      type: external_exports.literal("init")
    });
    proxySchema = external_exports.object({
      type: external_exports.literal("proxy"),
      data: external_exports.object({
        sql: external_exports.string(),
        params: external_exports.array(external_exports.any()).optional(),
        typings: external_exports.string().array().optional(),
        mode: external_exports.enum(["array", "object"]).default("object"),
        method: external_exports.union([external_exports.literal("values"), external_exports.literal("get"), external_exports.literal("all"), external_exports.literal("run"), external_exports.literal("execute")])
      })
    });
    transactionProxySchema = external_exports.object({
      type: external_exports.literal("tproxy"),
      data: external_exports.object({
        sql: external_exports.string(),
        method: external_exports.union([external_exports.literal("values"), external_exports.literal("get"), external_exports.literal("all"), external_exports.literal("run"), external_exports.literal("execute")]).optional()
      }).array()
    });
    defaultsSchema = external_exports.object({
      type: external_exports.literal("defaults"),
      data: external_exports.array(
        external_exports.object({
          schema: external_exports.string(),
          table: external_exports.string(),
          column: external_exports.string()
        })
      ).min(1)
    });
    schema5 = external_exports.union([init, proxySchema, transactionProxySchema, defaultsSchema]);
    jsonStringify = (data) => {
      return JSON.stringify(data, (_key, value) => {
        if (value instanceof Error) {
          return {
            error: value.message
          };
        }
        if (typeof value === "bigint") {
          return value.toString();
        }
        if (value && typeof value === "object" && "type" in value && "data" in value && value.type === "Buffer" || value instanceof ArrayBuffer || value instanceof Buffer) {
          return Buffer.from(value).toString("base64");
        }
        return value;
      });
    };
    prepareServer = async ({
      dialect: dialect6,
      driver: driver2,
      packageName,
      databaseName,
      proxy,
      transactionProxy,
      customDefaults,
      schema: drizzleSchema,
      relations: relations5,
      dbHash,
      schemaFiles
    }, app) => {
      app = app !== void 0 ? app : new Hono2();
      app.use(compress());
      app.use(async (ctx, next) => {
        await next();
        ctx.header("Access-Control-Allow-Private-Network", "true");
      });
      app.use(cors());
      app.onError((err2, ctx) => {
        console.error(err2);
        return ctx.json({
          status: "error",
          error: err2.message
        });
      });
      const relationalSchema = {
        ...Object.fromEntries(
          Object.entries(drizzleSchema).map(([schemaName, schema6]) => {
            const mappedTableEntries = Object.entries(schema6).map(([tableName, table6]) => {
              return [`__${schemaName}__.${tableName}`, table6];
            });
            return mappedTableEntries;
          }).flat()
        ),
        ...relations5
      };
      const relationsConfig = (0, import_drizzle_orm12.extractTablesRelationalConfig)(relationalSchema, import_drizzle_orm12.createTableRelationsHelpers);
      app.post("/", zValidator("json", schema5), async (c3) => {
        const body = c3.req.valid("json");
        const { type } = body;
        if (type === "init") {
          const preparedDefaults = customDefaults.map((d3) => ({
            schema: d3.schema,
            table: d3.table,
            column: d3.column
          }));
          let relations6 = [];
          try {
            relations6 = extractRelations(relationsConfig);
          } catch (error2) {
            console.warn("Failed to extract relations. This is likely due to ambiguous or misconfigured relations.");
            console.warn("Please check your schema and ensure that all relations are correctly defined.");
            console.warn("See: https://orm.drizzle.team/docs/relations#disambiguating-relations");
            console.warn("Error message:", error2.message);
          }
          return c3.json({
            version: "6.2",
            dialect: dialect6,
            driver: driver2,
            packageName,
            schemaFiles,
            customDefaults: preparedDefaults,
            relations: relations6,
            dbHash,
            databaseName
          });
        }
        if (type === "proxy") {
          const result = await proxy({
            ...body.data,
            params: body.data.params || []
          });
          return c3.json(JSON.parse(jsonStringify(result)));
        }
        if (type === "tproxy") {
          const result = await transactionProxy(body.data);
          return c3.json(JSON.parse(jsonStringify(result)));
        }
        if (type === "defaults") {
          const columns = body.data;
          const result = columns.map((column11) => {
            const found = customDefaults.find((d3) => {
              return d3.schema === column11.schema && d3.table === column11.table && d3.column === column11.column;
            });
            if (!found) {
              throw new Error(`Custom default not found for ${column11.schema}.${column11.table}.${column11.column}`);
            }
            const value = found.func();
            return {
              ...column11,
              value
            };
          });
          return c3.json(JSON.parse(jsonStringify(result)));
        }
        throw new Error(`Unknown type: ${type}`);
      });
      return {
        start: (params) => {
          serve(
            {
              fetch: app.fetch,
              createServer: params.key ? import_node_https2.createServer : void 0,
              hostname: params.host,
              port: params.port,
              serverOptions: {
                key: params.key,
                cert: params.cert
              }
            },
            () => params.cb(null, `${params.host}:${params.port}`)
          );
        }
      };
    };
  }
});

// ../node_modules/.pnpm/@drizzle-team+brocli@0.10.2/node_modules/@drizzle-team/brocli/index.js
var __create2 = Object.create;
var __defProp2 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getProtoOf2 = Object.getPrototypeOf;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps2 = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames2(from))
      if (!__hasOwnProp2.call(to, key) && key !== except)
        __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var require_clone = __commonJS2({
  "node_modules/.pnpm/clone@2.1.2/node_modules/clone/clone.js"(exports2, module2) {
    "use strict";
    var clone2 = function() {
      "use strict";
      function _instanceof(obj, type) {
        return type != null && obj instanceof type;
      }
      var nativeMap;
      try {
        nativeMap = Map;
      } catch (_3) {
        nativeMap = function() {
        };
      }
      var nativeSet;
      try {
        nativeSet = Set;
      } catch (_3) {
        nativeSet = function() {
        };
      }
      var nativePromise;
      try {
        nativePromise = Promise;
      } catch (_3) {
        nativePromise = function() {
        };
      }
      function clone3(parent, circular, depth, prototype, includeNonEnumerable) {
        if (typeof circular === "object") {
          depth = circular.depth;
          prototype = circular.prototype;
          includeNonEnumerable = circular.includeNonEnumerable;
          circular = circular.circular;
        }
        var allParents = [];
        var allChildren = [];
        var useBuffer = typeof Buffer != "undefined";
        if (typeof circular == "undefined")
          circular = true;
        if (typeof depth == "undefined")
          depth = Infinity;
        function _clone(parent2, depth2) {
          if (parent2 === null)
            return null;
          if (depth2 === 0)
            return parent2;
          var child;
          var proto2;
          if (typeof parent2 != "object") {
            return parent2;
          }
          if (_instanceof(parent2, nativeMap)) {
            child = new nativeMap();
          } else if (_instanceof(parent2, nativeSet)) {
            child = new nativeSet();
          } else if (_instanceof(parent2, nativePromise)) {
            child = new nativePromise(function(resolve2, reject) {
              parent2.then(function(value) {
                resolve2(_clone(value, depth2 - 1));
              }, function(err2) {
                reject(_clone(err2, depth2 - 1));
              });
            });
          } else if (clone3.__isArray(parent2)) {
            child = [];
          } else if (clone3.__isRegExp(parent2)) {
            child = new RegExp(parent2.source, __getRegExpFlags(parent2));
            if (parent2.lastIndex) child.lastIndex = parent2.lastIndex;
          } else if (clone3.__isDate(parent2)) {
            child = new Date(parent2.getTime());
          } else if (useBuffer && Buffer.isBuffer(parent2)) {
            if (Buffer.allocUnsafe) {
              child = Buffer.allocUnsafe(parent2.length);
            } else {
              child = new Buffer(parent2.length);
            }
            parent2.copy(child);
            return child;
          } else if (_instanceof(parent2, Error)) {
            child = Object.create(parent2);
          } else {
            if (typeof prototype == "undefined") {
              proto2 = Object.getPrototypeOf(parent2);
              child = Object.create(proto2);
            } else {
              child = Object.create(prototype);
              proto2 = prototype;
            }
          }
          if (circular) {
            var index6 = allParents.indexOf(parent2);
            if (index6 != -1) {
              return allChildren[index6];
            }
            allParents.push(parent2);
            allChildren.push(child);
          }
          if (_instanceof(parent2, nativeMap)) {
            parent2.forEach(function(value, key) {
              var keyChild = _clone(key, depth2 - 1);
              var valueChild = _clone(value, depth2 - 1);
              child.set(keyChild, valueChild);
            });
          }
          if (_instanceof(parent2, nativeSet)) {
            parent2.forEach(function(value) {
              var entryChild = _clone(value, depth2 - 1);
              child.add(entryChild);
            });
          }
          for (var i4 in parent2) {
            var attrs;
            if (proto2) {
              attrs = Object.getOwnPropertyDescriptor(proto2, i4);
            }
            if (attrs && attrs.set == null) {
              continue;
            }
            child[i4] = _clone(parent2[i4], depth2 - 1);
          }
          if (Object.getOwnPropertySymbols) {
            var symbols = Object.getOwnPropertySymbols(parent2);
            for (var i4 = 0; i4 < symbols.length; i4++) {
              var symbol = symbols[i4];
              var descriptor = Object.getOwnPropertyDescriptor(parent2, symbol);
              if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
                continue;
              }
              child[symbol] = _clone(parent2[symbol], depth2 - 1);
              if (!descriptor.enumerable) {
                Object.defineProperty(child, symbol, {
                  enumerable: false
                });
              }
            }
          }
          if (includeNonEnumerable) {
            var allPropertyNames = Object.getOwnPropertyNames(parent2);
            for (var i4 = 0; i4 < allPropertyNames.length; i4++) {
              var propertyName = allPropertyNames[i4];
              var descriptor = Object.getOwnPropertyDescriptor(parent2, propertyName);
              if (descriptor && descriptor.enumerable) {
                continue;
              }
              child[propertyName] = _clone(parent2[propertyName], depth2 - 1);
              Object.defineProperty(child, propertyName, {
                enumerable: false
              });
            }
          }
          return child;
        }
        return _clone(parent, depth);
      }
      clone3.clonePrototype = function clonePrototype(parent) {
        if (parent === null)
          return null;
        var c3 = function() {
        };
        c3.prototype = parent;
        return new c3();
      };
      function __objToStr(o3) {
        return Object.prototype.toString.call(o3);
      }
      clone3.__objToStr = __objToStr;
      function __isDate(o3) {
        return typeof o3 === "object" && __objToStr(o3) === "[object Date]";
      }
      clone3.__isDate = __isDate;
      function __isArray(o3) {
        return typeof o3 === "object" && __objToStr(o3) === "[object Array]";
      }
      clone3.__isArray = __isArray;
      function __isRegExp(o3) {
        return typeof o3 === "object" && __objToStr(o3) === "[object RegExp]";
      }
      clone3.__isRegExp = __isRegExp;
      function __getRegExpFlags(re) {
        var flags = "";
        if (re.global) flags += "g";
        if (re.ignoreCase) flags += "i";
        if (re.multiline) flags += "m";
        return flags;
      }
      clone3.__getRegExpFlags = __getRegExpFlags;
      return clone3;
    }();
    if (typeof module2 === "object" && module2.exports) {
      module2.exports = clone2;
    }
  }
});
var require_quote = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/quote.js"(exports2, module2) {
    "use strict";
    module2.exports = function quote(xs) {
      return xs.map(function(s4) {
        if (s4 && typeof s4 === "object") {
          return s4.op.replace(/(.)/g, "\\$1");
        }
        if (/["\s]/.test(s4) && !/'/.test(s4)) {
          return "'" + s4.replace(/(['\\])/g, "\\$1") + "'";
        }
        if (/["'\s]/.test(s4)) {
          return '"' + s4.replace(/(["\\$`!])/g, "\\$1") + '"';
        }
        return String(s4).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
      }).join(" ");
    };
  }
});
var require_parse = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/parse.js"(exports2, module2) {
    "use strict";
    var CONTROL = "(?:" + [
      "\\|\\|",
      "\\&\\&",
      ";;",
      "\\|\\&",
      "\\<\\(",
      "\\<\\<\\<",
      ">>",
      ">\\&",
      "<\\&",
      "[&;()|<>]"
    ].join("|") + ")";
    var controlRE = new RegExp("^" + CONTROL + "$");
    var META = "|&;()<> \\t";
    var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
    var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
    var hash = /^#$/;
    var SQ = "'";
    var DQ = '"';
    var DS = "$";
    var TOKEN = "";
    var mult = 4294967296;
    for (i4 = 0; i4 < 4; i4++) {
      TOKEN += (mult * Math.random()).toString(16);
    }
    var i4;
    var startsWithToken = new RegExp("^" + TOKEN);
    function matchAll(s4, r4) {
      var origIndex = r4.lastIndex;
      var matches = [];
      var matchObj;
      while (matchObj = r4.exec(s4)) {
        matches.push(matchObj);
        if (r4.lastIndex === matchObj.index) {
          r4.lastIndex += 1;
        }
      }
      r4.lastIndex = origIndex;
      return matches;
    }
    function getVar(env3, pre, key) {
      var r4 = typeof env3 === "function" ? env3(key) : env3[key];
      if (typeof r4 === "undefined" && key != "") {
        r4 = "";
      } else if (typeof r4 === "undefined") {
        r4 = "$";
      }
      if (typeof r4 === "object") {
        return pre + TOKEN + JSON.stringify(r4) + TOKEN;
      }
      return pre + r4;
    }
    function parseInternal(string2, env3, opts) {
      if (!opts) {
        opts = {};
      }
      var BS = opts.escape || "\\";
      var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
      var chunker = new RegExp([
        "(" + CONTROL + ")",
        // control chars
        "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
      ].join("|"), "g");
      var matches = matchAll(string2, chunker);
      if (matches.length === 0) {
        return [];
      }
      if (!env3) {
        env3 = {};
      }
      var commented = false;
      return matches.map(function(match2) {
        var s4 = match2[0];
        if (!s4 || commented) {
          return void 0;
        }
        if (controlRE.test(s4)) {
          return { op: s4 };
        }
        var quote = false;
        var esc = false;
        var out = "";
        var isGlob = false;
        var i22;
        function parseEnvVar() {
          i22 += 1;
          var varend;
          var varname;
          var char = s4.charAt(i22);
          if (char === "{") {
            i22 += 1;
            if (s4.charAt(i22) === "}") {
              throw new Error("Bad substitution: " + s4.slice(i22 - 2, i22 + 1));
            }
            varend = s4.indexOf("}", i22);
            if (varend < 0) {
              throw new Error("Bad substitution: " + s4.slice(i22));
            }
            varname = s4.slice(i22, varend);
            i22 = varend;
          } else if (/[*@#?$!_-]/.test(char)) {
            varname = char;
            i22 += 1;
          } else {
            var slicedFromI = s4.slice(i22);
            varend = slicedFromI.match(/[^\w\d_]/);
            if (!varend) {
              varname = slicedFromI;
              i22 = s4.length;
            } else {
              varname = slicedFromI.slice(0, varend.index);
              i22 += varend.index - 1;
            }
          }
          return getVar(env3, "", varname);
        }
        for (i22 = 0; i22 < s4.length; i22++) {
          var c3 = s4.charAt(i22);
          isGlob = isGlob || !quote && (c3 === "*" || c3 === "?");
          if (esc) {
            out += c3;
            esc = false;
          } else if (quote) {
            if (c3 === quote) {
              quote = false;
            } else if (quote == SQ) {
              out += c3;
            } else {
              if (c3 === BS) {
                i22 += 1;
                c3 = s4.charAt(i22);
                if (c3 === DQ || c3 === BS || c3 === DS) {
                  out += c3;
                } else {
                  out += BS + c3;
                }
              } else if (c3 === DS) {
                out += parseEnvVar();
              } else {
                out += c3;
              }
            }
          } else if (c3 === DQ || c3 === SQ) {
            quote = c3;
          } else if (controlRE.test(c3)) {
            return { op: s4 };
          } else if (hash.test(c3)) {
            commented = true;
            var commentObj = { comment: string2.slice(match2.index + i22 + 1) };
            if (out.length) {
              return [out, commentObj];
            }
            return [commentObj];
          } else if (c3 === BS) {
            esc = true;
          } else if (c3 === DS) {
            out += parseEnvVar();
          } else {
            out += c3;
          }
        }
        if (isGlob) {
          return { op: "glob", pattern: out };
        }
        return out;
      }).reduce(function(prev, arg) {
        return typeof arg === "undefined" ? prev : prev.concat(arg);
      }, []);
    }
    module2.exports = function parse4(s4, env3, opts) {
      var mapped = parseInternal(s4, env3, opts);
      if (typeof env3 !== "function") {
        return mapped;
      }
      return mapped.reduce(function(acc, s22) {
        if (typeof s22 === "object") {
          return acc.concat(s22);
        }
        var xs = s22.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
        if (xs.length === 1) {
          return acc.concat(xs[0]);
        }
        return acc.concat(xs.filter(Boolean).map(function(x4) {
          if (startsWithToken.test(x4)) {
            return JSON.parse(x4.split(TOKEN)[1]);
          }
          return x4;
        }));
      }, []);
    };
  }
});
var require_shell_quote = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/index.js"(exports2) {
    "use strict";
    exports2.quote = require_quote();
    exports2.parse = require_parse();
  }
});
var BroCliError = class extends Error {
  constructor(message, event) {
    const errPrefix = "BroCli error: ";
    super(message === void 0 ? message : `${errPrefix}${message}`);
    this.event = event;
  }
};
var import_clone = __toESM2(require_clone(), 1);
var getOptionTypeText = (option) => {
  let result = "";
  switch (option.type) {
    case "boolean":
      result = "";
      break;
    case "number": {
      if ((option.minVal ?? option.maxVal) !== void 0) {
        let text = "";
        if (option.isInt) text = text + `integer `;
        if (option.minVal !== void 0) text = text + `[${option.minVal};`;
        else text = text + `(\u221E;`;
        if (option.maxVal !== void 0) text = text + `${option.maxVal}]`;
        else text = text + `\u221E)`;
        result = text;
        break;
      }
      if (option.isInt) {
        result = "integer";
        break;
      }
      result = "number";
      break;
    }
    case "string": {
      if (option.enumVals) {
        result = "[ " + option.enumVals.join(" | ") + " ]";
        break;
      }
      result = "string";
      break;
    }
    case "positional": {
      result = `${option.isRequired ? "<" : "["}${option.enumVals ? option.enumVals.join("|") : option.name}${option.isRequired ? ">" : "]"}`;
      break;
    }
  }
  if (option.isRequired && option.type !== "positional") result = "!" + result.length ? " " : "" + result;
  return result;
};
var defaultEventHandler = async (event) => {
  var _a2;
  switch (event.type) {
    case "command_help": {
      const command3 = event.command;
      const commandName = getCommandNameWithParents(command3);
      const cliName = event.name;
      const desc = command3.desc ?? command3.shortDesc;
      const subs = (_a2 = command3.subcommands) == null ? void 0 : _a2.filter((s4) => !s4.hidden);
      const subcommands = subs && subs.length ? subs : void 0;
      if (desc !== void 0) {
        console.log(`
${desc}`);
      }
      const opts = Object.values(command3.options ?? {}).filter(
        (opt) => !opt.config.isHidden
      );
      const positionals = opts.filter((opt) => opt.config.type === "positional");
      const options = opts.filter((opt) => opt.config.type !== "positional");
      console.log("\nUsage:");
      if (command3.handler) {
        console.log(
          `  ${cliName ? cliName + " " : ""}${commandName}${positionals.length ? " " + positionals.map(({ config: p3 }) => getOptionTypeText(p3)).join(" ") : ""} [flags]`
        );
      } else console.log(`  ${cliName ? cliName + " " : ""}${commandName} [command]`);
      if (command3.aliases) {
        console.log(`
Aliases:`);
        console.log(`  ${[command3.name, ...command3.aliases].join(", ")}`);
      }
      if (subcommands) {
        console.log("\nAvailable Commands:");
        const padding = 3;
        const maxLength = subcommands.reduce((p3, e4) => e4.name.length > p3 ? e4.name.length : p3, 0);
        const paddedLength = maxLength + padding;
        const preDescPad = 2 + paddedLength;
        const data = subcommands.map(
          (s4) => `  ${s4.name.padEnd(paddedLength)}${(() => {
            const description = s4.shortDesc ?? s4.desc;
            if (!(description == null ? void 0 : description.length)) return "";
            const split = description.split("\n");
            const first = split.shift();
            const final = [first, ...split.map((s22) => "".padEnd(preDescPad) + s22)].join("\n");
            return final;
          })()}`
        ).join("\n");
        console.log(data);
      }
      if (options.length) {
        const aliasLength = options.reduce((p3, e4) => {
          const currentLength = e4.config.aliases.reduce((pa, a3) => pa + a3.length, 0) + (e4.config.aliases.length - 1) * 2 + 1;
          return currentLength > p3 ? currentLength : p3;
        }, 0);
        const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
        const nameLength = options.reduce((p3, e4) => {
          const typeLen = getOptionTypeText(e4.config).length;
          const length = typeLen > 0 ? e4.config.name.length + 1 + typeLen : e4.config.name.length;
          return length > p3 ? length : p3;
        }, 0) + 3;
        const preDescPad = paddedAliasLength + nameLength + 2;
        const data = options.map(
          ({ config: opt }) => `  ${`${opt.aliases.length ? opt.aliases.join(", ") + "," : ""}`.padEnd(paddedAliasLength)}${`${opt.name}${(() => {
            const typeText = getOptionTypeText(opt);
            return typeText.length ? " " + typeText : "";
          })()}`.padEnd(nameLength)}${(() => {
            var _a3;
            if (!((_a3 = opt.description) == null ? void 0 : _a3.length)) {
              return opt.default !== void 0 ? `default: ${JSON.stringify(opt.default)}` : "";
            }
            const split = opt.description.split("\n");
            const first = split.shift();
            const def = opt.default !== void 0 ? ` (default: ${JSON.stringify(opt.default)})` : "";
            const final = [first, ...split.map((s4) => "".padEnd(preDescPad) + s4)].join("\n") + def;
            return final;
          })()}`
        ).join("\n");
        console.log("\nFlags:");
        console.log(data);
      }
      console.log("\nGlobal flags:");
      console.log(`  -h, --help      help for ${commandName}`);
      console.log(`  -v, --version   version${cliName ? ` for ${cliName}` : ""}`);
      if (subcommands) {
        console.log(
          `
Use "${cliName ? cliName + " " : ""}${commandName} [command] --help" for more information about a command.
`
        );
      }
      return true;
    }
    case "global_help": {
      const cliName = event.name;
      const desc = event.description;
      const commands3 = event.commands.filter((c3) => !c3.hidden);
      if (desc !== void 0) {
        console.log(`${desc}
`);
      }
      console.log("Usage:");
      console.log(`  ${cliName ? cliName + " " : ""}[command]`);
      if (commands3.length) {
        console.log("\nAvailable Commands:");
        const padding = 3;
        const maxLength = commands3.reduce((p3, e4) => e4.name.length > p3 ? e4.name.length : p3, 0);
        const paddedLength = maxLength + padding;
        const data = commands3.map(
          (c3) => `  ${c3.name.padEnd(paddedLength)}${(() => {
            const desc2 = c3.shortDesc ?? c3.desc;
            if (!(desc2 == null ? void 0 : desc2.length)) return "";
            const split = desc2.split("\n");
            const first = split.shift();
            const final = [first, ...split.map((s4) => "".padEnd(paddedLength + 2) + s4)].join("\n");
            return final;
          })()}`
        ).join("\n");
        console.log(data);
      } else {
        console.log("\nNo available commands.");
      }
      console.log("\nFlags:");
      console.log(`  -h, --help      help${cliName ? ` for ${cliName}` : ""}`);
      console.log(`  -v, --version   version${cliName ? ` for ${cliName}` : ""}`);
      console.log("\n");
      return true;
    }
    case "version": {
      return true;
    }
    case "error": {
      let msg;
      switch (event.violation) {
        case "above_max": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const max = option.maxVal;
          msg = `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
          break;
        }
        case "below_min": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const min = option.minVal;
          msg = `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
          break;
        }
        case "expected_int": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
          break;
        }
        case "invalid_boolean_syntax": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
Allowed values: true, false, 0, 1`;
          break;
        }
        case "invalid_string_syntax": {
          const matchedName = event.offender.namePart;
          msg = `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
          break;
        }
        case "invalid_number_syntax": {
          const matchedName = event.offender.namePart;
          msg = `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
          break;
        }
        case "invalid_number_value": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
          break;
        }
        case "enum_violation": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const values = option.enumVals;
          msg = option.type === "positional" ? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${values.join(", ")}; Received: ${data}` : `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`;
          break;
        }
        case "unknown_command_error": {
          const msg2 = `Unknown command: '${event.offender}'.
Type '--help' to get help on the cli.`;
          console.error(msg2);
          return true;
        }
        case "unknown_subcommand_error": {
          const cName = getCommandNameWithParents(event.command);
          const msg2 = `Unknown command: ${cName} ${event.offender}.
Type '${cName} --help' to get the help on command.`;
          console.error(msg2);
          return true;
        }
        case "missing_args_error": {
          const { missing: missingOpts, command: command3 } = event;
          msg = `Command '${command3.name}' is missing following required options: ${missingOpts.map((opt) => {
            const name = opt.shift();
            const aliases = opt;
            if (aliases.length) return `${name} [${aliases.join(", ")}]`;
            return name;
          }).join(", ")}`;
          break;
        }
        case "unrecognized_args_error": {
          const { command: command3, unrecognized } = event;
          msg = `Unrecognized options for command '${command3.name}': ${unrecognized.join(", ")}`;
          break;
        }
        case "unknown_error": {
          const e4 = event.error;
          console.error(typeof e4 === "object" && e4 !== null && "message" in e4 ? e4.message : e4);
          return true;
        }
      }
      console.error(msg);
      return true;
    }
  }
  return false;
};
var eventHandlerWrapper = (customEventHandler) => async (event) => await customEventHandler(event) ? true : await defaultEventHandler(event);
var import_shell_quote = __toESM2(require_shell_quote(), 1);
function isInt(value) {
  return value === Math.floor(value);
}
var executeOrLog = async (target) => typeof target === "string" ? console.log(target) : target ? await target() : void 0;
var generatePrefix = (name) => name.startsWith("-") ? name : name.length > 1 ? `--${name}` : `-${name}`;
var validateOptions = (config) => {
  const cloned = (0, import_clone.default)(config);
  const entries = [];
  const storedNames = [];
  const cfgEntries = Object.entries(cloned);
  for (const [key, value] of cfgEntries) {
    const cfg = value._.config;
    if (cfg.name === void 0) cfg.name = key;
    if (cfg.type === "positional") continue;
    if (cfg.name.includes("=")) {
      throw new BroCliError(
        `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
      );
    }
    for (const alias of cfg.aliases) {
      if (alias.includes("=")) {
        throw new BroCliError(
          `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
        );
      }
    }
    cfg.name = generatePrefix(cfg.name);
    cfg.aliases = cfg.aliases.map((a3) => generatePrefix(a3));
  }
  for (const [key, value] of cfgEntries) {
    const cfg = value._.config;
    if (cfg.type === "positional") {
      entries.push([key, { config: cfg, $output: void 0 }]);
      continue;
    }
    const reservedNames = ["--help", "-h", "--version", "-v"];
    const allNames = [cfg.name, ...cfg.aliases];
    for (const name of allNames) {
      const match2 = reservedNames.find((n3) => n3 === name);
      if (match2) throw new BroCliError(`Can't define option '${cfg.name}' - name '${match2}' is reserved!`);
    }
    for (const storage of storedNames) {
      const nameOccupier = storage.find((e4) => e4 === cfg.name);
      if (!nameOccupier) continue;
      throw new BroCliError(
        `Can't define option '${cfg.name}' - name is already in use by option '${storage[0]}'!`
      );
    }
    for (const alias of cfg.aliases) {
      for (const storage of storedNames) {
        const nameOccupier = storage.find((e4) => e4 === alias);
        if (!nameOccupier) continue;
        throw new BroCliError(
          `Can't define option '${cfg.name}' - alias '${alias}' is already in use by option '${storage[0]}'!`
        );
      }
    }
    const currentNames = [cfg.name, ...cfg.aliases];
    storedNames.push(currentNames);
    currentNames.forEach((name, idx) => {
      if (currentNames.findIndex((e4) => e4 === name) === idx) return;
      throw new BroCliError(
        `Can't define option '${cfg.name}' - duplicate alias '${name}'!`
      );
    });
    entries.push([key, { config: cfg, $output: void 0 }]);
  }
  return Object.fromEntries(entries);
};
var assignParent = (parent, subcommands) => subcommands.forEach((e4) => {
  e4.parent = parent;
  if (e4.subcommands) assignParent(e4, e4.subcommands);
});
var command2 = (command3) => {
  var _a2, _b, _c;
  const allNames = command3.aliases ? [command3.name, ...command3.aliases] : [command3.name];
  const cmd = (0, import_clone.default)(command3);
  if (command3.subcommands && command3.options && Object.values(command3.options).find((opt) => opt._.config.type === "positional")) {
    throw new BroCliError(
      `Can't define command '${cmd.name}' - command can't have subcommands and positional args at the same time!`
    );
  }
  if (!command3.handler && !command3.subcommands) {
    throw new BroCliError(
      `Can't define command '${cmd.name}' - command without subcommands must have a handler present!`
    );
  }
  const processedOptions = command3.options ? validateOptions(command3.options) : void 0;
  cmd.options = processedOptions;
  cmd.name = cmd.name ?? ((_a2 = cmd.aliases) == null ? void 0 : _a2.shift());
  if (!cmd.name) throw new BroCliError(`Can't define command without name!`);
  cmd.aliases = ((_b = cmd.aliases) == null ? void 0 : _b.length) ? cmd.aliases : void 0;
  if (cmd.name.startsWith("-")) {
    throw new BroCliError(`Can't define command '${cmd.name}' - command name can't start with '-'!`);
  }
  (_c = cmd.aliases) == null ? void 0 : _c.forEach((a3) => {
    if (a3.startsWith("-")) {
      throw new BroCliError(`Can't define command '${cmd.name}' - command aliases can't start with '-'!`);
    }
  });
  allNames.forEach((n3, i4) => {
    if (n3 === "help") {
      throw new BroCliError(
        `Can't define command '${cmd.name}' - 'help' is a reserved name. If you want to redefine help message - do so in runCli's config.`
      );
    }
    const lCaseName = n3 == null ? void 0 : n3.toLowerCase();
    if (lCaseName === "0" || lCaseName === "1" || lCaseName === "true" || lCaseName === "false") {
      throw new BroCliError(
        `Can't define command '${cmd.name}' - '${n3}' is a reserved for boolean values name!`
      );
    }
    const idx = allNames.findIndex((an) => an === n3);
    if (idx !== i4) throw new BroCliError(`Can't define command '${cmd.name}' - duplicate alias '${n3}'!`);
  });
  if (cmd.subcommands) {
    assignParent(cmd, cmd.subcommands);
  }
  return cmd;
};
var getCommandInner = (commands3, candidates, args, cliName, cliDescription) => {
  const { data: arg, originalIndex: index6 } = candidates.shift();
  const command3 = commands3.find((c3) => {
    const names = c3.aliases ? [c3.name, ...c3.aliases] : [c3.name];
    const res = names.find((name) => name === arg);
    return res;
  });
  if (!command3) {
    return {
      command: command3,
      args
    };
  }
  const newArgs = removeByIndex(args, index6);
  if (!candidates.length || !command3.subcommands) {
    return {
      command: command3,
      args: newArgs
    };
  }
  const newCandidates = candidates.map((c3) => ({ data: c3.data, originalIndex: c3.originalIndex - 1 }));
  const subcommand = getCommandInner(command3.subcommands, newCandidates, newArgs, cliName, cliDescription);
  if (!subcommand.command) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unknown_subcommand_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      offender: candidates[0].data
    });
  }
  return subcommand;
};
var getCommand = (commands3, args, cliName, cliDescription) => {
  var _a2;
  const candidates = [];
  for (let i4 = 0; i4 < args.length; ++i4) {
    const arg = args[i4];
    if (arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v") {
      const lCaseNext = (_a2 = args[i4 + 1]) == null ? void 0 : _a2.toLowerCase();
      if (lCaseNext === "0" || lCaseNext === "1" || lCaseNext === "true" || lCaseNext === "false") ++i4;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("-")) {
      if (!arg.includes("=")) ++i4;
      continue;
    }
    candidates.push({
      data: arg,
      originalIndex: i4
    });
  }
  if (!candidates.length) {
    return {
      command: void 0,
      args
    };
  }
  const firstCandidate = candidates[0];
  if (firstCandidate.data === "help") {
    return {
      command: "help",
      args: removeByIndex(args, firstCandidate.originalIndex)
    };
  }
  const { command: command3, args: argsRes } = getCommandInner(commands3, candidates, args, cliName, cliDescription);
  if (!command3) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unknown_command_error",
      commands: commands3,
      name: cliName,
      description: cliDescription,
      offender: firstCandidate.data
    });
  }
  return {
    command: command3,
    args: argsRes
  };
};
var parseArg = (command3, options, positionals, arg, nextArg, cliName, cliDescription) => {
  let data = void 0;
  const argSplit = arg.split("=");
  const hasEq = arg.includes("=");
  const namePart = argSplit.shift();
  const dataPart = hasEq ? argSplit.join("=") : nextArg;
  let skipNext = !hasEq;
  if (namePart === "--help" || namePart === "-h") {
    return {
      isHelp: true
    };
  }
  if (namePart === "--version" || namePart === "-v") {
    return {
      isVersion: true
    };
  }
  if (!arg.startsWith("-")) {
    if (!positionals.length) return {};
    const pos = positionals.shift();
    if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === arg)) {
      throw new BroCliError(void 0, {
        type: "error",
        name: cliName,
        description: cliDescription,
        violation: "enum_violation",
        command: command3,
        option: pos[1],
        offender: {
          dataPart: arg
        }
      });
    }
    data = arg;
    return {
      data,
      skipNext: false,
      name: pos[0],
      option: pos[1]
    };
  }
  const option = options.find(([optKey, opt]) => {
    const names = [opt.name, ...opt.aliases];
    if (opt.type === "boolean") {
      const match2 = names.find((name) => name === namePart);
      if (!match2) return false;
      let lcaseData = dataPart == null ? void 0 : dataPart.toLowerCase();
      if (!hasEq && (nextArg == null ? void 0 : nextArg.startsWith("-"))) {
        data = true;
        skipNext = false;
        return true;
      }
      if (lcaseData === void 0 || lcaseData === "" || lcaseData === "true" || lcaseData === "1") {
        data = true;
        return true;
      }
      if (lcaseData === "false" || lcaseData === "0") {
        data = false;
        return true;
      }
      if (!hasEq) {
        data = true;
        skipNext = false;
        return true;
      }
      throw new BroCliError(void 0, {
        type: "error",
        name: cliName,
        description: cliDescription,
        violation: "invalid_boolean_syntax",
        option: opt,
        command: command3,
        offender: {
          namePart,
          dataPart
        }
      });
    } else {
      const match2 = names.find((name) => name === namePart);
      if (!match2) return false;
      if (opt.type === "string") {
        if (!hasEq && nextArg === void 0) {
          throw new BroCliError(void 0, {
            type: "error",
            name: cliName,
            description: cliDescription,
            violation: "invalid_string_syntax",
            option: opt,
            command: command3,
            offender: {
              namePart,
              dataPart
            }
          });
        }
        if (opt.enumVals && !opt.enumVals.find((val2) => val2 === dataPart)) {
          throw new BroCliError(void 0, {
            type: "error",
            name: cliName,
            description: cliDescription,
            violation: "enum_violation",
            option: opt,
            command: command3,
            offender: {
              namePart,
              dataPart
            }
          });
        }
        data = dataPart;
        return true;
      }
      if (!hasEq && nextArg === void 0) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "invalid_number_syntax",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      const numData = Number(dataPart);
      if (isNaN(numData)) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "invalid_number_value",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.isInt && !isInt(numData)) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "expected_int",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.minVal !== void 0 && numData < opt.minVal) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "below_min",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.maxVal !== void 0 && numData > opt.maxVal) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "above_max",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      data = numData;
      return true;
    }
  });
  return {
    data,
    skipNext,
    name: option == null ? void 0 : option[0],
    option: option == null ? void 0 : option[1]
  };
};
var parseOptions = (command3, args, cliName, cliDescription, omitKeysOfUndefinedOptions) => {
  const options = command3.options;
  const optEntries = Object.entries(options ?? {}).map(
    (opt) => [opt[0], opt[1].config]
  );
  const nonPositionalEntries = optEntries.filter(([key, opt]) => opt.type !== "positional");
  const positionalEntries = optEntries.filter(([key, opt]) => opt.type === "positional");
  const result = {};
  const missingRequiredArr = [];
  const unrecognizedArgsArr = [];
  for (let i4 = 0; i4 < args.length; ++i4) {
    const arg = args[i4];
    const nextArg = args[i4 + 1];
    const {
      data,
      name,
      option,
      skipNext,
      isHelp,
      isVersion
    } = parseArg(command3, nonPositionalEntries, positionalEntries, arg, nextArg, cliName, cliDescription);
    if (!option) unrecognizedArgsArr.push(arg.split("=")[0]);
    if (skipNext) ++i4;
    if (isHelp) return "help";
    if (isVersion) return "version";
    result[name] = data;
  }
  for (const [optKey, option] of optEntries) {
    const data = result[optKey] ?? option.default;
    if (!omitKeysOfUndefinedOptions) {
      result[optKey] = data;
    } else {
      if (data !== void 0) result[optKey] = data;
    }
    if (option.isRequired && result[optKey] === void 0) missingRequiredArr.push([option.name, ...option.aliases]);
  }
  if (missingRequiredArr.length) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "missing_args_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      missing: missingRequiredArr
    });
  }
  if (unrecognizedArgsArr.length) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unrecognized_args_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      unrecognized: unrecognizedArgsArr
    });
  }
  return Object.keys(result).length ? result : void 0;
};
var getCommandNameWithParents = (command3) => command3.parent ? `${getCommandNameWithParents(command3.parent)} ${command3.name}` : command3.name;
var validateCommands = (commands3, parent) => {
  const storedNames = {};
  for (const cmd of commands3) {
    const storageVals = Object.values(storedNames);
    for (const storage of storageVals) {
      const nameOccupier = storage.find((e4) => e4 === cmd.name);
      if (!nameOccupier) continue;
      throw new BroCliError(
        `Can't define command '${getCommandNameWithParents(cmd)}': name is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
      );
    }
    if (cmd.aliases) {
      for (const alias of cmd.aliases) {
        for (const storage of storageVals) {
          const nameOccupier = storage.find((e4) => e4 === alias);
          if (!nameOccupier) continue;
          throw new BroCliError(
            `Can't define command '${getCommandNameWithParents(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
          );
        }
      }
    }
    storedNames[cmd.name] = cmd.aliases ? [cmd.name, ...cmd.aliases] : [cmd.name];
    if (cmd.subcommands) cmd.subcommands = validateCommands(cmd.subcommands, cmd);
  }
  return commands3;
};
var removeByIndex = (arr, idx) => [...arr.slice(0, idx), ...arr.slice(idx + 1, arr.length)];
var run = async (commands3, config) => {
  var _a2, _b;
  const eventHandler = (config == null ? void 0 : config.theme) ? eventHandlerWrapper(config.theme) : defaultEventHandler;
  const argSource = (config == null ? void 0 : config.argSource) ?? process.argv;
  const version3 = config == null ? void 0 : config.version;
  const help = config == null ? void 0 : config.help;
  const omitKeysOfUndefinedOptions = (config == null ? void 0 : config.omitKeysOfUndefinedOptions) ?? false;
  const cliName = config == null ? void 0 : config.name;
  const cliDescription = config == null ? void 0 : config.description;
  try {
    const processedCmds = validateCommands(commands3);
    let args = argSource.slice(2, argSource.length);
    if (!args.length) {
      return help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
    if (helpIndex !== -1 && (helpIndex > 0 ? ((_a2 = args[helpIndex - 1]) == null ? void 0 : _a2.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
      const command4 = getCommand(processedCmds, args, cliName, cliDescription).command;
      if (typeof command4 === "object") {
        return command4.help !== void 0 ? await executeOrLog(command4.help) : await eventHandler({
          type: "command_help",
          description: cliDescription,
          name: cliName,
          command: command4
        });
      } else {
        return help !== void 0 ? await executeOrLog(help) : await eventHandler({
          type: "global_help",
          description: cliDescription,
          name: cliName,
          commands: processedCmds
        });
      }
    }
    const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
    if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
      return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
        type: "version",
        name: cliName,
        description: cliDescription
      });
    }
    const { command: command3, args: newArgs } = getCommand(processedCmds, args, cliName, cliDescription);
    if (!command3) {
      return help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    if (command3 === "help") {
      let helpCommand;
      let newestArgs = newArgs;
      do {
        const res = getCommand(processedCmds, newestArgs, cliName, cliDescription);
        helpCommand = res.command;
        newestArgs = res.args;
      } while (helpCommand === "help");
      return helpCommand ? helpCommand.help !== void 0 ? await executeOrLog(helpCommand.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: helpCommand
      }) : help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    const optionResult = parseOptions(command3, newArgs, cliName, cliDescription, omitKeysOfUndefinedOptions);
    if (optionResult === "help") {
      return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: command3
      });
    }
    if (optionResult === "version") {
      return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
        type: "version",
        name: cliName,
        description: cliDescription
      });
    }
    if (command3.handler) {
      if (config == null ? void 0 : config.hook) await config.hook("before", command3);
      await command3.handler(command3.transform ? await command3.transform(optionResult) : optionResult);
      if (config == null ? void 0 : config.hook) await config.hook("after", command3);
      return;
    } else {
      return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: command3
      });
    }
  } catch (e4) {
    if (e4 instanceof BroCliError) {
      if (e4.event) await eventHandler(e4.event);
      else {
        if (!(config == null ? void 0 : config.noExit)) console.error(e4.message);
        else return e4.message;
      }
    } else {
      await eventHandler({
        type: "error",
        violation: "unknown_error",
        name: cliName,
        description: cliDescription,
        error: e4
      });
    }
    if (!(config == null ? void 0 : config.noExit)) process.exit(1);
    return;
  }
};
var OptionBuilderBase = class _OptionBuilderBase {
  _;
  config = () => this._.config;
  constructor(config) {
    this._ = {
      config: config ?? {
        aliases: [],
        type: "string"
      },
      $output: void 0
    };
  }
  string(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "string", name });
  }
  number(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "number", name });
  }
  boolean(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "boolean", name });
  }
  positional(displayName) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "positional", name: displayName });
  }
  alias(...aliases) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, aliases });
  }
  desc(description) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, description });
  }
  hidden() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isHidden: true });
  }
  required() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isRequired: true });
  }
  default(value) {
    const config = this.config();
    const enums = config.enumVals;
    if (enums && !enums.find((v6) => value === v6)) {
      throw new Error(
        `Option enums [ ${enums.join(", ")} ] are incompatible with default value ${value}`
      );
    }
    return new _OptionBuilderBase({ ...config, default: value });
  }
  enum(...values) {
    const config = this.config();
    const defaultVal = config.default;
    if (defaultVal !== void 0 && !values.find((v6) => defaultVal === v6)) {
      throw new Error(
        `Option enums [ ${values.join(", ")} ] are incompatible with default value ${defaultVal}`
      );
    }
    return new _OptionBuilderBase({ ...config, enumVals: values });
  }
  min(value) {
    const config = this.config();
    const maxVal = config.maxVal;
    if (maxVal !== void 0 && maxVal < value) {
      throw new BroCliError("Unable to define option's min value to be higher than max value!");
    }
    return new _OptionBuilderBase({ ...config, minVal: value });
  }
  max(value) {
    const config = this.config();
    const minVal = config.minVal;
    if (minVal !== void 0 && minVal > value) {
      throw new BroCliError("Unable to define option's max value to be lower than min value!");
    }
    return new _OptionBuilderBase({ ...config, maxVal: value });
  }
  int() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isInt: true });
  }
};
function string(name) {
  return typeof name === "string" ? new OptionBuilderBase().string(name) : new OptionBuilderBase().string();
}
function number(name) {
  return typeof name === "string" ? new OptionBuilderBase().number(name) : new OptionBuilderBase().number();
}
function boolean(name) {
  return typeof name === "string" ? new OptionBuilderBase().boolean(name) : new OptionBuilderBase().boolean();
}

// src/cli/index.ts
init_source();

// src/cli/schema.ts
init_source();

// ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/config.js
(function() {
  require_main().config(
    Object.assign(
      {},
      require_env_options(),
      require_cli_options()(process.argv)
    )
  );
})();

// src/cli/schema.ts
var import_fs13 = require("fs");
var import_hanji15 = __toESM(require_hanji());
init_schemaValidator();
init_utils();
init_global();
init_utils2();

// ../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
var import_node_path = __toESM(require("node:path"), 1);
var import_node_os2 = __toESM(require("node:os"), 1);
var import_node_process2 = __toESM(require("node:process"), 1);
var homedir = import_node_os2.default.homedir();
var tmpdir = import_node_os2.default.tmpdir();
var { env: env2 } = import_node_process2.default;
var macos = (name) => {
  const library = import_node_path.default.join(homedir, "Library");
  return {
    data: import_node_path.default.join(library, "Application Support", name),
    config: import_node_path.default.join(library, "Preferences", name),
    cache: import_node_path.default.join(library, "Caches", name),
    log: import_node_path.default.join(library, "Logs", name),
    temp: import_node_path.default.join(tmpdir, name)
  };
};
var windows = (name) => {
  const appData = env2.APPDATA || import_node_path.default.join(homedir, "AppData", "Roaming");
  const localAppData = env2.LOCALAPPDATA || import_node_path.default.join(homedir, "AppData", "Local");
  return {
    // Data/config/cache/log are invented by me as Windows isn't opinionated about this
    data: import_node_path.default.join(localAppData, name, "Data"),
    config: import_node_path.default.join(appData, name, "Config"),
    cache: import_node_path.default.join(localAppData, name, "Cache"),
    log: import_node_path.default.join(localAppData, name, "Log"),
    temp: import_node_path.default.join(tmpdir, name)
  };
};
var linux = (name) => {
  const username = import_node_path.default.basename(homedir);
  return {
    data: import_node_path.default.join(env2.XDG_DATA_HOME || import_node_path.default.join(homedir, ".local", "share"), name),
    config: import_node_path.default.join(env2.XDG_CONFIG_HOME || import_node_path.default.join(homedir, ".config"), name),
    cache: import_node_path.default.join(env2.XDG_CACHE_HOME || import_node_path.default.join(homedir, ".cache"), name),
    // https://wiki.debian.org/XDGBaseDirectorySpecification#state
    log: import_node_path.default.join(env2.XDG_STATE_HOME || import_node_path.default.join(homedir, ".local", "state"), name),
    temp: import_node_path.default.join(tmpdir, username, name)
  };
};
function envPaths(name, { suffix = "nodejs" } = {}) {
  if (typeof name !== "string") {
    throw new TypeError(`Expected a string, got ${typeof name}`);
  }
  if (suffix) {
    name += `-${suffix}`;
  }
  if (import_node_process2.default.platform === "darwin") {
    return macos(name);
  }
  if (import_node_process2.default.platform === "win32") {
    return windows(name);
  }
  return linux(name);
}

// src/utils/certs.ts
var import_fs2 = require("fs");
var import_promises = require("fs/promises");
var import_node_child_process = require("node:child_process");
var import_path2 = require("path");
function runCommand(command, options = {}) {
  return new Promise((resolve2) => {
    (0, import_node_child_process.exec)(command, options, (error2) => {
      return resolve2({ exitCode: (error2 == null ? void 0 : error2.code) ?? 0 });
    });
  });
}
var certs = async () => {
  const res = await runCommand("mkcert --help");
  if (res.exitCode === 0) {
    const p3 = envPaths("drizzle-studio", {
      suffix: ""
    });
    (0, import_fs2.mkdirSync)(p3.data, { recursive: true });
    const keyPath = (0, import_path2.join)(p3.data, "localhost-key.pem");
    const certPath = (0, import_path2.join)(p3.data, "localhost.pem");
    try {
      await Promise.all([(0, import_promises.access)(keyPath), (0, import_promises.access)(certPath)]);
    } catch (e4) {
      await runCommand(`mkcert localhost`, { cwd: p3.data });
    }
    const [key, cert] = await Promise.all([
      (0, import_promises.readFile)(keyPath, { encoding: "utf-8" }),
      (0, import_promises.readFile)(certPath, { encoding: "utf-8" })
    ]);
    return key && cert ? { key, cert } : null;
  }
  return null;
};

// src/cli/commands/check.ts
init_utils2();
var checkHandler = (out, dialect6) => {
  const { snapshots } = prepareOutFolder(out, dialect6);
  const report = validateWithReport(snapshots, dialect6);
  if (report.nonLatest.length > 0) {
    console.log(
      report.nonLatest.map((it) => {
        return `${it} is not of the latest version, please run "drizzle-kit up"`;
      }).join("\n")
    );
    process.exit(1);
  }
  if (report.malformed.length) {
    const message2 = report.malformed.map((it) => {
      return `${it} data is malformed`;
    }).join("\n");
    console.log(message2);
  }
  const collisionEntries = Object.entries(report.idsMap).filter(
    (it) => it[1].snapshots.length > 1
  );
  const message = collisionEntries.map((it) => {
    const data = it[1];
    return `[${data.snapshots.join(
      ", "
    )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
  }).join("\n");
  if (message) {
    console.log(message);
  }
  const abort = report.malformed.length || collisionEntries.length > 0;
  if (abort) {
    process.exit(1);
  }
};

// src/cli/commands/drop.ts
init_source();
var import_fs7 = require("fs");
var import_fs8 = __toESM(require("fs"));
var import_hanji4 = __toESM(require_hanji());
var import_path6 = require("path");
init_views();
init_migrate();
var dropMigration = async ({
  out,
  bundle
}) => {
  const metaFilePath = (0, import_path6.join)(out, "meta", "_journal.json");
  const journal = JSON.parse((0, import_fs7.readFileSync)(metaFilePath, "utf-8"));
  if (journal.entries.length === 0) {
    console.log(
      `[${source_default.blue("i")}] no migration entries found in ${metaFilePath}`
    );
    return;
  }
  const result = await (0, import_hanji4.render)(new DropMigrationView(journal.entries));
  if (result.status === "aborted") return;
  delete journal.entries[journal.entries.indexOf(result.data)];
  const resultJournal = {
    ...journal,
    entries: journal.entries.filter(Boolean)
  };
  const sqlFilePath = (0, import_path6.join)(out, `${result.data.tag}.sql`);
  const snapshotFilePath = (0, import_path6.join)(
    out,
    "meta",
    `${result.data.tag.split("_")[0]}_snapshot.json`
  );
  (0, import_fs7.rmSync)(sqlFilePath);
  (0, import_fs7.rmSync)(snapshotFilePath);
  (0, import_fs7.writeFileSync)(metaFilePath, JSON.stringify(resultJournal, null, 2));
  if (bundle) {
    import_fs8.default.writeFileSync(
      (0, import_path6.join)(out, `migrations.js`),
      embeddedMigrations(resultJournal)
    );
  }
  console.log(
    `[${source_default.green("\u2713")}] ${source_default.bold(
      result.data.tag
    )} migration successfully dropped`
  );
};

// src/cli/commands/mysqlUp.ts
var upMysqlHandler = (out) => {
};

// src/cli/commands/pgUp.ts
init_source();
var import_fs9 = require("fs");
init_pgSchema();
init_utils2();
var upPgHandler = (out) => {
  const { snapshots } = prepareOutFolder(out, "postgresql");
  const report = validateWithReport(snapshots, "postgresql");
  report.nonLatest.map((it) => ({
    path: it,
    raw: report.rawMap[it]
  })).forEach((it) => {
    const path4 = it.path;
    let resultV6 = it.raw;
    if (it.raw.version === "5") {
      resultV6 = updateUpToV6(it.raw);
    }
    const result = updateUpToV7(resultV6);
    console.log(`[${source_default.green("\u2713")}] ${path4}`);
    (0, import_fs9.writeFileSync)(path4, JSON.stringify(result, null, 2));
  });
  console.log("Everything's fine \u{1F436}\u{1F525}");
};
var updateUpToV6 = (json) => {
  const schema6 = pgSchemaV5.parse(json);
  const tables = Object.fromEntries(
    Object.entries(schema6.tables).map((it) => {
      const table6 = it[1];
      const schema7 = table6.schema || "public";
      return [`${schema7}.${table6.name}`, table6];
    })
  );
  const enums = Object.fromEntries(
    Object.entries(schema6.enums).map((it) => {
      const en = it[1];
      return [
        `public.${en.name}`,
        {
          name: en.name,
          schema: "public",
          values: Object.values(en.values)
        }
      ];
    })
  );
  return {
    ...schema6,
    version: "6",
    dialect: "postgresql",
    tables,
    enums
  };
};
var updateUpToV7 = (json) => {
  const schema6 = pgSchemaV6.parse(json);
  const tables = Object.fromEntries(
    Object.entries(schema6.tables).map((it) => {
      const table6 = it[1];
      const mappedIndexes = Object.fromEntries(
        Object.entries(table6.indexes).map((idx) => {
          const { columns, ...rest } = idx[1];
          const mappedColumns = columns.map((it2) => {
            return {
              expression: it2,
              isExpression: false,
              asc: true,
              nulls: "last",
              opClass: void 0
            };
          });
          return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
        })
      );
      return [it[0], { ...table6, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
    })
  );
  return {
    ...schema6,
    version: "7",
    dialect: "postgresql",
    sequences: {},
    tables,
    policies: {},
    views: {},
    roles: {}
  };
};

// src/cli/commands/singlestoreUp.ts
var upSinglestoreHandler = (out) => {
};

// src/cli/commands/sqliteUp.ts
init_source();
var import_fs10 = require("fs");
init_global();
init_sqliteSchema();
init_utils2();
var upSqliteHandler = (out) => {
  const { snapshots } = prepareOutFolder(out, "sqlite");
  const report = validateWithReport(snapshots, "sqlite");
  report.nonLatest.map((it) => ({
    path: it,
    raw: report.rawMap[it]
  })).forEach((it) => {
    const path4 = it.path;
    const result = updateUpToV62(it.raw);
    console.log(`[${source_default.green("\u2713")}] ${path4}`);
    (0, import_fs10.writeFileSync)(path4, JSON.stringify(result, null, 2));
  });
  console.log("Everything's fine \u{1F436}\u{1F525}");
};
var updateUpToV62 = (json) => {
  const schema6 = sqliteSchemaV5.parse(json);
  const tables = mapEntries(schema6.tables, (tableKey2, table6) => {
    const columns = mapEntries(table6.columns, (key, value) => {
      if (value.default && (typeof value.default === "object" || Array.isArray(value.default))) {
        value.default = `'${JSON.stringify(value.default)}'`;
      }
      return [key, value];
    });
    table6.columns = columns;
    return [tableKey2, table6];
  });
  return {
    ...schema6,
    version: "6",
    dialect: "sqlite",
    tables,
    views: {}
  };
};

// src/cli/schema.ts
init_utils3();
init_utils5();
init_common();
init_outputs();
init_views();
var optionDialect = string("dialect").enum(...dialects).desc(
  `Database dialect: 'gel', 'postgresql', 'mysql', 'sqlite', 'turso' or 'singlestore'`
);
var optionOut = string().desc("Output folder, 'drizzle' by default");
var optionConfig = string().desc("Path to drizzle config file");
var optionBreakpoints = boolean().desc(
  `Prepare SQL statements with breakpoints`
);
var optionDriver = string().enum(...drivers).desc("Database driver");
var optionCasing = string().enum("camelCase", "snake_case").desc("Casing for serialization");
var generate = command2({
  name: "generate",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    driver: optionDriver,
    casing: optionCasing,
    schema: string().desc("Path to a schema file or folder"),
    out: optionOut,
    name: string().desc("Migration file name"),
    breakpoints: optionBreakpoints,
    custom: boolean().desc("Prepare empty migration file for custom SQL").default(false),
    prefix: string().enum(...prefixes).default("index")
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "generate",
      opts,
      ["prefix", "name", "custom"],
      ["driver", "breakpoints", "schema", "out", "dialect", "casing"]
    );
    return prepareGenerateConfig(opts, from);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const {
      prepareAndMigratePg: prepareAndMigratePg2,
      prepareAndMigrateMysql: prepareAndMigrateMysql2,
      prepareAndMigrateSqlite: prepareAndMigrateSqlite2,
      prepareAndMigrateLibSQL: prepareAndMigrateLibSQL2,
      prepareAndMigrateSingleStore: prepareAndMigrateSingleStore2
    } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
    const dialect6 = opts.dialect;
    if (dialect6 === "postgresql") {
      await prepareAndMigratePg2(opts);
    } else if (dialect6 === "mysql") {
      await prepareAndMigrateMysql2(opts);
    } else if (dialect6 === "sqlite") {
      await prepareAndMigrateSqlite2(opts);
    } else if (dialect6 === "turso") {
      await prepareAndMigrateLibSQL2(opts);
    } else if (dialect6 === "singlestore") {
      await prepareAndMigrateSingleStore2(opts);
    } else if (dialect6 === "gel") {
      console.log(
        error(
          `You can't use 'generate' command with Gel dialect`
        )
      );
      process.exit(1);
    } else {
      assertUnreachable(dialect6);
    }
  }
});
var migrate = command2({
  name: "migrate",
  options: {
    config: optionConfig
  },
  transform: async (opts) => {
    return await prepareMigrateConfig(opts.config);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const { dialect: dialect6, schema: schema6, table: table6, out, credentials: credentials2 } = opts;
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await preparePostgresDB2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table6,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "mysql") {
        const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToMySQL2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table6,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "singlestore") {
        const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToSingleStore2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table6,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "sqlite") {
        const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToSQLite2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: opts.out,
            migrationsTable: table6,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "turso") {
        const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToLibSQL2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: opts.out,
            migrationsTable: table6,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "gel") {
        console.log(
          error(
            `You can't use 'migrate' command with Gel dialect`
          )
        );
        process.exit(1);
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e4) {
      console.error(e4);
      process.exit(1);
    }
    process.exit(0);
  }
});
var optionsFilters = {
  tablesFilter: string().desc("Table name filters"),
  schemaFilters: string().desc("Schema name filters"),
  extensionsFilters: string().desc(
    "`Database extensions internal database filters"
  )
};
var optionsDatabaseCredentials = {
  url: string().desc("Database connection URL"),
  host: string().desc("Database host"),
  port: string().desc("Database port"),
  user: string().desc("Database user"),
  password: string().desc("Database password"),
  database: string().desc("Database name"),
  ssl: string().desc("ssl mode"),
  // Turso
  authToken: string("auth-token").desc("Database auth token [Turso]"),
  // gel
  tlsSecurity: string("tlsSecurity").desc("tls security mode"),
  // specific cases
  driver: optionDriver
};
var push = command2({
  name: "push",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    casing: optionCasing,
    schema: string().desc("Path to a schema file or folder"),
    ...optionsFilters,
    ...optionsDatabaseCredentials,
    verbose: boolean().desc("Print all statements for each push").default(false),
    strict: boolean().desc("Always ask for confirmation").default(false),
    force: boolean().desc(
      "Auto-approve all data loss statements. Note: Data loss statements may truncate your tables and data"
    ).default(false)
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "push",
      opts,
      ["force", "verbose", "strict"],
      [
        "schema",
        "dialect",
        "driver",
        "url",
        "host",
        "port",
        "user",
        "password",
        "database",
        "ssl",
        "authToken",
        "schemaFilters",
        "extensionsFilters",
        "tablesFilter",
        "casing",
        "tlsSecurity"
      ]
    );
    return preparePushConfig(opts, from);
  },
  handler: async (config) => {
    await assertPackages("drizzle-orm");
    await assertOrmCoreVersion();
    const {
      dialect: dialect6,
      schemaPath,
      strict,
      verbose,
      credentials: credentials2,
      tablesFilter,
      schemasFilter,
      force,
      casing: casing2,
      entities
    } = config;
    try {
      if (dialect6 === "mysql") {
        const { mysqlPush: mysqlPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await mysqlPush2(
          schemaPath,
          credentials2,
          tablesFilter,
          strict,
          verbose,
          force,
          casing2
        );
      } else if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { pgPush: pgPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await pgPush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          schemasFilter,
          entities,
          force,
          casing2
        );
      } else if (dialect6 === "sqlite") {
        const { sqlitePush: sqlitePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await sqlitePush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          force,
          casing2
        );
      } else if (dialect6 === "turso") {
        const { libSQLPush: libSQLPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await libSQLPush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          force,
          casing2
        );
      } else if (dialect6 === "singlestore") {
        const { singlestorePush: singlestorePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await singlestorePush2(
          schemaPath,
          credentials2,
          tablesFilter,
          strict,
          verbose,
          force,
          casing2
        );
      } else if (dialect6 === "gel") {
        console.log(
          error(
            `You can't use 'push' command with Gel dialect`
          )
        );
        process.exit(1);
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e4) {
      console.error(e4);
    }
    process.exit(0);
  }
});
var check = command2({
  name: "check",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["dialect", "out"]);
    return prepareCheckParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    const { out, dialect: dialect6 } = config;
    checkHandler(out, dialect6);
    console.log("Everything's fine \u{1F436}\u{1F525}");
  }
});
var up = command2({
  name: "up",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["dialect", "out"]);
    return prepareCheckParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    const { out, dialect: dialect6 } = config;
    await assertPackages("drizzle-orm");
    if (dialect6 === "postgresql") {
      upPgHandler(out);
    }
    if (dialect6 === "mysql") {
      upMysqlHandler(out);
    }
    if (dialect6 === "sqlite" || dialect6 === "turso") {
      upSqliteHandler(out);
    }
    if (dialect6 === "singlestore") {
      upSinglestoreHandler(out);
    }
    if (dialect6 === "gel") {
      console.log(
        error(
          `You can't use 'up' command with Gel dialect`
        )
      );
      process.exit(1);
    }
  }
});
var pull = command2({
  name: "introspect",
  aliases: ["pull"],
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut,
    breakpoints: optionBreakpoints,
    casing: string("introspect-casing").enum("camel", "preserve"),
    ...optionsFilters,
    ...optionsDatabaseCredentials
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "introspect",
      opts,
      [],
      [
        "dialect",
        "driver",
        "out",
        "url",
        "host",
        "port",
        "user",
        "password",
        "database",
        "ssl",
        "authToken",
        "casing",
        "breakpoints",
        "tablesFilter",
        "schemaFilters",
        "extensionsFilters",
        "tlsSecurity"
      ]
    );
    return preparePullConfig(opts, from);
  },
  handler: async (config) => {
    await assertPackages("drizzle-orm");
    await assertOrmCoreVersion();
    const {
      dialect: dialect6,
      credentials: credentials2,
      out,
      casing: casing2,
      breakpoints,
      tablesFilter,
      schemasFilter,
      prefix: prefix2,
      entities
    } = config;
    (0, import_fs13.mkdirSync)(out, { recursive: true });
    console.log(
      grey(
        `Pulling from [${schemasFilter.map((it) => `'${it}'`).join(", ")}] list of schemas`
      )
    );
    console.log();
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { introspectPostgres: introspectPostgres2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectPostgres2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          schemasFilter,
          prefix2,
          entities
        );
      } else if (dialect6 === "mysql") {
        const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectMysql2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "sqlite") {
        const { introspectSqlite: introspectSqlite2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectSqlite2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "turso") {
        const { introspectLibSQL: introspectLibSQL2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectLibSQL2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "singlestore") {
        const { introspectSingleStore: introspectSingleStore2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectSingleStore2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "gel") {
        const { introspectGel: introspectGel2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectGel2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          schemasFilter,
          prefix2,
          entities
        );
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e4) {
      console.error(e4);
    }
    process.exit(0);
  }
});
var drop = command2({
  name: "drop",
  options: {
    config: optionConfig,
    out: optionOut,
    driver: optionDriver
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["driver", "out"]);
    return prepareDropParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    assertV1OutFolder(config.out);
    await dropMigration(config);
  }
});
var studio = command2({
  name: "studio",
  options: {
    config: optionConfig,
    port: number().desc("Custom port for drizzle studio [default=4983]"),
    host: string().desc("Custom host for drizzle studio [default=0.0.0.0]"),
    verbose: boolean().default(false).desc("Print all stataments that are executed by Studio")
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    assertStudioNodeVersion();
    const {
      dialect: dialect6,
      schema: schemaPath,
      port,
      host,
      credentials: credentials2
    } = await prepareStudioConfig(opts);
    const {
      drizzleForPostgres: drizzleForPostgres2,
      preparePgSchema: preparePgSchema2,
      prepareMySqlSchema: prepareMySqlSchema2,
      drizzleForMySQL: drizzleForMySQL2,
      prepareSQLiteSchema: prepareSQLiteSchema2,
      drizzleForSQLite: drizzleForSQLite2,
      prepareSingleStoreSchema: prepareSingleStoreSchema2,
      drizzleForSingleStore: drizzleForSingleStore2,
      drizzleForLibSQL: drizzleForLibSQL2
    } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
    let setup;
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { schema: schema6, relations: relations5, files } = schemaPath ? await preparePgSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForPostgres2(credentials2, schema6, relations5, files);
      } else if (dialect6 === "mysql") {
        const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareMySqlSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForMySQL2(credentials2, schema6, relations5, files);
      } else if (dialect6 === "sqlite") {
        const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForSQLite2(credentials2, schema6, relations5, files);
      } else if (dialect6 === "turso") {
        const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForLibSQL2(credentials2, schema6, relations5, files);
      } else if (dialect6 === "singlestore") {
        const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSingleStoreSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForSingleStore2(
          credentials2,
          schema6,
          relations5,
          files
        );
      } else if (dialect6 === "gel") {
        console.log(
          error(
            `You can't use 'studio' command with Gel dialect`
          )
        );
        process.exit(1);
      } else {
        assertUnreachable(dialect6);
      }
      const { prepareServer: prepareServer2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
      const server = await prepareServer2(setup);
      console.log();
      console.log(
        withStyle.fullWarning(
          "Drizzle Studio is currently in Beta. If you find anything that is not working as expected or should be improved, feel free to create an issue on GitHub: https://github.com/drizzle-team/drizzle-kit-mirror/issues/new or write to us on Discord: https://discord.gg/WcRKz2FFxN"
        )
      );
      const { key, cert } = await certs() || {};
      server.start({
        host,
        port,
        key,
        cert,
        cb: (err2, address) => {
          if (err2) {
            console.error(err2);
          } else {
            const queryParams = {};
            if (port !== 4983) {
              queryParams.port = port;
            }
            if (host !== "127.0.0.1") {
              queryParams.host = host;
            }
            const queryString = Object.keys(queryParams).map((key2) => {
              return `${key2}=${queryParams[key2]}`;
            }).join("&");
            console.log(
              `
Drizzle Studio is up and running on ${source_default.blue(
                `https://local.drizzle.studio${queryString ? `?${queryString}` : ""}`
              )}`
            );
          }
        }
      });
    } catch (e4) {
      console.error(e4);
      process.exit(0);
    }
  }
});
var exportRaw = command2({
  name: "export",
  desc: "Generate diff between current state and empty state in specified formats: sql",
  options: {
    sql: boolean("sql").default(true).desc("Generate as sql"),
    config: optionConfig,
    dialect: optionDialect,
    schema: string().desc("Path to a schema file or folder")
  },
  transform: async (opts) => {
    const from = assertCollisions("export", opts, ["sql"], ["dialect", "schema"]);
    return prepareExportConfig(opts, from);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const {
      prepareAndExportPg: prepareAndExportPg2,
      prepareAndExportMysql: prepareAndExportMysql2,
      prepareAndExportSqlite: prepareAndExportSqlite2,
      prepareAndExportLibSQL: prepareAndExportLibSQL2,
      prepareAndExportSinglestore: prepareAndExportSinglestore2
    } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
    const dialect6 = opts.dialect;
    if (dialect6 === "postgresql") {
      await prepareAndExportPg2(opts);
    } else if (dialect6 === "mysql") {
      await prepareAndExportMysql2(opts);
    } else if (dialect6 === "sqlite") {
      await prepareAndExportSqlite2(opts);
    } else if (dialect6 === "turso") {
      await prepareAndExportLibSQL2(opts);
    } else if (dialect6 === "singlestore") {
      await prepareAndExportSinglestore2(opts);
    } else if (dialect6 === "gel") {
      console.log(
        error(
          `You can't use 'export' command with Gel dialect`
        )
      );
      process.exit(1);
    } else {
      assertUnreachable(dialect6);
    }
  }
});

// src/cli/index.ts
init_utils5();
var version2 = async () => {
  const { npmVersion } = await ormCoreVersions();
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
  const envVersion = "0.31.4";
  const kitVersion = envVersion ? `v${envVersion}` : "--";
  const versions = `drizzle-kit: ${kitVersion}
${ormVersion}`;
  console.log(source_default.gray(versions), "\n");
};
var legacyCommand = (name, newName) => {
  return command2({
    name,
    hidden: true,
    handler: () => {
      console.log(
        `This command is deprecated, please use updated '${newName}' command (see https://orm.drizzle.team/kit-docs/upgrade-21#how-to-migrate-to-0210)`
      );
    }
  });
};
var legacy = [
  legacyCommand("generate:pg", "generate"),
  legacyCommand("generate:mysql", "generate"),
  legacyCommand("generate:sqlite", "generate"),
  legacyCommand("push:pg", "push"),
  legacyCommand("push:mysql", "push"),
  legacyCommand("push:sqlite", "push"),
  legacyCommand("introspect:pg", "introspect"),
  legacyCommand("introspect:mysql", "introspect"),
  legacyCommand("introspect:sqlite", "introspect"),
  legacyCommand("up:pg", "up"),
  legacyCommand("up:mysql", "up"),
  legacyCommand("up:sqlite", "up"),
  legacyCommand("check:pg", "check"),
  legacyCommand("check:mysql", "check"),
  legacyCommand("check:sqlite", "check")
];
run([generate, migrate, pull, push, studio, up, check, drop, exportRaw, ...legacy], {
  name: "drizzle-kit",
  version: version2
});
/*! Bundled license information:

web-streams-polyfill/dist/ponyfill.es2018.js:
  (**
   * @license
   * web-streams-polyfill v3.3.3
   * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
   * This code is released under the MIT license.
   * SPDX-License-Identifier: MIT
   *)

fetch-blob/index.js:
  (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

formdata-polyfill/esm.min.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

node-domexception/index.js:
  (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

gel/dist/primitives/chars.js:
gel/dist/primitives/buffer.js:
gel/dist/errors/index.js:
gel/dist/primitives/lru.js:
gel/dist/codecs/consts.js:
gel/dist/codecs/ifaces.js:
gel/dist/codecs/boolean.js:
gel/dist/codecs/numbers.js:
gel/dist/codecs/numerics.js:
gel/dist/codecs/text.js:
gel/dist/codecs/uuid.js:
gel/dist/codecs/bytes.js:
gel/dist/codecs/json.js:
gel/dist/datatypes/datetime.js:
gel/dist/codecs/datetime.js:
gel/dist/datatypes/memory.js:
gel/dist/codecs/memory.js:
gel/dist/codecs/pgvector.js:
gel/dist/codecs/codecs.js:
gel/dist/codecs/tuple.js:
gel/dist/datatypes/range.js:
gel/dist/codecs/range.js:
gel/dist/codecs/namedtuple.js:
gel/dist/codecs/array.js:
gel/dist/codecs/enum.js:
gel/dist/codecs/object.js:
gel/dist/codecs/set.js:
gel/dist/codecs/record.js:
gel/dist/codecs/sparseObject.js:
gel/dist/codecs/registry.js:
gel/dist/retry.js:
gel/dist/conUtils.js:
gel/dist/errors/map.js:
gel/dist/errors/resolve.js:
gel/dist/baseConn.js:
gel/dist/scram.js:
gel/dist/rawConn.js:
gel/dist/index.shared.js:
gel/dist/index.node.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2019-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/datatypes/dateutil.js:
  (*!
   * Portions Copyright (c) 2019 MagicStack Inc. and the Gel authors.
   * Portions Copyright (c) 2001-2019 Python Software Foundation.
   * All rights reserved.
   * Licence: PSFL https://docs.python.org/3/license.html
   *)

gel/dist/utils.js:
gel/dist/ifaces.js:
gel/dist/primitives/queues.js:
gel/dist/baseClient.js:
gel/dist/reflection/strictMap.js:
gel/dist/reflection/index.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2020-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/primitives/event.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2021-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/fetchConn.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2022-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)
*/
