PHP 7.4.33
Preview: api.mjs Size: 1.63 MB
/var/www/gtechmarathon2026.bitkit.dk/httpdocs/node_modules/drizzle-kit/api.mjs
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name2 in all)
    __defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except5, desc2) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except5)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.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);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// ../node_modules/.pnpm/chalk@5.3.0/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 integer3 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer3 >> 16 & 255,
          integer3 >> 8 & 255,
          integer3 & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (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.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
    "use strict";
    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.3.0/node_modules/chalk/source/vendor/supports-color/index.js
import process2 from "process";
import os from "os";
import tty from "tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.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 min2 = forceColor || 0;
  if (env.TERM === "dumb") {
    return min2;
  }
  if (process2.platform === "win32") {
    const osRelease = os.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
      return 3;
    }
    if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min2;
  }
  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 version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 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 min2;
}
function createSupportsColor(stream, options = {}) {
  const level = _supportsColor(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel(level);
}
var env, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
  "../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
    "use strict";
    ({ env } = process2);
    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: tty.isatty(1) }),
      stderr: createSupportsColor({ isTTY: tty.isatty(2) })
    };
    supports_color_default = supportsColor;
  }
});

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

// ../node_modules/.pnpm/chalk@5.3.0/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.3.0/node_modules/chalk/source/index.js"() {
    "use strict";
    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, string) => {
      if (self2.level <= 0 || !string) {
        return self2[IS_EMPTY] ? "" : string;
      }
      let styler = self2[STYLER];
      if (styler === void 0) {
        return string;
      }
      const { openAll, closeAll } = styler;
      if (string.includes("\x1B")) {
        while (styler !== void 0) {
          string = stringReplaceAll(string, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string.indexOf("\n");
      if (lfIndex !== -1) {
        string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
      }
      return openAll + string + closeAll;
    };
    Object.defineProperties(createChalk.prototype, styles2);
    chalk = createChalk();
    chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
    source_default = chalk;
  }
});

// ../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"(exports) {
    "use strict";
    var pathModule = __require("path");
    var isWindows = process.platform === "win32";
    var fs = __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(err) {
        if (err) {
          backtrace.message = err.message;
          err = backtrace;
          missingCallback(err);
        }
      }
      function missingCallback(err) {
        if (err) {
          if (process.throwDeprecation)
            throw err;
          else if (!process.noDeprecation) {
            var msg = "fs: missing callback " + (err.stack || err.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;
    exports.realpathSync = function realpathSync(p, cache) {
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return cache[p];
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m = splitRootRe.exec(p);
        pos = m[0].length;
        current = m[0];
        base = m[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs.lstatSync(base);
          knownHard[base] = true;
        }
      }
      while (pos < p.length) {
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          continue;
        }
        var resolvedLink;
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          resolvedLink = cache[base];
        } else {
          var stat = fs.lstatSync(base);
          if (!stat.isSymbolicLink()) {
            knownHard[base] = true;
            if (cache) cache[base] = base;
            continue;
          }
          var linkTarget = null;
          if (!isWindows) {
            var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
            if (seenLinks.hasOwnProperty(id)) {
              linkTarget = seenLinks[id];
            }
          }
          if (linkTarget === null) {
            fs.statSync(base);
            linkTarget = fs.readlinkSync(base);
          }
          resolvedLink = pathModule.resolve(previous, linkTarget);
          if (cache) cache[base] = resolvedLink;
          if (!isWindows) seenLinks[id] = linkTarget;
        }
        p = pathModule.resolve(resolvedLink, p.slice(pos));
        start();
      }
      if (cache) cache[original] = p;
      return p;
    };
    exports.realpath = function realpath(p, cache, cb) {
      if (typeof cb !== "function") {
        cb = maybeCallback(cache);
        cache = null;
      }
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return process.nextTick(cb.bind(null, null, cache[p]));
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m = splitRootRe.exec(p);
        pos = m[0].length;
        current = m[0];
        base = m[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs.lstat(base, function(err) {
            if (err) return cb(err);
            knownHard[base] = true;
            LOOP();
          });
        } else {
          process.nextTick(LOOP);
        }
      }
      function LOOP() {
        if (pos >= p.length) {
          if (cache) cache[original] = p;
          return cb(null, p);
        }
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          return process.nextTick(LOOP);
        }
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          return gotResolvedLink(cache[base]);
        }
        return fs.lstat(base, gotStat);
      }
      function gotStat(err, stat) {
        if (err) return cb(err);
        if (!stat.isSymbolicLink()) {
          knownHard[base] = true;
          if (cache) cache[base] = base;
          return process.nextTick(LOOP);
        }
        if (!isWindows) {
          var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
          if (seenLinks.hasOwnProperty(id)) {
            return gotTarget(null, seenLinks[id], base);
          }
        }
        fs.stat(base, function(err2) {
          if (err2) return cb(err2);
          fs.readlink(base, function(err3, target) {
            if (!isWindows) seenLinks[id] = target;
            gotTarget(err3, target);
          });
        });
      }
      function gotTarget(err, target, base2) {
        if (err) return cb(err);
        var resolvedLink = pathModule.resolve(previous, target);
        if (cache) cache[base2] = resolvedLink;
        gotResolvedLink(resolvedLink);
      }
      function gotResolvedLink(resolvedLink) {
        p = pathModule.resolve(resolvedLink, p.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"(exports, module) {
    "use strict";
    module.exports = realpath;
    realpath.realpath = realpath;
    realpath.sync = realpathSync;
    realpath.realpathSync = realpathSync;
    realpath.monkeypatch = monkeypatch;
    realpath.unmonkeypatch = unmonkeypatch;
    var fs = __require("fs");
    var origRealpath = fs.realpath;
    var origRealpathSync = fs.realpathSync;
    var version2 = process.version;
    var ok = /^v[0-5]\./.test(version2);
    var old = require_old();
    function newError(er) {
      return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
    }
    function realpath(p, cache, cb) {
      if (ok) {
        return origRealpath(p, cache, cb);
      }
      if (typeof cache === "function") {
        cb = cache;
        cache = null;
      }
      origRealpath(p, cache, function(er, result) {
        if (newError(er)) {
          old.realpath(p, cache, cb);
        } else {
          cb(er, result);
        }
      });
    }
    function realpathSync(p, cache) {
      if (ok) {
        return origRealpathSync(p, cache);
      }
      try {
        return origRealpathSync(p, cache);
      } catch (er) {
        if (newError(er)) {
          return old.realpathSync(p, cache);
        } else {
          throw er;
        }
      }
    }
    function monkeypatch() {
      fs.realpath = realpath;
      fs.realpathSync = realpathSync;
    }
    function unmonkeypatch() {
      fs.realpath = origRealpath;
      fs.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"(exports, module) {
    "use strict";
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module.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"(exports, module) {
    "use strict";
    module.exports = balanced;
    function balanced(a, b, str) {
      if (a instanceof RegExp) a = maybeMatch(a, str);
      if (b instanceof RegExp) b = maybeMatch(b, str);
      var r = range(a, b, str);
      return r && {
        start: r[0],
        end: r[1],
        pre: str.slice(0, r[0]),
        body: str.slice(r[0] + a.length, r[1]),
        post: str.slice(r[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m = str.match(reg);
      return m ? m[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i + 1);
          }
          i = 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"(exports, module) {
    "use strict";
    var balanced = require_balanced_match();
    module.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 numeric3(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 m = balanced("{", "}", str);
      if (!m)
        return str.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      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 lte2(i, y) {
      return i <= y;
    }
    function gte2(i, y) {
      return i >= y;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str);
      if (!m) return [str];
      var pre = m.pre;
      var post = m.post.length ? expand2(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,.*\}/)) {
            str = m.pre + "{" + m.body + escClose + m.post;
            return expand2(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m.body.split(/\.\./);
        } else {
          n = parseCommaParts(m.body);
          if (n.length === 1) {
            n = expand2(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric3(n[0]);
          var y = numeric3(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric3(n[2])) : 1;
          var test = lte2;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte2;
          }
          var pad = n.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i);
              if (c === "\\")
                c = "";
            } else {
              c = String(i);
              if (pad) {
                var need = width - c.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c = "-" + z + c.slice(1);
                  else
                    c = z + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand2(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            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"(exports, module) {
    "use strict";
    var minimatch2 = module.exports = (p, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p);
    };
    module.exports = minimatch2;
    var path2 = require_path();
    minimatch2.sep = path2.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 = (s) => s.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    var reSpecials2 = charSet2("().*{}+?[]^$\\!");
    var addPatternStartSet2 = charSet2("[.(");
    var slashSplit = /\/+/;
    minimatch2.filter = (pattern, options = {}) => (p, i, list) => minimatch2(p, pattern, options);
    var ext2 = (a, b = {}) => {
      const t = {};
      Object.keys(a).forEach((k) => t[k] = a[k]);
      Object.keys(b).forEach((k) => t[k] = b[k]);
      return t;
    };
    minimatch2.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch2;
      }
      const orig = minimatch2;
      const m = (p, pattern, options) => orig(p, pattern, ext2(def, options));
      m.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m.defaults = (options) => orig.defaults(ext2(def, options));
      m.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m;
    };
    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((f) => mm.match(f));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape2 = (s) => s.replace(/\\(.)/g, "$1");
    var charUnescape = (s) => s.replace(/\\([^-\]])/g, "$1");
    var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s) => s.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((s) => s.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s, si, set2) => s.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s) => s.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 i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          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 p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false) return false;
          if (p === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            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 p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = f.match(p);
            this.debug("pattern match", p, f, 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 = (p) => p.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 i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
          this.debug("%s	%s %s %j", pattern, i, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials2[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i + 1) === "-") {
                re += c;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
              if (inClass) {
                this.debug("  in class");
                if (c === "!" && i === classStart + 1) c = "^";
                re += c;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext) clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i - 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(i + 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(i + 1));
              }
              continue;
            }
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c;
                continue;
              }
              inClass = true;
              classStart = i;
              reClassStart = re.length;
              re += c;
              continue;
            case "]":
              if (i === classStart + 1 || !inClass) {
                re += "\\" + c;
                continue;
              }
              cs = pattern.substring(classStart + 1, i);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c] && !(c === "^" && inClass)) {
                re += "\\";
              }
              re += c;
              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, (_2, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet2[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          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 i = 0; i < openParensBefore; i++) {
            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(
            (p) => typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR2 ? GLOBSTAR2 : p._src
          ).reduce((set2, p) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p === GLOBSTAR2)) {
              set2.push(p);
            }
            return set2;
          }, []);
          pattern.forEach((p, i) => {
            if (p !== GLOBSTAR2 || pattern[i - 1] === GLOBSTAR2) {
              return;
            }
            if (i === 0) {
              if (pattern.length > 1) {
                pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1];
              } else {
                pattern[i] = twoStar;
              }
            } else if (i === pattern.length - 1) {
              pattern[i - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1];
              pattern[i + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p) => p !== 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(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment) return false;
        if (this.empty) return f === "";
        if (f === "/" && partial) return true;
        const options = this.options;
        if (path2.sep !== "/") {
          f = f.split(path2.sep).join("/");
        }
        f = f.split(slashSplit);
        this.debug(this.pattern, "split", f);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i = f.length - 1; i >= 0; i--) {
          filename = f[i];
          if (filename) break;
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = f;
          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"(exports, module) {
    "use strict";
    if (typeof Object.create === "function") {
      module.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 {
      module.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"(exports, module) {
    "use strict";
    try {
      util2 = __require("util");
      if (typeof util2.inherits !== "function") throw "";
      module.exports = util2.inherits;
    } catch (e) {
      module.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"(exports) {
    "use strict";
    exports.setopts = setopts;
    exports.ownProp = ownProp;
    exports.makeAbs = makeAbs;
    exports.finish = finish;
    exports.mark = mark;
    exports.isIgnored = isIgnored;
    exports.childrenIgnored = childrenIgnored;
    function ownProp(obj, field) {
      return Object.prototype.hasOwnProperty.call(obj, field);
    }
    var fs = __require("fs");
    var path2 = __require("path");
    var minimatch2 = require_minimatch();
    var isAbsolute = __require("path").isAbsolute;
    var Minimatch2 = minimatch2.Minimatch;
    function alphasort(a, b) {
      return a.localeCompare(b, "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 || fs;
      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 = path2.resolve(cwd);
      else {
        self2.cwd = path2.resolve(options.cwd);
        self2.changedCwd = self2.cwd !== cwd;
      }
      self2.root = options.root || path2.resolve(self2.cwd, "/");
      self2.root = path2.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 i = 0, l = self2.matches.length; i < l; i++) {
        var matches = self2.matches[i];
        if (!matches || Object.keys(matches).length === 0) {
          if (self2.nonull) {
            var literal = self2.minimatch.globSet[i];
            if (nou)
              all.push(literal);
            else
              all[literal] = true;
          }
        } else {
          var m = Object.keys(matches);
          if (nou)
            all.push.apply(all, m);
          else
            m.forEach(function(m2) {
              all[m2] = true;
            });
        }
      }
      if (!nou)
        all = Object.keys(all);
      if (!self2.nosort)
        all = all.sort(alphasort);
      if (self2.mark) {
        for (var i = 0; i < all.length; i++) {
          all[i] = self2._mark(all[i]);
        }
        if (self2.nodir) {
          all = all.filter(function(e) {
            var notDir = !/\/$/.test(e);
            var c = self2.cache[e] || self2.cache[makeAbs(self2, e)];
            if (notDir && c)
              notDir = c !== "DIR" && !Array.isArray(c);
            return notDir;
          });
        }
      }
      if (self2.ignore.length)
        all = all.filter(function(m2) {
          return !isIgnored(self2, m2);
        });
      self2.found = all;
    }
    function mark(self2, p) {
      var abs = makeAbs(self2, p);
      var c = self2.cache[abs];
      var m = p;
      if (c) {
        var isDir = c === "DIR" || Array.isArray(c);
        var slash = p.slice(-1) === "/";
        if (isDir && !slash)
          m += "/";
        else if (!isDir && slash)
          m = m.slice(0, -1);
        if (m !== p) {
          var mabs = makeAbs(self2, m);
          self2.statCache[mabs] = self2.statCache[abs];
          self2.cache[mabs] = self2.cache[abs];
        }
      }
      return m;
    }
    function makeAbs(self2, f) {
      var abs = f;
      if (f.charAt(0) === "/") {
        abs = path2.join(self2.root, f);
      } else if (isAbsolute(f) || f === "") {
        abs = f;
      } else if (self2.changedCwd) {
        abs = path2.resolve(self2.cwd, f);
      } else {
        abs = path2.resolve(f);
      }
      if (process.platform === "win32")
        abs = abs.replace(/\\/g, "/");
      return abs;
    }
    function isIgnored(self2, path3) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return item.matcher.match(path3) || !!(item.gmatcher && item.gmatcher.match(path3));
      });
    }
    function childrenIgnored(self2, path3) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return !!(item.gmatcher && item.gmatcher.match(path3));
      });
    }
  }
});

// ../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"(exports, module) {
    "use strict";
    module.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 path2 = __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 n = this.minimatch.set.length;
      this.matches = new Array(n);
      for (var i = 0; i < n; i++) {
        this._process(this.minimatch.set[i], i, false);
      }
      this._finish();
    }
    GlobSync.prototype._finish = function() {
      assert.ok(this instanceof GlobSync);
      if (this.realpath) {
        var self2 = this;
        this.matches.forEach(function(matchset, index5) {
          var set = self2.matches[index5] = /* @__PURE__ */ Object.create(null);
          for (var p in matchset) {
            try {
              p = self2._makeAbs(p);
              var real5 = rp.realpathSync(p, self2.realpathCache);
              set[real5] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index5, inGlobStar) {
      assert.ok(this instanceof GlobSync);
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        case pattern.length:
          this._processSimple(pattern.join("/"), index5);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).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, index5, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index5, 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 i = 0; i < entries.length; i++) {
        var e = entries[i];
        if (e.charAt(0) !== "." || dotOk) {
          var m;
          if (negate && !prefix2) {
            m = !e.match(pn);
          } else {
            m = e.match(pn);
          }
          if (m)
            matchedEntries.push(e);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return;
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index5])
          this.matches[index5] = /* @__PURE__ */ Object.create(null);
        for (var i = 0; i < len; i++) {
          var e = matchedEntries[i];
          if (prefix2) {
            if (prefix2.slice(-1) !== "/")
              e = prefix2 + "/" + e;
            else
              e = prefix2 + e;
          }
          if (e.charAt(0) === "/" && !this.nomount) {
            e = path2.join(this.root, e);
          }
          this._emitMatch(index5, e);
        }
        return;
      }
      remain.shift();
      for (var i = 0; i < len; i++) {
        var e = matchedEntries[i];
        var newPattern;
        if (prefix2)
          newPattern = [prefix2, e];
        else
          newPattern = [e];
        this._process(newPattern.concat(remain), index5, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index5, e) {
      if (isIgnored(this, e))
        return;
      var abs = this._makeAbs(e);
      if (this.mark)
        e = this._mark(e);
      if (this.absolute) {
        e = abs;
      }
      if (this.matches[index5][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index5][e] = true;
      if (this.stat)
        this._stat(e);
    };
    GlobSync.prototype._readdirInGlobStar = function(abs) {
      if (this.follow)
        return this._readdir(abs, false);
      var entries;
      var lstat;
      var stat;
      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 c = this.cache[abs];
        if (!c || c === "FILE")
          return null;
        if (Array.isArray(c))
          return c;
      }
      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 i = 0; i < entries.length; i++) {
          var e = entries[i];
          if (abs === "/")
            e = abs + e;
          else
            e = abs + "/" + e;
          this.cache[e] = true;
        }
      }
      this.cache[abs] = entries;
      return entries;
    };
    GlobSync.prototype._readdirError = function(f, er) {
      switch (er.code) {
        case "ENOTSUP":
        case "ENOTDIR":
          var abs = this._makeAbs(f);
          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":
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f)] = false;
          break;
        default:
          this.cache[this._makeAbs(f)] = false;
          if (this.strict)
            throw er;
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
    };
    GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index5, 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, index5, false);
      var len = entries.length;
      var isSym = this.symlinks[abs];
      if (isSym && inGlobStar)
        return;
      for (var i = 0; i < len; i++) {
        var e = entries[i];
        if (e.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i], remainWithoutGlobStar);
        this._process(instead, index5, true);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index5, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index5) {
      var exists2 = this._stat(prefix2);
      if (!this.matches[index5])
        this.matches[index5] = /* @__PURE__ */ Object.create(null);
      if (!exists2)
        return;
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path2.join(this.root, prefix2);
        } else {
          prefix2 = path2.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index5, prefix2);
    };
    GlobSync.prototype._stat = function(f) {
      var abs = this._makeAbs(f);
      var needDir = f.slice(-1) === "/";
      if (f.length > this.maxLength)
        return false;
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return c;
        if (needDir && c === "FILE")
          return false;
      }
      var exists2;
      var stat = this.statCache[abs];
      if (!stat) {
        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 {
            stat = this.fs.statSync(abs);
          } catch (er) {
            stat = lstat;
          }
        } else {
          stat = lstat;
        }
      }
      this.statCache[abs] = stat;
      var c = true;
      if (stat)
        c = stat.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return false;
      return c;
    };
    GlobSync.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    GlobSync.prototype._makeAbs = function(f) {
      return common.makeAbs(this, f);
    };
  }
});

// ../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"(exports, module) {
    "use strict";
    module.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

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

// ../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"(exports, module) {
    "use strict";
    var wrappy = require_wrappy();
    var reqs = /* @__PURE__ */ Object.create(null);
    var once = require_once();
    module.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 i = 0; i < len; i++) {
            cbs[i].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 i = 0; i < length; i++) array2[i] = args[i];
      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"(exports, module) {
    "use strict";
    module.exports = glob2;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var inherits = require_inherits();
    var EE = __require("events").EventEmitter;
    var path2 = __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 i = keys.length;
      while (i--) {
        origin[keys[i]] = add[keys[i]];
      }
      return origin;
    }
    glob2.hasMagic = function(pattern, options_) {
      var options = extend({}, options_);
      options.noprocess = true;
      var g = new Glob(pattern, options);
      var set = g.minimatch.set;
      if (!pattern)
        return false;
      if (set.length > 1)
        return true;
      for (var j = 0; j < set[0].length; j++) {
        if (typeof set[0][j] !== "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 n = this.minimatch.set.length;
      this.matches = new Array(n);
      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 (n === 0)
        return done();
      var sync2 = true;
      for (var i = 0; i < n; i++) {
        this._process(this.minimatch.set[i], i, 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 n = this.matches.length;
      if (n === 0)
        return this._finish();
      var self2 = this;
      for (var i = 0; i < this.matches.length; i++)
        this._realpathSet(i, next);
      function next() {
        if (--n === 0)
          self2._finish();
      }
    };
    Glob.prototype._realpathSet = function(index5, cb) {
      var matchset = this.matches[index5];
      if (!matchset)
        return cb();
      var found = Object.keys(matchset);
      var self2 = this;
      var n = found.length;
      if (n === 0)
        return cb();
      var set = this.matches[index5] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p, i) {
        p = self2._makeAbs(p);
        rp.realpath(p, self2.realpathCache, function(er, real5) {
          if (!er)
            set[real5] = true;
          else if (er.syscall === "stat")
            set[p] = true;
          else
            self2.emit("error", er);
          if (--n === 0) {
            self2.matches[index5] = set;
            cb();
          }
        });
      });
    };
    Glob.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    Glob.prototype._makeAbs = function(f) {
      return common.makeAbs(this, f);
    };
    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 eq2 = this._emitQueue.slice(0);
          this._emitQueue.length = 0;
          for (var i = 0; i < eq2.length; i++) {
            var e = eq2[i];
            this._emitMatch(e[0], e[1]);
          }
        }
        if (this._processQueue.length) {
          var pq = this._processQueue.slice(0);
          this._processQueue.length = 0;
          for (var i = 0; i < pq.length; i++) {
            var p = pq[i];
            this._processing--;
            this._process(p[0], p[1], p[2], p[3]);
          }
        }
      }
    };
    Glob.prototype._process = function(pattern, index5, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index5, inGlobStar, cb]);
        return;
      }
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        case pattern.length:
          this._processSimple(pattern.join("/"), index5, cb);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).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, index5, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index5, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index5, 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 i = 0; i < entries.length; i++) {
        var e = entries[i];
        if (e.charAt(0) !== "." || dotOk) {
          var m;
          if (negate && !prefix2) {
            m = !e.match(pn);
          } else {
            m = e.match(pn);
          }
          if (m)
            matchedEntries.push(e);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return cb();
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index5])
          this.matches[index5] = /* @__PURE__ */ Object.create(null);
        for (var i = 0; i < len; i++) {
          var e = matchedEntries[i];
          if (prefix2) {
            if (prefix2 !== "/")
              e = prefix2 + "/" + e;
            else
              e = prefix2 + e;
          }
          if (e.charAt(0) === "/" && !this.nomount) {
            e = path2.join(this.root, e);
          }
          this._emitMatch(index5, e);
        }
        return cb();
      }
      remain.shift();
      for (var i = 0; i < len; i++) {
        var e = matchedEntries[i];
        var newPattern;
        if (prefix2) {
          if (prefix2 !== "/")
            e = prefix2 + "/" + e;
          else
            e = prefix2 + e;
        }
        this._process([e].concat(remain), index5, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index5, e) {
      if (this.aborted)
        return;
      if (isIgnored(this, e))
        return;
      if (this.paused) {
        this._emitQueue.push([index5, e]);
        return;
      }
      var abs = isAbsolute(e) ? e : this._makeAbs(e);
      if (this.mark)
        e = this._mark(e);
      if (this.absolute)
        e = abs;
      if (this.matches[index5][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index5][e] = true;
      var st = this.statCache[abs];
      if (st)
        this.emit("stat", e, st);
      this.emit("match", e);
    };
    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 c = this.cache[abs];
        if (!c || c === "FILE")
          return cb();
        if (Array.isArray(c))
          return cb(null, c);
      }
      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 i = 0; i < entries.length; i++) {
          var e = entries[i];
          if (abs === "/")
            e = abs + e;
          else
            e = abs + "/" + e;
          this.cache[e] = true;
        }
      }
      this.cache[abs] = entries;
      return cb(null, entries);
    };
    Glob.prototype._readdirError = function(f, er, cb) {
      if (this.aborted)
        return;
      switch (er.code) {
        case "ENOTSUP":
        case "ENOTDIR":
          var abs = this._makeAbs(f);
          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":
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f)] = false;
          break;
        default:
          this.cache[this._makeAbs(f)] = 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, index5, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index5, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index5, false, cb);
      var isSym = this.symlinks[abs];
      var len = entries.length;
      if (isSym && inGlobStar)
        return cb();
      for (var i = 0; i < len; i++) {
        var e = entries[i];
        if (e.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i], remainWithoutGlobStar);
        this._process(instead, index5, true, cb);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index5, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index5, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists2) {
        self2._processSimple2(prefix2, index5, er, exists2, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index5, er, exists2, cb) {
      if (!this.matches[index5])
        this.matches[index5] = /* @__PURE__ */ Object.create(null);
      if (!exists2)
        return cb();
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path2.join(this.root, prefix2);
        } else {
          prefix2 = path2.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index5, prefix2);
      cb();
    };
    Glob.prototype._stat = function(f, cb) {
      var abs = this._makeAbs(f);
      var needDir = f.slice(-1) === "/";
      if (f.length > this.maxLength)
        return cb();
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return cb(null, c);
        if (needDir && c === "FILE")
          return cb();
      }
      var exists2;
      var stat = this.statCache[abs];
      if (stat !== void 0) {
        if (stat === false)
          return cb(null, stat);
        else {
          var type = stat.isDirectory() ? "DIR" : "FILE";
          if (needDir && type === "FILE")
            return cb();
          else
            return cb(null, type, stat);
        }
      }
      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, stat2) {
            if (er2)
              self2._stat2(f, abs, null, lstat, cb);
            else
              self2._stat2(f, abs, er2, stat2, cb);
          });
        } else {
          self2._stat2(f, abs, er, lstat, cb);
        }
      }
    };
    Glob.prototype._stat2 = function(f, abs, er, stat, cb) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return cb();
      }
      var needDir = f.slice(-1) === "/";
      this.statCache[abs] = stat;
      if (abs.slice(-1) === "/" && stat && !stat.isDirectory())
        return cb(null, false, stat);
      var c = true;
      if (stat)
        c = stat.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return cb();
      return cb(null, c, stat);
    };
  }
});

// ../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"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.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
      };
    };
    exports.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"(exports, module) {
    "use strict";
    var ESC = "\x1B";
    var CSI = `${ESC}[`;
    var beep = "\x07";
    var cursor = {
      to(x, y) {
        if (!y) return `${CSI}${x + 1}G`;
        return `${CSI}${y + 1};${x + 1}H`;
      },
      move(x, y) {
        let ret = "";
        if (x < 0) ret += `${CSI}${-x}D`;
        else if (x > 0) ret += `${CSI}${x}C`;
        if (y < 0) ret += `${CSI}${-y}A`;
        else if (y > 0) ret += `${CSI}${y}B`;
        return ret;
      },
      up: (count2 = 1) => `${CSI}${count2}A`,
      down: (count2 = 1) => `${CSI}${count2}B`,
      forward: (count2 = 1) => `${CSI}${count2}C`,
      backward: (count2 = 1) => `${CSI}${count2}D`,
      nextLine: (count2 = 1) => `${CSI}E`.repeat(count2),
      prevLine: (count2 = 1) => `${CSI}F`.repeat(count2),
      left: `${CSI}G`,
      hide: `${CSI}?25l`,
      show: `${CSI}?25h`,
      save: `${ESC}7`,
      restore: `${ESC}8`
    };
    var scroll = {
      up: (count2 = 1) => `${CSI}S`.repeat(count2),
      down: (count2 = 1) => `${CSI}T`.repeat(count2)
    };
    var erase = {
      screen: `${CSI}2J`,
      up: (count2 = 1) => `${CSI}1J`.repeat(count2),
      down: (count2 = 1) => `${CSI}J`.repeat(count2),
      line: `${CSI}2K`,
      lineEnd: `${CSI}K`,
      lineStart: `${CSI}1K`,
      lines(count2) {
        let clear = "";
        for (let i = 0; i < count2; i++)
          clear += this.line + (i < count2 - 1 ? cursor.up() : "");
        if (count2)
          clear += cursor.left;
        return clear;
      }
    };
    module.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"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.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 line2 of lines) {
        rows += 1 + Math.floor(Math.max(stringWidth(line2) - 1, 0) / perLine);
      }
      return sisteransi_1.erase.lines(rows);
    };
    exports.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"(exports, module) {
    "use strict";
    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(time4) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time4;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time4) {
        lastInvokeTime = time4;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time4) : result;
      }
      function remainingWait(time4) {
        var timeSinceLastCall = time4 - lastCallTime, timeSinceLastInvoke = time4 - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time4) {
        var timeSinceLastCall = time4 - lastCallTime, timeSinceLastInvoke = time4 - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time4 = now();
        if (shouldInvoke(time4)) {
          return trailingEdge(time4);
        }
        timerId = setTimeout(timerExpired, remainingWait(time4));
      }
      function trailingEdge(time4) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time4);
        }
        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 time4 = now(), isInvoking = shouldInvoke(time4);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time4;
        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;
    }
    module.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"(exports) {
    "use strict";
    var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.onTerminate = exports.renderWithTask = exports.render = exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
    var readline_1 = require_readline();
    var sisteransi_1 = require_src();
    var utils_1 = require_utils();
    var lodash_throttle_1 = __importDefault(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));
      }
    };
    exports.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;
      }
    };
    exports.SelectState = SelectState3;
    var deferred = () => {
      let resolve;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
      });
      return {
        resolve,
        reject,
        promise
      };
    };
    exports.deferred = deferred;
    var Terminal = class {
      constructor(view4, stdin, stdout, closable) {
        this.view = view4;
        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;
          }
          view4.input(str, key);
        };
        this.stdin.on("keypress", keypress);
        this.view.attach(this);
        const { resolve, promise } = (0, exports.deferred)();
        this.resolve = resolve;
        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(state) {
        if (state === "hide") {
          this.stdout.write(sisteransi_1.cursor.hide);
        } else {
          this.stdout.write(sisteransi_1.cursor.show);
        }
      }
      requestLayout() {
        const string = this.view.render(this.status);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.renderFunc(`${clearPrefix}${string}`);
      }
    };
    exports.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);
        }
      }
    };
    exports.TaskView = TaskView2;
    var TaskTerminal = class {
      constructor(view4, stdout) {
        this.view = view4;
        this.stdout = stdout;
        this.text = "";
        this.view.attach(this);
      }
      requestLayout() {
        const string = this.view.render("pending");
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.stdout.write(`${clearPrefix}${string}`);
      }
      clear() {
        const string = 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}${string}`);
      }
    };
    exports.TaskTerminal = TaskTerminal;
    function render7(view4) {
      const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
      if (view4 instanceof Prompt3) {
        const terminal = new Terminal(view4, stdin, stdout, closable);
        terminal.requestLayout();
        return terminal.result();
      }
      stdout.write(`${view4}
`);
      closable.close();
      return;
    }
    exports.render = render7;
    function renderWithTask5(view4, task) {
      return __awaiter(this, void 0, void 0, function* () {
        const terminal = new TaskTerminal(view4, process.stdout);
        terminal.requestLayout();
        const result = yield task;
        terminal.clear();
        return result;
      });
    }
    exports.renderWithTask = renderWithTask5;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports.onTerminate = onTerminate;
  }
});

// src/global.ts
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, map) => {
      const result = Object.keys(obj).reduce(function(result2, key) {
        result2[key] = map(obj[key]);
        return result2;
      }, {});
      return result;
    };
    mapKeys = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const newKey = map(key, val);
          return [newKey, val];
        })
      );
      return result;
    };
    mapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const [newKey, newVal] = map(key, val);
          return [newKey, newVal];
        })
      );
      return result;
    };
    customMapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const [newKey, newVal] = map(key, val);
          return [newKey, newVal];
        })
      );
      return result;
    };
  }
});

// ../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs
function getErrorMap() {
  return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
function 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) => {
    var _a415, _b305;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a415 = message !== null && message !== void 0 ? message : required_error) !== null && _a415 !== void 0 ? _a415 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b305 = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b305 !== void 0 ? _b305 : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex = `${regex}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex = `${regex}(\\.\\d+)?`;
  }
  return regex;
}
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, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
function deepPartialify(schema5) {
  if (schema5 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema5.shape) {
      const fieldSchema = schema5.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema5._def,
      shape: () => newShape
    });
  } else if (schema5 instanceof ZodArray) {
    return new ZodArray({
      ...schema5._def,
      type: deepPartialify(schema5.element)
    });
  } else if (schema5 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema5.unwrap()));
  } else if (schema5 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema5.unwrap()));
  } else if (schema5 instanceof ZodTuple) {
    return ZodTuple.create(schema5.items.map((item) => deepPartialify(item)));
  } else {
    return schema5;
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index5 = 0; index5 < a.length; index5++) {
      const itemA = a[index5];
      const itemB = b[index5];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, ZodError, errorMap, overrideErrorMap, makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv6Regex, base64Regex, 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, 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, coerce;
var init_lib = __esm({
  "../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs"() {
    "use strict";
    (function(util2) {
      util2.assertEqual = (val) => val;
      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((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e) {
          return obj[e];
        });
      };
      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" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
      function joinValues(array2, separator = " | ") {
        return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_2, 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 t = typeof data;
      switch (t) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return 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;
      }
    };
    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"
    ]);
    ZodError = class _ZodError extends Error {
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      get errors() {
        return this.issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (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 i = 0;
              while (i < issue.path.length) {
                const el = issue.path[i];
                const terminal = i === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, 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;
    };
    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 };
    };
    overrideErrorMap = errorMap;
    makeIssue = (params) => {
      const { data, path: path2, errorMaps, issueData } = params;
      const fullPath = [...path2, ...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((m) => !!m).slice().reverse();
      for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    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 s of results) {
          if (s.status === "aborted")
            return INVALID;
          if (s.status === "dirty")
            status.dirty();
          arrayValue.push(s.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 = (x) => x.status === "aborted";
    isDirty = (x) => x.status === "dirty";
    isValid = (x) => x.status === "valid";
    isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
    })(errorUtil || (errorUtil = {}));
    ParseInputLazyPath = class {
      constructor(parent, value, path2, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path2;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (this._key instanceof Array) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    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 {
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
      }
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        var _a415;
        const ctx = {
          common: {
            issues: [],
            async: (_a415 = params === null || params === void 0 ? void 0 : params.async) !== null && _a415 !== void 0 ? _a415 : false,
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      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 || params === void 0 ? void 0 : params.errorMap,
            async: true
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          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(check, message) {
        const getIssueProperties = (val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        };
        return this._refinement((val, ctx) => {
          const result = check(val);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          });
          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(check, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this, this._def);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
    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;
    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])$/;
    ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
    base64Regex = /^([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 check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.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: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch (_a415) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex = datetimeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex = timeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        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(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      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) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        var _a415, _b305;
        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 || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          offset: (_a415 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a415 !== void 0 ? _a415 : false,
          local: (_b305 = options === null || options === void 0 ? void 0 : options.local) !== null && _b305 !== void 0 ? _b305 : false,
          ...errorUtil.errToObj(options === null || options === void 0 ? 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 || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          ...errorUtil.errToObj(options === null || options === void 0 ? 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 || options === void 0 ? void 0 : options.position,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * @deprecated Use z.string().min(1) instead.
       * @see {@link ZodString.min}
       */
      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 isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get minLength() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxLength() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodString.create = (params) => {
      var _a415;
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a415 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a415 !== void 0 ? _a415 : 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 check of this._def.checks) {
          if (check.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        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(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max2 = null, min2 = 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 (min2 === null || ch.value > min2)
              min2 = ch.value;
          } else if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return Number.isFinite(min2) && Number.isFinite(max2);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params === null || params === void 0 ? 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) {
          input.data = BigInt(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.bigint,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        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 _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodBigInt.create = (params) => {
      var _a415;
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a415 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a415 !== void 0 ? _a415 : 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 || params === void 0 ? 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 (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 check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2 != null ? new Date(min2) : null;
      }
      get maxDate() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2 != null ? new Date(max2) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? 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, i) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        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 = (schema5, params) => {
      return new ZodArray({
        type: schema5,
        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);
        return this._cached = { shape, keys };
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, 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 _a415, _b305, _c14, _d6;
              const defaultError = (_c14 = (_b305 = (_a415 = this._def).errorMap) === null || _b305 === void 0 ? void 0 : _b305.call(_a415, issue, ctx).message) !== null && _c14 !== void 0 ? _c14 : ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: (_d6 = errorUtil.errToObj(message).message) !== null && _d6 !== void 0 ? _d6 : 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, schema5) {
        return this.augment({ [key]: schema5 });
      }
      // 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(index5) {
        return new _ZodObject({
          ...this._def,
          catchall: index5
        });
      }
      pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => 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 = (types, params) => {
      return new ZodUnion({
        options: types,
        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 schema5 = this._def.items[itemIndex] || this._def.rest;
          if (!schema5)
            return null;
          return schema5._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x) => !!x);
        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], index5) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index5, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index5, "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, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    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(),
              errorMap
            ].filter((x) => !!x),
            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(),
              errorMap
            ].filter((x) => !!x),
            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((e) => {
              error2.addIssue(makeArgsIssue(args, e));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
              error2.addIssue(makeReturnsIssue(result, e));
              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 {
      constructor() {
        super(...arguments);
        _ZodEnum_cache.set(this, void 0);
      }
      _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 (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").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 val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _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_cache = /* @__PURE__ */ new WeakMap();
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      constructor() {
        super(...arguments);
        _ZodNativeEnum_cache.set(this, void 0);
      }
      _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 (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").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_cache = /* @__PURE__ */ new WeakMap();
    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 = (schema5, params) => {
      return new ZodPromise({
        type: schema5,
        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 base;
            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 base;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema5, effect, params) => {
      return new ZodEffects({
        schema: schema5,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema5, params) => {
      return new ZodEffects({
        schema: schema5,
        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(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          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 = {}));
    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;
    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 })
    };
  }
});

// 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_lib();
    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 [name2, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name: name2,
          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 [name2, columns] = unq.split(";");
        return { name: name2, columns: columns.split(",") };
      },
      squashFK: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk.parse({
          name: name2,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashCheck: (input) => {
        return `${input.name};${input.value}`;
      },
      unsquashCheck: (input) => {
        const [name2, value] = input.split(";");
        return { name: name2, value };
      },
      squashView: (view4) => {
        return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
      },
      unsquashView: (meta) => {
        const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
        const toReturn = {
          algorithm,
          sqlSecurity,
          withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
        };
        return viewMeta.parse(toReturn);
      }
    };
    squashMysqlScheme = (json4) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index5) => {
            return MySqlSquasher.squashIdx(index5);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
            return MySqlSquasher.squashFK(fk4);
          });
          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, (check) => {
            return MySqlSquasher.squashCheck(check);
          });
          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(json4.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: json4.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_lib();
    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(
          (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass ? c.opclass : ""}`
        ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
      },
      unsquashIdx: (input) => {
        const [
          name2,
          columnsString,
          isUnique,
          concurrently,
          method,
          where,
          idxWith
        ] = input.split(";");
        const columnString = columnsString.split(",,");
        const columns = [];
        for (const column5 of columnString) {
          const [expression, isExpression, asc2, nulls, opclass] = column5.split("--");
          columns.push({
            nulls,
            isExpression: isExpression === "true",
            asc: asc2 === "true",
            expression,
            opclass: opclass === "undefined" ? void 0 : opclass
          });
        }
        const result = index2.parse({
          name: name2,
          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((c) => `${c.isExpression ? "" : c.expression}--${c.asc}--${c.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
      },
      unsquashIdxPush: (input) => {
        const [name2, columnsString, isUnique, method, idxWith] = input.split(";");
        const columnString = columnsString.split("--");
        const columns = [];
        for (const column5 of columnString) {
          const [expression, asc2, nulls, opclass] = column5.split(",");
          columns.push({
            nulls,
            isExpression: expression === "",
            asc: asc2 === "true",
            expression
          });
        }
        const result = index2.parse({
          name: name2,
          columns,
          isUnique: isUnique === "true",
          concurrently: false,
          method,
          with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashFK: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
      },
      squashPolicy: (policy4) => {
        return `${policy4.name}--${policy4.as}--${policy4.for}--${policy4.to?.join(",")}--${policy4.using}--${policy4.withCheck}--${policy4.on}`;
      },
      unsquashPolicy: (policy4) => {
        const splitted = policy4.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: (policy4) => {
        return `${policy4.name}--${policy4.as}--${policy4.for}--${policy4.to?.join(",")}--${policy4.on}`;
      },
      unsquashPolicyPush: (policy4) => {
        const splitted = policy4.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 [name2, columns, nullsNotDistinct] = unq.split(";");
        return {
          name: name2,
          columns: columns.split(","),
          nullsNotDistinct: nullsNotDistinct === "true"
        };
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete,
          schemaTo
        ] = input.split(";");
        const result = fk2.parse({
          name: name2,
          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: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name2,
          value
        ] = input.split(";");
        return { name: name2, value };
      }
    };
    squashPgScheme = (json4, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index5) => {
            return action === "push" ? PgSquasher.squashIdxPush(index5) : PgSquasher.squashIdx(index5);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
            return PgSquasher.squashFK(fk4);
          });
          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, (policy4) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy4) : PgSquasher.squashPolicy(policy4);
          });
          const squashedChecksContraints = mapValues(
            it[1].checkConstraints,
            (check) => {
              return PgSquasher.squashCheck(check);
            }
          );
          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(json4.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(json4.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: json4.dialect,
        tables: mappedTables,
        enums: json4.enums,
        schemas: json4.schemas,
        views: json4.views,
        policies: mappedPolicies,
        sequences: mappedSequences,
        roles: json4.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_lib();
    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 [name2, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name: name2,
          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 [name2, columns] = unq.split(";");
        return { name: name2, 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 = (json4) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index5) => {
            return SingleStoreSquasher.squashIdx(index5);
          });
          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: json4.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_lib();
    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 [name2, columnsString, isUnique, where] = input.split(";");
        const result = index4.parse({
          name: name2,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          where: where ?? void 0
        });
        return result;
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name2, columns] = unq.split(";");
        return { name: name2, columns: columns.split(",") };
      },
      squashFK: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk3.parse({
          name: name2,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPushFK: (fk4) => {
        return `${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.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: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name2,
          value
        ] = input.split(";");
        return { name: name2, value };
      }
    };
    squashSqliteScheme = (json4, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index5) => {
            return SQLiteSquasher.squashIdx(index5);
          });
          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,
            (check) => {
              return SQLiteSquasher.squashCheck(check);
            }
          );
          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: json4.dialect,
        tables: mappedTables,
        views: json4.views,
        enums: json4.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/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, "''");
}
var copy, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey;
var init_utils = __esm({
  "src/utils.ts"() {
    "use strict";
    init_views();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    copy = (it) => {
      return JSON.parse(JSON.stringify(it));
    };
    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 = (table5, schema5, column5) => {
      const out = schema5 ? `"${schema5}"."${table5}"."${column5}"` : `"${table5}"."${column5}"`;
      return out;
    };
  }
});

// src/cli/views.ts
var import_hanji, warning, error, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, ProgressView;
var init_views = __esm({
  "src/cli/views.ts"() {
    "use strict";
    init_source();
    import_hanji = __toESM(require_hanji());
    init_utils();
    warning = (msg) => {
      (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
    };
    error = (error2, greyMsg = "") => {
      return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    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 text5 = `
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((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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")}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      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 text5 = `
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((_2) => {
          const it = _2;
          const keyFrom = it.from.name;
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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}`)}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      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 text5 = `
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((_2) => {
          const it = _2;
          const keyFrom = tableKey(it.from);
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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}`)}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      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 text5 = `
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((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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")}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      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;
        };
      }
    };
    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}
`;
      }
    };
  }
});

// src/serializer/index.ts
var glob;
var init_serializer = __esm({
  "src/serializer/index.ts"() {
    "use strict";
    glob = __toESM(require_glob());
    init_views();
  }
});

// src/migrationPreparator.ts
var fillPgSnapshot;
var init_migrationPreparator = __esm({
  "src/migrationPreparator.ts"() {
    "use strict";
    init_serializer();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    fillPgSnapshot = ({
      serialized,
      id,
      idPrev
    }) => {
      return { id, prevId: idPrev, ...serialized };
    };
  }
});

// ../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"(exports, module) {
    "use strict";
    (function() {
      var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min2, nlargest, nsmallest, updateItem, _siftdown, _siftup;
      floor = Math.floor, min2 = Math.min;
      defaultCmp = function(x, y) {
        if (x < y) {
          return -1;
        }
        if (x > y) {
          return 1;
        }
        return 0;
      };
      insort = function(a, x, 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 = a.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x, a[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a, [lo, lo - lo].concat(x)), x;
      };
      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 i, _i2, _j2, _len, _ref, _ref1, _results, _results1;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        _ref1 = function() {
          _results1 = [];
          for (var _j3 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j3 < _ref2 : _j3 > _ref2; 0 <= _ref2 ? _j3++ : _j3--) {
            _results1.push(_j3);
          }
          return _results1;
        }.apply(this).reverse();
        _results = [];
        for (_i2 = 0, _len = _ref1.length; _i2 < _len; _i2++) {
          i = _ref1[_i2];
          _results.push(_siftup(array2, i, 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, n, cmp) {
        var elem, result, _i2, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array2.slice(0, n);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array2.slice(n);
        for (_i2 = 0, _len = _ref.length; _i2 < _len; _i2++) {
          elem = _ref[_i2];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array2, n, cmp) {
        var elem, i, los, result, _i2, _j2, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n * 10 <= array2.length) {
          result = array2.slice(0, n).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array2.slice(n);
          for (_i2 = 0, _len = _ref.length; _i2 < _len; _i2++) {
            elem = _ref[_i2];
            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 (i = _j2 = 0, _ref1 = min2(n, array2.length); 0 <= _ref1 ? _j2 < _ref1 : _j2 > _ref1; i = 0 <= _ref1 ? ++_j2 : --_j2) {
          _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(x) {
          return heappush(this.nodes, x, this.cmp);
        };
        Heap2.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap2.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap2.prototype.contains = function(x) {
          return this.nodes.indexOf(x) !== -1;
        };
        Heap2.prototype.replace = function(x) {
          return heapreplace(this.nodes, x, this.cmp);
        };
        Heap2.prototype.pushpop = function(x) {
          return heappushpop(this.nodes, x, this.cmp);
        };
        Heap2.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap2.prototype.updateItem = function(x) {
          return updateItem(this.nodes, x, 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 exports === "object") {
          return module.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap;
      });
    }).call(exports);
  }
});

// ../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"(exports, module) {
    "use strict";
    module.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"(exports) {
    "use strict";
    (function() {
      var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max2, min2, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
      ({ floor, max: max2, min: min2 } = Math);
      Heap = require_heap2();
      assert = __require("assert");
      _calculateRatio = function(matches, length) {
        if (length) {
          return 2 * matches / length;
        } else {
          return 1;
        }
      };
      _arrayCmp = function(a, b) {
        var i, l, la, lb, ref;
        [la, lb] = [a.length, b.length];
        for (i = l = 0, ref = min2(la, lb); 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
          if (a[i] < b[i]) {
            return -1;
          }
          if (a[i] > b[i]) {
            return 1;
          }
        }
        return la - lb;
      };
      _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
      _any = function(items) {
        var item, l, len;
        for (l = 0, len = items.length; l < len; l++) {
          item = items[l];
          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, a = "", b = "", autojunk = true) {
          this.isjunk = isjunk1;
          this.autojunk = autojunk;
          this.a = this.b = null;
          this.setSeqs(a, b);
        }
        setSeqs(a, b) {
          this.setSeq1(a);
          return this.setSeq2(b);
        }
        setSeq1(a) {
          if (a === this.a) {
            return;
          }
          this.a = a;
          return this.matchingBlocks = this.opcodes = null;
        }
        setSeq2(b) {
          if (b === this.b) {
            return;
          }
          this.b = b;
          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 b, b2j, elt, i, indices, isjunk, junk, l, len, n, ntest, popular;
          b = this.b;
          this.b2j = b2j = /* @__PURE__ */ new Map();
          for (i = l = 0, len = b.length; l < len; i = ++l) {
            elt = b[i];
            if (!b2j.has(elt)) {
              b2j.set(elt, []);
            }
            indices = b2j.get(elt);
            indices.push(i);
          }
          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();
          n = b.length;
          if (this.autojunk && n >= 200) {
            ntest = floor(n / 100) + 1;
            b2j.forEach(function(idxs, elt2) {
              if (idxs.length > ntest) {
                popular.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          this.isbjunk = function(b2) {
            return junk.has(b2);
          };
          return this.isbpopular = function(b2) {
            return popular.has(b2);
          };
        }
        findLongestMatch(alo, ahi, blo, bhi) {
          var a, b, b2j, besti, bestj, bestsize, i, isbjunk, j, j2len, jlist, k, l, len, m, newj2len, ref, ref1;
          [a, b, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
          [besti, bestj, bestsize] = [alo, blo, 0];
          j2len = {};
          for (i = l = ref = alo, ref1 = ahi; ref <= ref1 ? l < ref1 : l > ref1; i = ref <= ref1 ? ++l : --l) {
            newj2len = {};
            jlist = [];
            if (b2j.has(a[i])) {
              jlist = b2j.get(a[i]);
            }
            for (m = 0, len = jlist.length; m < len; m++) {
              j = jlist[m];
              if (j < blo) {
                continue;
              }
              if (j >= bhi) {
                break;
              }
              k = newj2len[j] = (j2len[j - 1] || 0) + 1;
              if (k > bestsize) {
                [besti, bestj, bestsize] = [i - k + 1, j - k + 1, k];
              }
            }
            j2len = newj2len;
          }
          while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          return [besti, bestj, bestsize];
        }
        getMatchingBlocks() {
          var ahi, alo, bhi, blo, i, i1, i2, j, j1, j2, k, k1, k2, l, la, lb, len, matchingBlocks, nonAdjacent, queue, x;
          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();
            [i, j, k] = x = this.findLongestMatch(alo, ahi, blo, bhi);
            if (k) {
              matchingBlocks.push(x);
              if (alo < i && blo < j) {
                queue.push([alo, i, blo, j]);
              }
              if (i + k < ahi && j + k < bhi) {
                queue.push([i + k, ahi, j + k, bhi]);
              }
            }
          }
          matchingBlocks.sort(_arrayCmp);
          i1 = j1 = k1 = 0;
          nonAdjacent = [];
          for (l = 0, len = matchingBlocks.length; l < len; l++) {
            [i2, j2, k2] = matchingBlocks[l];
            if (i1 + k1 === i2 && j1 + k1 === j2) {
              k1 += k2;
            } else {
              if (k1) {
                nonAdjacent.push([i1, j1, k1]);
              }
              [i1, j1, k1] = [i2, j2, k2];
            }
          }
          if (k1) {
            nonAdjacent.push([i1, j1, k1]);
          }
          nonAdjacent.push([la, lb, 0]);
          return this.matchingBlocks = nonAdjacent;
        }
        getOpcodes() {
          var ai, answer, bj, i, j, l, len, ref, size, tag;
          if (this.opcodes) {
            return this.opcodes;
          }
          i = j = 0;
          this.opcodes = answer = [];
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            [ai, bj, size] = ref[l];
            tag = "";
            if (i < ai && j < bj) {
              tag = "replace";
            } else if (i < ai) {
              tag = "delete";
            } else if (j < bj) {
              tag = "insert";
            }
            if (tag) {
              answer.push([tag, i, ai, j, bj]);
            }
            [i, j] = [ai + size, bj + size];
            if (size) {
              answer.push(["equal", ai, i, bj, j]);
            }
          }
          return answer;
        }
        getGroupedOpcodes(n = 3) {
          var codes, group, groups, i1, i2, j1, j2, l, len, nn, tag;
          codes = this.getOpcodes();
          if (!codes.length) {
            codes = [["equal", 0, 1, 0, 1]];
          }
          if (codes[0][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[0];
            codes[0] = [tag, max2(i1, i2 - n), i2, max2(j1, j2 - n), j2];
          }
          if (codes[codes.length - 1][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[codes.length - 1];
            codes[codes.length - 1] = [tag, i1, min2(i2, i1 + n), j1, min2(j2, j1 + n)];
          }
          nn = n + n;
          groups = [];
          group = [];
          for (l = 0, len = codes.length; l < len; l++) {
            [tag, i1, i2, j1, j2] = codes[l];
            if (tag === "equal" && i2 - i1 > nn) {
              group.push([tag, i1, min2(i2, i1 + n), j1, min2(j2, j1 + n)]);
              groups.push(group);
              group = [];
              [i1, j1] = [max2(i1, i2 - n), max2(j1, j2 - n)];
            }
            group.push([tag, i1, i2, j1, j2]);
          }
          if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
            groups.push(group);
          }
          return groups;
        }
        ratio() {
          var l, len, match2, matches, ref;
          matches = 0;
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            match2 = ref[l];
            matches += match2[2];
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        quickRatio() {
          var avail, elt, fullbcount, l, len, len1, m, matches, numb, ref, ref1;
          if (!this.fullbcount) {
            this.fullbcount = fullbcount = {};
            ref = this.b;
            for (l = 0, len = ref.length; l < len; l++) {
              elt = ref[l];
              fullbcount[elt] = (fullbcount[elt] || 0) + 1;
            }
          }
          fullbcount = this.fullbcount;
          avail = {};
          matches = 0;
          ref1 = this.a;
          for (m = 0, len1 = ref1.length; m < len1; m++) {
            elt = ref1[m];
            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(min2(la, lb), la + lb);
        }
      };
      getCloseMatches = function(word, possibilities, n = 3, cutoff = 0.6) {
        var l, len, len1, m, result, results, s, score, x;
        if (!(n > 0)) {
          throw new Error(`n must be > 0: (${n})`);
        }
        if (!(0 <= cutoff && cutoff <= 1)) {
          throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
        }
        result = [];
        s = new SequenceMatcher();
        s.setSeq2(word);
        for (l = 0, len = possibilities.length; l < len; l++) {
          x = possibilities[l];
          s.setSeq1(x);
          if (s.realQuickRatio() >= cutoff && s.quickRatio() >= cutoff && s.ratio() >= cutoff) {
            result.push([s.ratio(), x]);
          }
        }
        result = Heap.nlargest(result, n, _arrayCmp);
        results = [];
        for (m = 0, len1 = result.length; m < len1; m++) {
          [score, x] = result[m];
          results.push(x);
        }
        return results;
      };
      _countLeading = function(line2, ch) {
        var i, n;
        [i, n] = [0, line2.length];
        while (i < n && line2[i] === ch) {
          i++;
        }
        return i;
      };
      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(a, b) {
          var ahi, alo, bhi, blo, cruncher, g, l, len, len1, line2, lines, m, ref, tag;
          cruncher = new SequenceMatcher(this.linejunk, a, b);
          lines = [];
          ref = cruncher.getOpcodes();
          for (l = 0, len = ref.length; l < len; l++) {
            [tag, alo, ahi, blo, bhi] = ref[l];
            switch (tag) {
              case "replace":
                g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
                break;
              case "delete":
                g = this._dump("-", a, alo, ahi);
                break;
              case "insert":
                g = this._dump("+", b, blo, bhi);
                break;
              case "equal":
                g = this._dump(" ", a, alo, ahi);
                break;
              default:
                throw new Error(`unknow tag (${tag})`);
            }
            for (m = 0, len1 = g.length; m < len1; m++) {
              line2 = g[m];
              lines.push(line2);
            }
          }
          return lines;
        }
        _dump(tag, x, lo, hi) {
          var i, l, ref, ref1, results;
          results = [];
          for (i = l = ref = lo, ref1 = hi; ref <= ref1 ? l < ref1 : l > ref1; i = ref <= ref1 ? ++l : --l) {
            results.push(`${tag} ${x[i]}`);
          }
          return results;
        }
        _plainReplace(a, alo, ahi, b, blo, bhi) {
          var first, g, l, len, len1, line2, lines, m, ref, second;
          assert(alo < ahi && blo < bhi);
          if (bhi - blo < ahi - alo) {
            first = this._dump("+", b, blo, bhi);
            second = this._dump("-", a, alo, ahi);
          } else {
            first = this._dump("-", a, alo, ahi);
            second = this._dump("+", b, blo, bhi);
          }
          lines = [];
          ref = [first, second];
          for (l = 0, len = ref.length; l < len; l++) {
            g = ref[l];
            for (m = 0, len1 = g.length; m < len1; m++) {
              line2 = g[m];
              lines.push(line2);
            }
          }
          return lines;
        }
        _fancyReplace(a, alo, ahi, b, blo, bhi) {
          var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i, j, l, la, lb, len, len1, len2, len3, len4, line2, lines, m, o, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t, 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 (j = l = ref = blo, ref1 = bhi; ref <= ref1 ? l < ref1 : l > ref1; j = ref <= ref1 ? ++l : --l) {
            bj = b[j];
            cruncher.setSeq2(bj);
            for (i = m = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m < ref3 : m > ref3; i = ref2 <= ref3 ? ++m : --m) {
              ai = a[i];
              if (ai === bj) {
                if (eqi === null) {
                  [eqi, eqj] = [i, j];
                }
                continue;
              }
              cruncher.setSeq1(ai);
              if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
                [bestRatio, besti, bestj] = [cruncher.ratio(), i, j];
              }
            }
          }
          if (bestRatio < cutoff) {
            if (eqi === null) {
              ref4 = this._plainReplace(a, alo, ahi, b, blo, bhi);
              for (o = 0, len = ref4.length; o < len; o++) {
                line2 = ref4[o];
                lines.push(line2);
              }
              return lines;
            }
            [besti, bestj, bestRatio] = [eqi, eqj, 1];
          } else {
            eqi = null;
          }
          ref5 = this._fancyHelper(a, alo, besti, b, blo, bestj);
          for (p = 0, len1 = ref5.length; p < len1; p++) {
            line2 = ref5[p];
            lines.push(line2);
          }
          [aelt, belt] = [a[besti], b[bestj]];
          if (eqi === null) {
            atags = btags = "";
            cruncher.setSeqs(aelt, belt);
            ref6 = cruncher.getOpcodes();
            for (q = 0, len2 = ref6.length; q < len2; q++) {
              [tag, ai1, ai2, bj1, bj2] = ref6[q];
              [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 (r = 0, len3 = ref7.length; r < len3; r++) {
              line2 = ref7[r];
              lines.push(line2);
            }
          } else {
            lines.push("  " + aelt);
          }
          ref8 = this._fancyHelper(a, besti + 1, ahi, b, bestj + 1, bhi);
          for (t = 0, len4 = ref8.length; t < len4; t++) {
            line2 = ref8[t];
            lines.push(line2);
          }
          return lines;
        }
        _fancyHelper(a, alo, ahi, b, blo, bhi) {
          var g;
          g = [];
          if (alo < ahi) {
            if (blo < bhi) {
              g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
            } else {
              g = this._dump("-", a, alo, ahi);
            }
          } else if (blo < bhi) {
            g = this._dump("+", b, blo, bhi);
          }
          return g;
        }
        _qformat(aline, bline, atags, btags) {
          var common, lines;
          lines = [];
          common = min2(_countLeading(aline, "	"), _countLeading(bline, "	"));
          common = min2(common, _countLeading(atags.slice(0, common), " "));
          common = min2(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(line2, pat = /^\s*#?\s*$/) {
        return pat.test(line2);
      };
      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(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line2, lines, m, o, p, q, ref, ref1, ref2, ref3, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        lines = [];
        started = false;
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          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 (m = 0, len1 = group.length; m < len1; m++) {
            [tag, i1, i2, j1, j2] = group[m];
            if (tag === "equal") {
              ref1 = a.slice(i1, i2);
              for (o = 0, len2 = ref1.length; o < len2; o++) {
                line2 = ref1[o];
                lines.push(" " + line2);
              }
              continue;
            }
            if (tag === "replace" || tag === "delete") {
              ref2 = a.slice(i1, i2);
              for (p = 0, len3 = ref2.length; p < len3; p++) {
                line2 = ref2[p];
                lines.push("-" + line2);
              }
            }
            if (tag === "replace" || tag === "insert") {
              ref3 = b.slice(j1, j2);
              for (q = 0, len4 = ref3.length; q < len4; q++) {
                line2 = ref3[q];
                lines.push("+" + line2);
              }
            }
          }
        }
        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(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var _2, file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line2, lines, m, o, p, prefix2, q, ref, ref1, ref2, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        prefix2 = {
          insert: "+ ",
          delete: "- ",
          replace: "! ",
          equal: "  "
        };
        started = false;
        lines = [];
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          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, m2, results;
              results = [];
              for (m2 = 0, len12 = group.length; m2 < len12; m2++) {
                [tag, _2, _2, _2, _2] = group[m2];
                results.push(tag === "replace" || tag === "delete");
              }
              return results;
            }())) {
              for (m = 0, len1 = group.length; m < len1; m++) {
                [tag, i1, i2, _2, _2] = group[m];
                if (tag !== "insert") {
                  ref1 = a.slice(i1, i2);
                  for (o = 0, len2 = ref1.length; o < len2; o++) {
                    line2 = ref1[o];
                    lines.push(prefix2[tag] + line2);
                  }
                }
              }
            }
            file2Range = _formatRangeContext(first[3], last[4]);
            lines.push(`--- ${file2Range} ----${lineterm}`);
            if (_any(function() {
              var len32, p2, results;
              results = [];
              for (p2 = 0, len32 = group.length; p2 < len32; p2++) {
                [tag, _2, _2, _2, _2] = group[p2];
                results.push(tag === "replace" || tag === "insert");
              }
              return results;
            }())) {
              for (p = 0, len3 = group.length; p < len3; p++) {
                [tag, _2, _2, j1, j2] = group[p];
                if (tag !== "delete") {
                  ref2 = b.slice(j1, j2);
                  for (q = 0, len4 = ref2.length; q < len4; q++) {
                    line2 = ref2[q];
                    lines.push(prefix2[tag] + line2);
                  }
                }
              }
            }
          }
        }
        return lines;
      };
      ndiff = function(a, b, linejunk, charjunk = IS_CHARACTER_JUNK) {
        return new Differ(linejunk, charjunk).compare(a, b);
      };
      restore = function(delta, which) {
        var l, len, line2, 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 (l = 0, len = delta.length; l < len; l++) {
          line2 = delta[l];
          if (ref = line2.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
            lines.push(line2.slice(2));
          }
        }
        return lines;
      };
      exports._arrayCmp = _arrayCmp;
      exports.SequenceMatcher = SequenceMatcher;
      exports.getCloseMatches = getCloseMatches;
      exports._countLeading = _countLeading;
      exports.Differ = Differ;
      exports.IS_LINE_JUNK = IS_LINE_JUNK;
      exports.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
      exports._formatRangeUnified = _formatRangeUnified;
      exports.unifiedDiff = unifiedDiff;
      exports._formatRangeContext = _formatRangeContext;
      exports.contextDiff = contextDiff;
      exports.ndiff = ndiff;
      exports.restore = restore;
    }).call(exports);
  }
});

// ../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"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    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((x) => roundObj(x, 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;
      }
    };
    module.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"(exports, module) {
    "use strict";
    var styles3 = {};
    module["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 val = codes[key];
      var style = styles3[key] = [];
      style.open = "\x1B[" + val[0] + "m";
      style.close = "\x1B[" + val[1] + "m";
    });
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
var require_has_flag = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    var os2 = __require("os");
    var hasFlag2 = require_has_flag();
    var env2 = 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 env2) {
      forceColor = env2.FORCE_COLOR.length === 0 || parseInt(env2.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 min2 = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        var osRelease = os2.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 env2) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env2;
        }) || env2.CI_NAME === "codeship") {
          return 1;
        }
        return min2;
      }
      if ("TEAMCITY_VERSION" in env2) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env2) {
        var version2 = parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env2.TERM_PROGRAM) {
          case "iTerm.app":
            return version2 >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env2.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env2) {
        return 1;
      }
      if (env2.TERM === "dumb") {
        return min2;
      }
      return min2;
    }
    function getSupportLevel(stream) {
      var level = supportsColor2(stream);
      return translateLevel2(level);
    }
    module.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"(exports, module) {
    "use strict";
    module["exports"] = function runTheTrap(text5, options) {
      var result = "";
      text5 = text5 || "Run the trap, drop the bass";
      text5 = text5.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"]
      };
      text5.forEach(function(c) {
        c = c.toLowerCase();
        var chars = trap[c] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c] !== "undefined") {
          result += trap[c][rand];
        } else {
          result += c;
        }
      });
      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"(exports, module) {
    "use strict";
    module["exports"] = function zalgo(text5, options) {
      text5 = text5 || "   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 r = Math.floor(Math.random() * range);
        return r;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i) {
          bool = i === character;
        });
        return bool;
      }
      function heComes(text6, options2) {
        var result = "";
        var counts;
        var l;
        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";
        text6 = text6.split("");
        for (l in text6) {
          if (isChar(l)) {
            continue;
          }
          result = result + text6[l];
          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 d in arr) {
            var index5 = arr[d];
            for (var i = 0; i <= counts[index5]; i++) {
              if (options2[index5]) {
                result = result + soul[index5][randomNumber(soul[index5].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text5, 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"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      return function(letter, i, exploded) {
        if (letter === " ") return letter;
        switch (i % 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"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      return function(letter, i, exploded) {
        return i % 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"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors[rainbowColors[i++ % 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"(exports, module) {
    "use strict";
    module["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, i, 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"(exports, module) {
    "use strict";
    var colors = {};
    module["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 i = nestedStyles.length;
      while (i--) {
        var code = ansiStyles2[nestedStyles[i]];
        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 i in theme[style2]) {
                out = colors[theme[style2][i]](out);
              }
              return out;
            }
            return colors[theme[style2]](str);
          };
        })(style);
      }
    };
    function init() {
      var ret = {};
      Object.keys(styles3).forEach(function(name2) {
        ret[name2] = {
          get: function() {
            return build([name2]);
          }
        };
      });
      return ret;
    }
    var sequencer = function sequencer2(map2, str) {
      var exploded = str.split("");
      exploded = exploded.map(map2);
      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 (map in colors.maps) {
      (function(map2) {
        colors[map2] = function(str) {
          return sequencer(colors.maps[map2], str);
        };
      })(map);
    }
    var map;
    defineProps(colors, init());
  }
});

// ../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"(exports, module) {
    "use strict";
    var colors = require_colors();
    module["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"(exports, module) {
    "use strict";
    var color = require_safe();
    var { extendedTypeOf } = require_util();
    var Theme = {
      " "(s) {
        return s;
      },
      "+": color.green,
      "-": color.red
    };
    var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
      let subvalue;
      const prefix2 = key ? `${key}: ` : "";
      const subindent = indent + "  ";
      const outputElisions = (n) => {
        const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
        if (n < maxElisions) {
          for (let i = 0; i < n; i++) {
            output(" ", subindent + "...");
          }
        } else {
          output(" ", subindent + `... (${n} 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 m;
              subvalue = diff2[subkey];
              if (m = subkey.match(/^(.*)__deleted$/)) {
                subcolorizeToCallback(options, m[1], subvalue, output, "-", subindent);
              } else if (m = subkey.match(/^(.*)__added$/)) {
                subcolorizeToCallback(options, m[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, line2) => output.push(`${color2}${line2}`));
      return output;
    };
    var colorize = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, function(color2, line2) {
        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}${line2}`) + "\n");
        } else {
          return output.push(`${color2}${line2}
`);
        }
      });
      return output.join("");
    };
    module.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"(exports, module) {
    "use strict";
    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, index5, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index5);
            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 index5 = 0; index5 < array2.length; index5++) {
            const item = array2[index5];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index5, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index5 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index5 = 0; index5 < array2.length; index5++) {
          const item = array2[index5];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index5] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index5 };
            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, i2, j1, j2] of opcodes) {
          let i, j;
          let asc2, end;
          let asc1, end1;
          let asc22, end2;
          if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
            equal = false;
          }
          switch (op) {
            case "equal":
              for (i = i1, end = i2, asc2 = i1 <= end; asc2 ? i < end : i > end; asc2 ? i++ : i--) {
                const item = seq1[i];
                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 (i = i1, end1 = i2, asc1 = i1 <= end1; asc1 ? i < end1 : i > end1; asc1 ? i++ : i--) {
                result.push(["-", this.descalarize(seq1[i], originals1)]);
                score -= 5;
              }
              break;
            case "insert":
              for (j = j1, end2 = j2, asc22 = j1 <= end2; asc22 ? j < end2 : j > end2; asc22 ? j++ : j--) {
                result.push(["+", this.descalarize(seq2[j], originals2)]);
                score -= 5;
              }
              break;
            case "replace":
              if (!this.options.keysOnly) {
                let asc3, end3;
                let asc4, end4;
                for (i = i1, end3 = i2, asc3 = i1 <= end3; asc3 ? i < end3 : i > end3; asc3 ? i++ : i--) {
                  result.push(["-", this.descalarize(seq1[i], originals1)]);
                  score -= 5;
                }
                for (j = j1, end4 = j2, asc4 = j1 <= end4; asc4 ? j < end4 : j > end4; asc4 ? j++ : j--) {
                  result.push(["+", this.descalarize(seq2[j], originals2)]);
                  score -= 5;
                }
              } else {
                let asc5, end5;
                for (i = i1, end5 = i2, asc5 = i1 <= end5; asc5 ? i < end5 : i > end5; asc5 ? i++ : i--) {
                  const change = this.diff(
                    this.descalarize(seq1[i], originals1),
                    this.descalarize(seq2[i - 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);
    }
    module.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 table5 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table5.name, schema: table5.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 table5 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table5.name, schema: table5.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function applyJsonDiff(json1, json22) {
  json1 = JSON.parse(JSON.stringify(json1));
  json22 = JSON.parse(JSON.stringify(json22));
  const rawDiff = (0, import_json_diff.diff)(json1, json22);
  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 table5 = json1.tables[key];
    difference.tables[key] = {
      name: table5.name,
      schema: table5.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table5 = 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 table5.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table5["columns"];
    }
    if ("name" in table5 && "schema" in table5 && Object.keys(table5).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: name2, schema: schema5, 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: name2, schema: schema5, 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 json22.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 json22.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 json22.policies[it[0]];
  });
  const viewsEntries = Object.entries(difference.views);
  const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
    ([nameWithSchema, view4]) => {
      const deletedWithOption = view4.with__deleted;
      const addedWithOption = view4.with__added;
      const deletedWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
          return [key.replace("__deleted", ""), value];
        })
      );
      const addedWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
          return [key.replace("__added", ""), value];
        })
      );
      const alterWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter(
          (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
        ).map(
          (it) => {
            return [it[0], it[1].__new];
          }
        )
      );
      const alteredSchema = view4.schema;
      const alteredDefinition = view4.definition;
      const alteredExisting = view4.isExisting;
      const addedTablespace = view4.tablespace__added;
      const droppedTablespace = view4.tablespace__deleted;
      const alterTablespaceTo = view4.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 = view4.using__added;
      const droppedUsing = view4.using__deleted;
      const alterUsingTo = view4.using;
      let alteredUsing;
      if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
      if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
      if (alterUsingTo) alteredUsing = alterUsingTo;
      const alteredMeta = view4.meta;
      return Object.fromEntries(
        Object.entries({
          name: json22.views[nameWithSchema].name,
          schema: json22.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(([_2, value]) => value !== void 0)
      );
    }
  );
  const alteredTablesWithColumns = Object.values(difference.tables).map(
    (table5) => {
      return findAlternationsInTable(table5);
    }
  );
  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 i = 0; i < diff2.length; i++) {
        const it = diff2[i];
        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 = (table5) => {
      const columns = table5.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(table5.indexes__deleted || {}).concat(
          Object.entries(table5.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table5.indexes__added || {}).concat(
          Object.entries(table5.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table5.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table5.policies__deleted || {}).concat(
          Object.entries(table5.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table5.policies__added || {}).concat(
          Object.entries(table5.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table5.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys__deleted || {}).concat(
          Object.entries(table5.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys__added || {}).concat(
          Object.entries(table5.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table5.name,
        schema: table5.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column5) => {
      const altered = [column5];
      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, json22) {
  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, json22, 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_utils();
    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"
      ];
      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) {
        const policy4 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy4.using ? ` USING (${policy4.using})` : "";
        const withCheckPart = policy4.withCheck ? ` WITH CHECK (${policy4.withCheck})` : "";
        const policyToPart = policy4.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy4.name}" ON ${tableNameWithSchema} AS ${policy4.as?.toUpperCase()} FOR ${policy4.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy4 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy4.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) {
        const policy4 = statement.data;
        const usingPart = policy4.using ? ` USING (${policy4.using})` : "";
        const withCheckPart = policy4.withCheck ? ` WITH CHECK (${policy4.withCheck})` : "";
        const policyToPart = policy4.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy4.name}" ON ${policy4.on} AS ${policy4.as?.toUpperCase()} FOR ${policy4.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy4 = statement.data;
        return `DROP POLICY "${policy4.name}" ON ${policy4.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: schema5, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
        let statement = "";
        const name2 = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        statement += `CREATE TABLE ${name2} (
`;
        for (let i = 0; i < columns.length; i++) {
          const column5 = columns[i];
          const primaryKeyStatement = column5.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column5.notNull && !column5.identity ? " NOT NULL" : "";
          const defaultStatement = column5.default !== void 0 ? ` DEFAULT ${column5.default}` : "";
          const uniqueConstraint5 = column5.isUnique ? ` CONSTRAINT "${column5.uniqueName}" UNIQUE${column5.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column5.typeSchema && column5.typeSchema !== "public" ? `"${column5.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column5.type);
          const generated = column5.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
          const unsquashedIdentity = column5.identity ? PgSquasher.unsquashIdentity(column5.identity) : void 0;
          const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${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 += `	"${column5.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint5}${identity}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK5.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint5);
            statement += `	CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint4 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint4);
            statement += `	CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        const enableRls = new PgEnableRlsConvertor().convert({
          type: "enable_rls",
          tableName,
          schema: schema5
        });
        return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
      }
    };
    MySqlCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "mysql";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema5,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column5 = columns[i];
          const primaryKeyStatement = column5.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column5.notNull ? " NOT NULL" : "";
          const defaultStatement = column5.default !== void 0 ? ` DEFAULT ${column5.default}` : "";
          const onUpdateStatement = column5.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column5.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column5.generated ? ` GENERATED ALWAYS AS (${column5.generated?.as}) ${column5.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column5.name}\` ${column5.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK5.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint5);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint4 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint4);
            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) {
        const {
          tableName,
          columns,
          schema: schema5,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column5 = columns[i];
          const primaryKeyStatement = column5.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column5.notNull ? " NOT NULL" : "";
          const defaultStatement = column5.default !== void 0 ? ` DEFAULT ${column5.default}` : "";
          const onUpdateStatement = column5.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column5.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column5.generated ? ` GENERATED ALWAYS AS (${column5.generated?.as}) ${column5.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column5.name}\` ${column5.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${compositePK5.name}\` PRIMARY KEY(\`${compositePK5.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint5);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.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 i = 0; i < columns.length; i++) {
          const column5 = columns[i];
          const primaryKeyStatement = column5.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column5.notNull ? " NOT NULL" : "";
          const defaultStatement = column5.default !== void 0 ? ` DEFAULT ${column5.default}` : "";
          const autoincrementStatement = column5.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column5.generated ? ` GENERATED ALWAYS AS ${column5.generated.as} ${column5.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column5.name}\` ${column5.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        compositePKs.forEach((it) => {
          statement += ",\n	";
          statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
        });
        for (let i = 0; i < referenceData.length; i++) {
          const {
            name: name2,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          } = referenceData[i];
          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 uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint5);
            statement += `	CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const check of checkConstraints) {
            statement += ",\n";
            const { value, name: name2 } = SQLiteSquasher.unsquashCheck(check);
            statement += `	CONSTRAINT "${name2}" 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: schema5, with: withOption, materialized, withNoData, tablespace, using } = st;
        const name2 = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
        let statement = materialized ? `CREATE MATERIALIZED VIEW ${name2}` : `CREATE VIEW ${name2}`;
        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: name2, algorithm, sqlSecurity, withCheckOption, replace } = st;
        let statement = `CREATE `;
        statement += replace ? `OR REPLACE ` : "";
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name2}\` 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: name2 } = st;
        return `CREATE VIEW \`${name2}\` AS ${definition};`;
      }
    };
    PgDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: viewName, schema: schema5, materialized } = st;
        const name2 = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
        return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
      }
    };
    MySqlDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    SqliteDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    MySqlAlterViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_mysql_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name: name2, algorithm, definition, sqlSecurity, withCheckOption } = st;
        let statement = `ALTER `;
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name2}\` 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: schema5, materialized } = st;
        const nameFrom = `"${schema5}"."${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: name2, materialized } = st;
        const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name2}" 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: schema5, with: withOption, name: name2, materialized } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name2}" 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: schema5, name: name2, materialized, with: withOptions } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name2}" 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: schema5, name: name2, toTablespace } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name2}" 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: schema5, name: name2, toUsing } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name2}" 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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: name2, values, schema: schema5 } = st;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        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: name2, schema: schema5 } = st;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `DROP SEQUENCE ${sequenceWithSchema};`;
      }
    };
    RenamePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom, nameTo, schema: schema5 } = st;
        const sequenceWithSchemaFrom = schema5 ? `"${schema5}"."${nameFrom}"` : `"${nameFrom}"`;
        const sequenceWithSchemaTo = schema5 ? `"${schema5}"."${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: name2 } = st;
        const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
        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: name2, schema: schema5, values } = st;
        const { increment, minValue, maxValue, startWith, cache, cycle } = values;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache ? ` CACHE ${cache}` : ""}${cycle ? ` CYCLE` : ""};`;
      }
    };
    CreateTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "create_type_enum";
      }
      convert(st) {
        const { name: name2, values, schema: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        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: name2, schema: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        let statement = `DROP TYPE ${enumNameWithSchema};`;
        return statement;
      }
    };
    AlterTypeAddValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_add_value";
      }
      convert(st) {
        const { name: name2, schema: schema5, value, before } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        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: name2, schemaFrom, schemaTo } = st;
        const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
        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: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${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: name2, newValues, schema: schema5 } = st;
        const statements = [];
        for (const withEnum of columnsWithEnum) {
          statements.push(
            `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
          );
        }
        statements.push(new DropTypeEnumConvertor().convert({ name: name2, schema: schema5, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name: name2,
          schema: schema5,
          values: newValues,
          type: "create_type_enum"
        }));
        for (const withEnum of columnsWithEnum) {
          statements.push(
            `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE "${schema5}"."${name2}" USING "${withEnum.column}"::"${schema5}"."${name2}";`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "postgresql";
      }
      convert(statement, _d6, action) {
        const { tableName, schema: schema5, policies } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const dropPolicyConvertor = new PgDropPolicyConvertor();
        const droppedPolicies = policies?.map((p) => {
          return dropPolicyConvertor.convert({
            type: "drop_policy",
            tableName,
            data: action === "push" ? PgSquasher.unsquashPolicyPush(p) : PgSquasher.unsquashPolicy(p),
            schema: schema5
          });
        }) ?? [];
        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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: column5, schema: schema5 } = statement;
        const { name: name2, type, notNull, generated, primaryKey, identity } = column5;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column5.default !== void 0 ? ` DEFAULT ${column5.default}` : ""}`;
        const schemaPrefix = column5.typeSchema && column5.typeSchema !== "public" ? `"${column5.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column5.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${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?.as}) STORED` : "";
        return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name2}" ${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: column5 } = statement;
        const {
          name: name2,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column5;
        const defaultStatement = `${column5.default !== void 0 ? ` DEFAULT ${column5.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?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name2}\` ${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: column5 } = statement;
        const {
          name: name2,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column5;
        const defaultStatement = `${column5.default !== void 0 ? ` DEFAULT ${column5.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?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name2}\` ${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: column5, referenceData } = statement;
        const { name: name2, type, notNull, primaryKey, generated } = column5;
        const defaultStatement = `${column5.default !== void 0 ? ` DEFAULT ${column5.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 \`${name2}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
      }
    };
    PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_type" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${newDataType};`;
      }
    };
    PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${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: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema5,
          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: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema5,
          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: schema5,
          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: schema5,
          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: schema5,
          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: schema5,
          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: schema5,
          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: schema5,
          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: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `\`${schema5}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
          schema: schema5,
          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, json22) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        const sqlStatements = [];
        const indexes = [];
        for (const table5 of Object.values(json22.tables)) {
          for (const index5 of Object.values(table5.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index5);
            sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table5.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 index5 of indexes) {
          const indexPart = index5.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index5.where ? ` WHERE ${index5.where}` : "";
          const uniqueString = index5.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index5.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index5.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) {
        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 (statement.columnGenerated?.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 (${statement.columnGenerated?.as}) ${statement.columnGenerated?.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 (statement.oldColumn?.generated?.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 (${statement.columnGenerated?.as}) ${statement.columnGenerated?.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: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `\`${schema5}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
          schema: schema5,
          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) {
        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 (statement.columnGenerated?.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 (${statement.columnGenerated?.as}) ${statement.columnGenerated?.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 (statement.oldColumn?.generated?.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 (${statement.columnGenerated?.as}) ${statement.columnGenerated?.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: name2, 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: name2, 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: name2, 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: name2, 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: name2, 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: name2, 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: schema5 } = 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 schema5 === "undefined" || schema5 === "" ? "public" : schema5}'
                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: name2,
          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 "${name2}" 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, json22, 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: name2,
          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 \`${name2}\` 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 sql2 = `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};`;
        sql2 += alterStatement;
        return sql2;
      }
    };
    PgDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name: name2 } = PgSquasher.unsquashFK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name2}";
`;
      }
    };
    MySqlDeleteForeignKeyConvertor = class extends
Showing 512.00 KB of 1.63 MB. Use Edit/Download for full content.

Directory Contents

Dirs: 1 × Files: 15
Name Size Perms Modified Actions
- drwxr-xr-x 2025-07-10 12:55:01
Edit Download
101.94 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
101.93 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
1.63 MB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
1.63 MB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
2.99 MB lrwxr-xr-x 2025-07-10 12:54:57
Edit Download
11.61 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
11.61 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
85 B lrw-r--r-- 2025-07-10 12:54:58
Edit Download
84 B lrw-r--r-- 2025-07-10 12:54:58
Edit Download
1.08 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
94 B lrw-r--r-- 2025-07-10 12:54:58
Edit Download
3.63 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
2.02 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
181.55 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
180.36 KB lrw-r--r-- 2025-07-10 12:54:58
Edit Download
If ZipArchive is unavailable, a .tar will be created (no compression).