"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name2 in all)
    __defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except4, desc2) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except4)
        __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
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
  const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix2 + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
function envForceColor() {
  if ("FORCE_COLOR" in env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor();
  if (noFlagForceColor !== void 0) {
    flagForceColor = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
      return 3;
    }
    if (hasFlag("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min2 = forceColor || 0;
  if (env.TERM === "dumb") {
    return min2;
  }
  if (import_node_process.default.platform === "win32") {
    const osRelease = import_node_os.default.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
      return 3;
    }
    if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return 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 import_node_process, import_node_os, import_node_tty, env, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
  "../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
    "use strict";
    import_node_process = __toESM(require("process"), 1);
    import_node_os = __toESM(require("os"), 1);
    import_node_tty = __toESM(require("tty"), 1);
    ({ env } = import_node_process.default);
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      flagForceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      flagForceColor = 1;
    }
    supportsColor = {
      stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
      stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
    };
    supports_color_default = supportsColor;
  }
});

// ../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring, replacer) {
  let index4 = string.indexOf(substring);
  if (index4 === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index4) + substring + replacer;
    endIndex = index4 + substringLength;
    index4 = string.indexOf(substring, endIndex);
  } while (index4 !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix2, postfix, index4) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index4 - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index4 - 1 : index4) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index4 + 1;
    index4 = string.indexOf("\n", endIndex);
  } while (index4 !== -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"(exports2) {
    "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;
    exports2.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;
    };
    exports2.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"(exports2, module2) {
    "use strict";
    module2.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"(exports2, module2) {
    "use strict";
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  }
});

// ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    module2.exports = balanced;
    function balanced(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"(exports2, module2) {
    "use strict";
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function 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"(exports2, module2) {
    "use strict";
    var minimatch2 = module2.exports = (p, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p);
    };
    module2.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"(exports2, module2) {
    "use strict";
    if (typeof Object.create === "function") {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

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

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
var require_common = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports2) {
    "use strict";
    exports2.setopts = setopts;
    exports2.ownProp = ownProp;
    exports2.makeAbs = makeAbs;
    exports2.finish = finish;
    exports2.mark = mark;
    exports2.isIgnored = isIgnored;
    exports2.childrenIgnored = childrenIgnored;
    function ownProp(obj, field) {
      return Object.prototype.hasOwnProperty.call(obj, field);
    }
    var 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"(exports2, module2) {
    "use strict";
    module2.exports = globSync;
    globSync.GlobSync = GlobSync;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var Glob = require_glob().Glob;
    var util2 = require("util");
    var 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, index4) {
          var set = self2.matches[index4] = /* @__PURE__ */ Object.create(null);
          for (var p in matchset) {
            try {
              p = self2._makeAbs(p);
              var real4 = rp.realpathSync(p, self2.realpathCache);
              set[real4] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index4, 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("/"), index4);
          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, index4, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index4, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index4, 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[index4])
          this.matches[index4] = /* @__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(index4, 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), index4, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index4, 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[index4][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index4][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, index4, 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, index4, 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, index4, true);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index4, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index4) {
      var exists2 = this._stat(prefix2);
      if (!this.matches[index4])
        this.matches[index4] = /* @__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(index4, 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"(exports2, module2) {
    "use strict";
    module2.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

// ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
  "../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports2, module2) {
    "use strict";
    var wrappy = require_wrappy();
    module2.exports = wrappy(once);
    module2.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once(fn) {
      var f = function() {
        if (f.called) return f.value;
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      f.called = false;
      return f;
    }
    function onceStrict(fn) {
      var f = function() {
        if (f.called)
          throw new Error(f.onceError);
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      var 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"(exports2, module2) {
    "use strict";
    var wrappy = require_wrappy();
    var reqs = /* @__PURE__ */ Object.create(null);
    var once = require_once();
    module2.exports = wrappy(inflight);
    function inflight(key, cb) {
      if (reqs[key]) {
        reqs[key].push(cb);
        return null;
      } else {
        reqs[key] = [cb];
        return makeres(key);
      }
    }
    function makeres(key) {
      return once(function RES() {
        var cbs = reqs[key];
        var len = cbs.length;
        var args = slice(arguments);
        try {
          for (var 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"(exports2, module2) {
    "use strict";
    module2.exports = glob2;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var inherits = require_inherits();
    var EE = require("events").EventEmitter;
    var 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(index4, cb) {
      var matchset = this.matches[index4];
      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[index4] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p, i) {
        p = self2._makeAbs(p);
        rp.realpath(p, self2.realpathCache, function(er, real4) {
          if (!er)
            set[real4] = true;
          else if (er.syscall === "stat")
            set[p] = true;
          else
            self2.emit("error", er);
          if (--n === 0) {
            self2.matches[index4] = 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, index4, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index4, inGlobStar, cb]);
        return;
      }
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        case pattern.length:
          this._processSimple(pattern.join("/"), index4, 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, index4, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index4, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index4, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index4, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index4, 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[index4])
          this.matches[index4] = /* @__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(index4, 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), index4, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index4, e) {
      if (this.aborted)
        return;
      if (isIgnored(this, e))
        return;
      if (this.paused) {
        this._emitQueue.push([index4, 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[index4][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index4][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, index4, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index4, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index4, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index4, 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, index4, true, cb);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index4, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index4, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists2) {
        self2._processSimple2(prefix2, index4, er, exists2, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index4, er, exists2, cb) {
      if (!this.matches[index4])
        this.matches[index4] = /* @__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(index4, 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"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareReadLine = void 0;
    var prepareReadLine = () => {
      const stdin = process.stdin;
      const stdout = process.stdout;
      const readline = require("readline");
      const rl = readline.createInterface({
        input: stdin,
        escapeCodeTimeout: 50
      });
      readline.emitKeypressEvents(stdin, rl);
      return {
        stdin,
        stdout,
        closable: rl
      };
    };
    exports2.prepareReadLine = prepareReadLine;
  }
});

// ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
  "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
    "use strict";
    var ESC = "\x1B";
    var CSI = `${ESC}[`;
    var beep = "\x07";
    var cursor = {
      to(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;
      }
    };
    module2.exports = { cursor, scroll, erase, beep };
  }
});

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

// ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
  "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
    "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(time3) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time3;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time3) {
        lastInvokeTime = time3;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time3) : result;
      }
      function remainingWait(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time3 = now();
        if (shouldInvoke(time3)) {
          return trailingEdge(time3);
        }
        timerId = setTimeout(timerExpired, remainingWait(time3));
      }
      function trailingEdge(time3) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time3);
        }
        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 time3 = now(), isInvoking = shouldInvoke(time3);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time3;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function throttle(func, wait, options) {
      var leading = true, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = "leading" in options ? !!options.leading : leading;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
        "leading": leading,
        "maxWait": wait,
        "trailing": trailing
      });
    }
    function isObject(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module2.exports = throttle;
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
var require_hanji = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports2) {
    "use strict";
    var __awaiter = exports2 && exports2.__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 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.onTerminate = exports2.renderWithTask = exports2.render = exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
    var readline_1 = require_readline();
    var sisteransi_1 = require_src();
    var utils_1 = require_utils();
    var lodash_throttle_1 = __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));
      }
    };
    exports2.Prompt = Prompt3;
    var SelectState3 = class {
      constructor(items) {
        this.items = items;
        this.selectedIdx = 0;
      }
      bind(prompt) {
        prompt.on("input", (str, key) => {
          const invalidate = this.consume(str, key);
          if (invalidate)
            prompt.requestLayout();
        });
      }
      consume(str, key) {
        if (!key)
          return false;
        if (key.name === "down") {
          this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
          return true;
        }
        if (key.name === "up") {
          this.selectedIdx -= 1;
          this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
          return true;
        }
        return false;
      }
    };
    exports2.SelectState = SelectState3;
    var deferred = () => {
      let resolve;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
      });
      return {
        resolve,
        reject,
        promise
      };
    };
    exports2.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, exports2.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}`);
      }
    };
    exports2.Terminal = Terminal;
    var TaskView2 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        }
      }
    };
    exports2.TaskView = TaskView2;
    var TaskTerminal = class {
      constructor(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}`);
      }
    };
    exports2.TaskTerminal = TaskTerminal;
    function render6(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;
    }
    exports2.render = render6;
    function renderWithTask4(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;
      });
    }
    exports2.renderWithTask = renderWithTask4;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports2.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 _a326, _b233;
    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: (_a326 = message !== null && message !== void 0 ? message : required_error) !== null && _a326 !== void 0 ? _a326 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b233 = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b233 !== void 0 ? _b233 : 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(schema4) {
  if (schema4 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema4.shape) {
      const fieldSchema = schema4.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema4._def,
      shape: () => newShape
    });
  } else if (schema4 instanceof ZodArray) {
    return new ZodArray({
      ...schema4._def,
      type: deepPartialify(schema4.element)
    });
  } else if (schema4 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema4.unwrap()));
  } else if (schema4 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema4.unwrap()));
  } else if (schema4 instanceof ZodTuple) {
    return ZodTuple.create(schema4.items.map((item) => deepPartialify(item)));
  } else {
    return schema4;
  }
}
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 index4 = 0; index4 < a.length; index4++) {
      const itemA = a[index4];
      const itemB = b[index4];
      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 _a326;
        const ctx = {
          common: {
            issues: [],
            async: (_a326 = params === null || params === void 0 ? void 0 : params.async) !== null && _a326 !== void 0 ? _a326 : 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 (_a326) {
              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 _a326, _b233;
        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: (_a326 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a326 !== void 0 ? _a326 : false,
          local: (_b233 = options === null || options === void 0 ? void 0 : options.local) !== null && _b233 !== void 0 ? _b233 : 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 _a326;
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a326 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a326 !== void 0 ? _a326 : 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 _a326;
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a326 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a326 !== void 0 ? _a326 : 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 = (schema4, params) => {
      return new ZodArray({
        type: schema4,
        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 _a326, _b233, _c11, _d5;
              const defaultError = (_c11 = (_b233 = (_a326 = this._def).errorMap) === null || _b233 === void 0 ? void 0 : _b233.call(_a326, issue, ctx).message) !== null && _c11 !== void 0 ? _c11 : ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: (_d5 = errorUtil.errToObj(message).message) !== null && _d5 !== void 0 ? _d5 : 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, schema4) {
        return this.augment({ [key]: schema4 });
      }
      // 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(index4) {
        return new _ZodObject({
          ...this._def,
          catchall: index4
        });
      }
      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 schema4 = this._def.items[itemIndex] || this._def.rest;
          if (!schema4)
            return null;
          return schema4._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], index4) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index4, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index4, "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 = (schema4, params) => {
      return new ZodPromise({
        type: schema4,
        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 = (schema4, effect, params) => {
      return new ZodEffects({
        schema: schema4,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema4, params) => {
      return new ZodEffects({
        schema: schema4,
        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 = (json3) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json3.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index4) => {
            return MySqlSquasher.squashIdx(index4);
          });
          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(json3.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: json3.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 column4 of columnString) {
          const [expression, isExpression, asc2, nulls, opclass] = column4.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 column4 of columnString) {
          const [expression, asc2, nulls, opclass] = column4.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: (policy3) => {
        return `${policy3.name}--${policy3.as}--${policy3.for}--${policy3.to?.join(",")}--${policy3.using}--${policy3.withCheck}--${policy3.on}`;
      },
      unsquashPolicy: (policy3) => {
        const splitted = policy3.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: (policy3) => {
        return `${policy3.name}--${policy3.as}--${policy3.for}--${policy3.to?.join(",")}--${policy3.on}`;
      },
      unsquashPolicyPush: (policy3) => {
        const splitted = policy3.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 = (json3, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json3.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index4) => {
            return action === "push" ? PgSquasher.squashIdxPush(index4) : PgSquasher.squashIdx(index4);
          });
          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, (policy3) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy3) : PgSquasher.squashPolicy(policy3);
          });
          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(json3.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(json3.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: json3.dialect,
        tables: mappedTables,
        enums: json3.enums,
        schemas: json3.schemas,
        views: json3.views,
        policies: mappedPolicies,
        sequences: mappedSequences,
        roles: json3.roles
      };
    };
    dryPg = pgSchema.parse({
      version: snapshotVersion,
      dialect: "postgresql",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/sqliteSchema.ts
var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, checkConstraint3, table3, view3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema2, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
  "src/serializer/sqliteSchema.ts"() {
    "use strict";
    init_lib();
    init_global();
    index3 = 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();
    compositePK3 = objectType({
      columns: stringType().array(),
      name: stringType().optional()
    }).strict();
    column3 = 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(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    uniqueConstraint3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint3 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    table3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
      checkConstraints: recordType(stringType(), checkConstraint3).default({})
    }).strict();
    view3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict();
    dialect2 = enumType(["sqlite"]);
    schemaHash3 = objectType({
      id: stringType(),
      prevId: stringType()
    }).strict();
    schemaInternalV32 = objectType({
      version: literalType("3"),
      dialect: dialect2,
      tables: recordType(stringType(), tableV33),
      enums: objectType({})
    }).strict();
    schemaInternalV42 = objectType({
      version: literalType("4"),
      dialect: dialect2,
      tables: recordType(stringType(), table3),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({})
    }).strict();
    schemaInternalV52 = objectType({
      version: literalType("5"),
      dialect: dialect2,
      tables: recordType(stringType(), table3),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    kitInternals3 = objectType({
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    latestVersion = literalType("6");
    schemaInternal2 = objectType({
      version: latestVersion,
      dialect: dialect2,
      tables: recordType(stringType(), table3),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    schemaV32 = schemaInternalV32.merge(schemaHash3).strict();
    schemaV42 = schemaInternalV42.merge(schemaHash3).strict();
    schemaV52 = schemaInternalV52.merge(schemaHash3).strict();
    schema2 = schemaInternal2.merge(schemaHash3).strict();
    tableSquashed3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed2 = objectType({
      version: latestVersion,
      dialect: dialect2,
      tables: recordType(stringType(), tableSquashed3),
      views: recordType(stringType(), view3),
      enums: anyType()
    }).strict();
    SQLiteSquasher = {
      squashIdx: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name2, columnsString, isUnique, where] = input.split(";");
        const result = index3.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 = (json3, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json3.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index4) => {
            return SQLiteSquasher.squashIdx(index4);
          });
          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: json3.dialect,
        tables: mappedTables,
        views: json3.views,
        enums: json3.enums
      };
    };
    drySQLite = schema2.parse({
      version: "6",
      dialect: "sqlite",
      id: originUUID,
      prevId: "",
      tables: {},
      views: {},
      enums: {},
      _meta: {
        tables: {},
        columns: {}
      }
    });
    sqliteSchemaV5 = schemaV52;
    sqliteSchema = schema2;
    SQLiteSchemaSquashed = schemaSquashed2;
    backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema2]);
  }
});

// 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_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 = (table4, schema4, column4) => {
      const out = schema4 ? `"${schema4}"."${table4}"."${column4}"` : `"${table4}"."${column4}"`;
      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 text4 = `
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")}`;
          text4 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text4 += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text4;
      }
      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 text4 = `
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}`)}`;
          text4 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text4 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text4;
      }
      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 text4 = `
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}`)}`;
          text4 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text4 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text4;
      }
      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 text4 = `
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")}`;
          text4 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text4 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text4;
      }
      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_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"(exports2, module2) {
    "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 exports2 === "object") {
          return module2.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap;
      });
    }).call(exports2);
  }
});

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

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
var require_difflib = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports2) {
    "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;
      };
      exports2._arrayCmp = _arrayCmp;
      exports2.SequenceMatcher = SequenceMatcher;
      exports2.getCloseMatches = getCloseMatches;
      exports2._countLeading = _countLeading;
      exports2.Differ = Differ;
      exports2.IS_LINE_JUNK = IS_LINE_JUNK;
      exports2.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
      exports2._formatRangeUnified = _formatRangeUnified;
      exports2.unifiedDiff = unifiedDiff;
      exports2._formatRangeContext = _formatRangeContext;
      exports2.contextDiff = contextDiff;
      exports2.ndiff = ndiff;
      exports2.restore = restore;
    }).call(exports2);
  }
});

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

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
var require_util = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports2, module2) {
    "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;
      }
    };
    module2.exports = { extendedTypeOf, roundObj };
  }
});

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

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports2, module2) {
    "use strict";
    var 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);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
var require_trap = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function runTheTrap(text4, options) {
      var result = "";
      text4 = text4 || "Run the trap, drop the bass";
      text4 = text4.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"]
      };
      text4.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"(exports2, module2) {
    "use strict";
    module2["exports"] = function zalgo(text4, options) {
      text4 = text4 || "   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(text5, 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";
        text5 = text5.split("");
        for (l in text5) {
          if (isChar(l)) {
            continue;
          }
          result = result + text5[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 index4 = arr[d];
            for (var i = 0; i <= counts[index4]; i++) {
              if (options2[index4]) {
                result = result + soul[index4][randomNumber(soul[index4].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text4, options);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
var require_america = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) {
    "use strict";
    module2["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"(exports2, module2) {
    "use strict";
    module2["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"(exports2, module2) {
    "use strict";
    module2["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"(exports2, module2) {
    "use strict";
    module2["exports"] = function(colors) {
      var available = [
        "underline",
        "inverse",
        "grey",
        "yellow",
        "red",
        "green",
        "blue",
        "white",
        "cyan",
        "magenta",
        "brightYellow",
        "brightRed",
        "brightGreen",
        "brightBlue",
        "brightWhite",
        "brightCyan",
        "brightMagenta"
      ];
      return function(letter, 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"(exports2, module2) {
    "use strict";
    var colors = {};
    module2["exports"] = colors;
    colors.themes = {};
    var util2 = require("util");
    var ansiStyles2 = colors.styles = require_styles();
    var defineProps = Object.defineProperties;
    var newLineRegex = new RegExp(/[\r\n]+/g);
    colors.supportsColor = require_supports_colors().supportsColor;
    if (typeof colors.enabled === "undefined") {
      colors.enabled = colors.supportsColor() !== false;
    }
    colors.enable = function() {
      colors.enabled = true;
    };
    colors.disable = function() {
      colors.enabled = false;
    };
    colors.stripColors = colors.strip = function(str) {
      return ("" + str).replace(/\x1B\[\d+m/g, "");
    };
    var stylize = colors.stylize = function stylize2(str, style) {
      if (!colors.enabled) {
        return str + "";
      }
      var styleMap = ansiStyles2[style];
      if (!styleMap && style in colors) {
        return colors[style](str);
      }
      return styleMap.open + str + styleMap.close;
    };
    var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
    var escapeStringRegexp = function(str) {
      if (typeof str !== "string") {
        throw new TypeError("Expected a string");
      }
      return str.replace(matchOperatorsRe, "\\$&");
    };
    function build(_styles) {
      var builder = function builder2() {
        return applyStyle2.apply(builder2, arguments);
      };
      builder._styles = _styles;
      builder.__proto__ = proto2;
      return builder;
    }
    var styles3 = function() {
      var ret = {};
      ansiStyles2.grey = ansiStyles2.gray;
      Object.keys(ansiStyles2).forEach(function(key) {
        ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
        ret[key] = {
          get: function() {
            return build(this._styles.concat(key));
          }
        };
      });
      return ret;
    }();
    var proto2 = defineProps(function colors2() {
    }, styles3);
    function applyStyle2() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.map(function(arg) {
        if (arg != null && arg.constructor === String) {
          return arg;
        } else {
          return util2.inspect(arg);
        }
      }).join(" ");
      if (!colors.enabled || !str) {
        return str;
      }
      var newLinesPresent = str.indexOf("\n") != -1;
      var nestedStyles = this._styles;
      var 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"(exports2, module2) {
    "use strict";
    var colors = require_colors();
    module2["exports"] = colors;
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
var require_colorize = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports2, module2) {
    "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("");
    };
    module2.exports = { colorize, colorizeToArray, colorizeToCallback };
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
var require_lib = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports2, module2) {
    "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, index4, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index4);
            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 index4 = 0; index4 < array2.length; index4++) {
            const item = array2[index4];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index4, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index4 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index4 = 0; index4 < array2.length; index4++) {
          const item = array2[index4];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index4] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index4 };
            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);
    }
    module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  }
});

// src/jsonDiffer.js
function diffSchemasOrTables(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffIndPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffColumns(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].columns = {
        added: addedColumns,
        deleted: deletedColumns
      };
      const table4 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table4.name, schema: table4.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 table4 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table4.name, schema: table4.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 table4 = json1.tables[key];
    difference.tables[key] = {
      name: table4.name,
      schema: table4.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table4 = 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 table4.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table4["columns"];
    }
    if ("name" in table4 && "schema" in table4 && Object.keys(table4).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: schema4, 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: schema4, 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(
    (table4) => {
      return findAlternationsInTable(table4);
    }
  );
  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 = (table4) => {
      const columns = table4.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(table4.indexes__deleted || {}).concat(
          Object.entries(table4.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table4.indexes__added || {}).concat(
          Object.entries(table4.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table4.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table4.policies__deleted || {}).concat(
          Object.entries(table4.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table4.policies__added || {}).concat(
          Object.entries(table4.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table4.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table4.foreignKeys__deleted || {}).concat(
          Object.entries(table4.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table4.foreignKeys__added || {}).concat(
          Object.entries(table4.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table4.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table4.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table4.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table4.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table4.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table4.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table4.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table4.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table4.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table4.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table4.name,
        schema: table4.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column4) => {
      const altered = [column4];
      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, dialect4, action, json22) {
  const result = statements.flatMap((statement) => {
    const filtered = convertors.filter((it) => {
      return it.can(statement, dialect4);
    });
    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, 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, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
var init_sqlgenerator = __esm({
  "src/sqlgenerator.ts"() {
    "use strict";
    init_migrate();
    init_mysqlSchema();
    init_pgSchema();
    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, dialect4) {
        return statement.type === "create_role" && dialect4 === "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, dialect4) {
        return statement.type === "drop_role" && dialect4 === "postgresql";
      }
      convert(statement) {
        return `DROP ROLE "${statement.name}";`;
      }
    };
    PgRenameRoleConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_role" && dialect4 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
      }
    };
    PgAlterRoleConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_role" && dialect4 === "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, dialect4) {
        return statement.type === "create_policy" && dialect4 === "postgresql";
      }
      convert(statement) {
        const policy3 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy3.using ? ` USING (${policy3.using})` : "";
        const withCheckPart = policy3.withCheck ? ` WITH CHECK (${policy3.withCheck})` : "";
        const policyToPart = policy3.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy3.name}" ON ${tableNameWithSchema} AS ${policy3.as?.toUpperCase()} FOR ${policy3.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_policy" && dialect4 === "postgresql";
      }
      convert(statement) {
        const policy3 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy3.name}" ON ${tableNameWithSchema} CASCADE;`;
      }
    };
    PgRenamePolicyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_policy" && dialect4 === "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, dialect4) {
        return statement.type === "alter_policy" && dialect4 === "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, dialect4) {
        return statement.type === "create_ind_policy" && dialect4 === "postgresql";
      }
      convert(statement) {
        const policy3 = statement.data;
        const usingPart = policy3.using ? ` USING (${policy3.using})` : "";
        const withCheckPart = policy3.withCheck ? ` WITH CHECK (${policy3.withCheck})` : "";
        const policyToPart = policy3.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy3.name}" ON ${policy3.on} AS ${policy3.as?.toUpperCase()} FOR ${policy3.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_ind_policy" && dialect4 === "postgresql";
      }
      convert(statement) {
        const policy3 = statement.data;
        return `DROP POLICY "${policy3.name}" ON ${policy3.on} CASCADE;`;
      }
    };
    PgRenameIndPolicyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_ind_policy" && dialect4 === "postgresql";
      }
      convert(statement) {
        return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterIndPolicyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_ind_policy" && dialect4 === "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, dialect4) {
        return statement.type === "enable_rls" && dialect4 === "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, dialect4) {
        return statement.type === "disable_rls" && dialect4 === "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, dialect4) {
        return statement.type === "create_table" && dialect4 === "postgresql";
      }
      convert(st) {
        const { tableName, schema: schema4, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
        let statement = "";
        const name2 = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        statement += `CREATE TABLE IF NOT EXISTS ${name2} (
`;
        for (let i = 0; i < columns.length; i++) {
          const column4 = columns[i];
          const primaryKeyStatement = column4.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column4.notNull && !column4.identity ? " NOT NULL" : "";
          const defaultStatement = column4.default !== void 0 ? ` DEFAULT ${column4.default}` : "";
          const uniqueConstraint4 = column4.isUnique ? ` CONSTRAINT "${column4.uniqueName}" UNIQUE${column4.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column4.typeSchema && column4.typeSchema !== "public" ? `"${column4.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column4.type);
          const generated = column4.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
          const unsquashedIdentity = column4.identity ? PgSquasher.unsquashIdentity(column4.identity) : void 0;
          const identityWithSchema = schema4 ? `"${schema4}"."${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 += `	"${column4.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint4}${identity}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK4 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK4.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint4 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint4);
            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: schema4
        });
        return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
      }
    };
    MySqlCreateTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_table" && dialect4 === "mysql";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema4,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column4 = columns[i];
          const primaryKeyStatement = column4.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column4.notNull ? " NOT NULL" : "";
          const defaultStatement = column4.default !== void 0 ? ` DEFAULT ${column4.default}` : "";
          const onUpdateStatement = column4.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column4.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column4.generated ? ` GENERATED ALWAYS AS (${column4.generated?.as}) ${column4.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column4.name}\` ${column4.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK4 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK4.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint4 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint4);
            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;
      }
    };
    SQLiteCreateTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "sqlite_create_table" && (dialect4 === "sqlite" || dialect4 === "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 column4 = columns[i];
          const primaryKeyStatement = column4.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column4.notNull ? " NOT NULL" : "";
          const defaultStatement = column4.default !== void 0 ? ` DEFAULT ${column4.default}` : "";
          const autoincrementStatement = column4.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column4.generated ? ` GENERATED ALWAYS AS ${column4.generated.as} ${column4.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column4.name}\` ${column4.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 uniqueConstraint4 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint4);
            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, dialect4) {
        return statement.type === "create_view" && dialect4 === "postgresql";
      }
      convert(st) {
        const { definition, name: viewName, schema: schema4, with: withOption, materialized, withNoData, tablespace, using } = st;
        const name2 = schema4 ? `"${schema4}"."${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, dialect4) {
        return statement.type === "mysql_create_view" && dialect4 === "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, dialect4) {
        return statement.type === "sqlite_create_view" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(st) {
        const { definition, name: name2 } = st;
        return `CREATE VIEW \`${name2}\` AS ${definition};`;
      }
    };
    PgDropViewConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_view" && dialect4 === "postgresql";
      }
      convert(st) {
        const { name: viewName, schema: schema4, materialized } = st;
        const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
        return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
      }
    };
    MySqlDropViewConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_view" && dialect4 === "mysql";
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    SqliteDropViewConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_view" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    MySqlAlterViewConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_mysql_view" && dialect4 === "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, dialect4) {
        return statement.type === "rename_view" && dialect4 === "postgresql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to, schema: schema4, materialized } = st;
        const nameFrom = `"${schema4}"."${from}"`;
        return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
      }
    };
    MySqlRenameViewConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_view" && dialect4 === "mysql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to } = st;
        return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
      }
    };
    PgAlterViewSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_view_alter_schema" && dialect4 === "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, dialect4) {
        return statement.type === "alter_view_add_with_option" && dialect4 === "postgresql";
      }
      convert(st) {
        const { schema: schema4, with: withOption, name: name2, materialized } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${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, dialect4) {
        return statement.type === "alter_view_drop_with_option" && dialect4 === "postgresql";
      }
      convert(st) {
        const { schema: schema4, name: name2, materialized, with: withOptions } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${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, dialect4) {
        return statement.type === "alter_view_alter_tablespace" && dialect4 === "postgresql";
      }
      convert(st) {
        const { schema: schema4, name: name2, toTablespace } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET TABLESPACE ${toTablespace};`;
        return statement;
      }
    };
    PgAlterViewAlterUsingConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_view_alter_using" && dialect4 === "postgresql";
      }
      convert(st) {
        const { schema: schema4, name: name2, toUsing } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET ACCESS METHOD "${toUsing}";`;
        return statement;
      }
    };
    PgAlterTableAlterColumnSetGenerated = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_set_identity" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { identity, tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const identityWithSchema = schema4 ? `"${schema4}"."${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, dialect4) {
        return statement.type === "alter_table_alter_column_drop_identity" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
      }
    };
    PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_change_identity" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { identity, oldIdentity, tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${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, dialect4) {
        return statement.type === "create_unique_constraint" && dialect4 === "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, dialect4) {
        return statement.type === "delete_unique_constraint" && dialect4 === "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, dialect4) {
        return statement.type === "create_check_constraint" && dialect4 === "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, dialect4) {
        return statement.type === "delete_check_constraint" && dialect4 === "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, dialect4) {
        return statement.type === "create_unique_constraint" && dialect4 === "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, dialect4) {
        return statement.type === "delete_unique_constraint" && dialect4 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_check_constraint" && dialect4 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
      }
    };
    MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "delete_check_constraint" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
      }
    };
    CreatePgSequenceConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_sequence" && dialect4 === "postgresql";
      }
      convert(st) {
        const { name: name2, values, schema: schema4 } = st;
        const sequenceWithSchema = schema4 ? `"${schema4}"."${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, dialect4) {
        return statement.type === "drop_sequence" && dialect4 === "postgresql";
      }
      convert(st) {
        const { name: name2, schema: schema4 } = st;
        const sequenceWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
        return `DROP SEQUENCE ${sequenceWithSchema};`;
      }
    };
    RenamePgSequenceConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_sequence" && dialect4 === "postgresql";
      }
      convert(st) {
        const { nameFrom, nameTo, schema: schema4 } = st;
        const sequenceWithSchemaFrom = schema4 ? `"${schema4}"."${nameFrom}"` : `"${nameFrom}"`;
        const sequenceWithSchemaTo = schema4 ? `"${schema4}"."${nameTo}"` : `"${nameTo}"`;
        return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
      }
    };
    MovePgSequenceConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "move_sequence" && dialect4 === "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, dialect4) {
        return statement.type === "alter_sequence" && dialect4 === "postgresql";
      }
      convert(st) {
        const { name: name2, schema: schema4, values } = st;
        const { increment, minValue, maxValue, startWith, cache, cycle } = values;
        const sequenceWithSchema = schema4 ? `"${schema4}"."${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: schema4 } = st;
        const enumNameWithSchema = schema4 ? `"${schema4}"."${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: schema4 } = st;
        const enumNameWithSchema = schema4 ? `"${schema4}"."${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: schema4, value, before } = st;
        const enumNameWithSchema = schema4 ? `"${schema4}"."${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: schema4 } = st;
        const enumNameWithSchema = schema4 ? `"${schema4}"."${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: schema4 } = 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: schema4, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name: name2,
          schema: schema4,
          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 "${schema4}"."${name2}" USING "${withEnum.column}"::"${schema4}"."${name2}";`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_table" && dialect4 === "postgresql";
      }
      convert(statement, _d5, action) {
        const { tableName, schema: schema4, policies } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${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: schema4
          });
        }) ?? [];
        return [
          ...droppedPolicies,
          `DROP TABLE ${tableNameWithSchema} CASCADE;`
        ];
      }
    };
    MySQLDropTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_table" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SQLiteDropTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_table" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    PgRenameTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_table" && dialect4 === "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, dialect4) {
        return statement.type === "rename_table" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    MySqlRenameTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_table" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
      }
    };
    PgAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_rename_column" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    MySqlAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_rename_column" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
      }
    };
    SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_rename_column" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    PgAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_drop_column" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN IF EXISTS "${columnName}";`;
      }
    };
    MySqlAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_drop_column" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SQLiteAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_drop_column" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    PgAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_add_column" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, column: column4, schema: schema4 } = statement;
        const { name: name2, type, notNull, generated, primaryKey, identity } = column4;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column4.default !== void 0 ? ` DEFAULT ${column4.default}` : ""}`;
        const schemaPrefix = column4.typeSchema && column4.typeSchema !== "public" ? `"${column4.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column4.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema4 ? `"${schema4}"."${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, dialect4) {
        return statement.type === "alter_table_add_column" && dialect4 === "mysql";
      }
      convert(statement) {
        const { tableName, column: column4 } = statement;
        const {
          name: name2,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column4;
        const defaultStatement = `${column4.default !== void 0 ? ` DEFAULT ${column4.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};`;
      }
    };
    SQLiteAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "sqlite_alter_table_add_column" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { tableName, column: column4, referenceData } = statement;
        const { name: name2, type, notNull, primaryKey, generated } = column4;
        const defaultStatement = `${column4.default !== void 0 ? ` DEFAULT ${column4.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, dialect4) {
        return statement.type === "alter_table_alter_column_set_type" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${newDataType};`;
      }
    };
    PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_set_default" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
      }
    };
    PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_drop_default" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
      }
    };
    PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_drop_generated" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
      }
    };
    PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_set_generated" && dialect4 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema4,
          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, dialect4) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect4 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema4,
          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, dialect4) {
        return statement.type === "alter_table_alter_column_drop_generated" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          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: schema4,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_set_generated" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          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: schema4,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_alter_generated" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          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: schema4,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect4 === "mysql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema4,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema4 ? `\`${schema4}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
          schema: schema4,
          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, dialect4) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect4 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    MySqlAlterTableDropPk = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect4 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    LibSQLModifyColumn = class extends Convertor {
      can(statement, dialect4) {
        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") && dialect4 === "turso";
      }
      convert(statement, json22) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        const sqlStatements = [];
        const indexes = [];
        for (const table4 of Object.values(json22.tables)) {
          for (const index4 of Object.values(table4.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index4);
            sqlStatements.push(`DROP INDEX IF EXISTS "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table4.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 index4 of indexes) {
          const indexPart = index4.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index4.where ? ` WHERE ${index4.where}` : "";
          const uniqueString = index4.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index4.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index4.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
          );
        }
        return sqlStatements;
      }
    };
    MySqlModifyColumn = class extends Convertor {
      can(statement, dialect4) {
        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") && dialect4 === "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};`;
      }
    };
    PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_composite_pk" && dialect4 === "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, dialect4) {
        return statement.type === "delete_composite_pk" && dialect4 === "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, dialect4) {
        return statement.type === "alter_composite_pk" && dialect4 === "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}"`;
        console.log(statement.oldConstraintName, statement.newConstraintName);
        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, dialect4) {
        return statement.type === "create_composite_pk" && dialect4 === "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, dialect4) {
        return statement.type === "delete_composite_pk" && dialect4 === "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, dialect4) {
        return statement.type === "alter_composite_pk" && dialect4 === "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, dialect4) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect4 === "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, dialect4) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema4 } = 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 schema4 === "undefined" || schema4 === "" ? "public" : schema4}'
                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, dialect4) {
        return statement.type === "alter_table_alter_column_set_notnull" && dialect4 === "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, dialect4) {
        return statement.type === "alter_table_alter_column_drop_notnull" && dialect4 === "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, dialect4) {
        return statement.type === "create_reference" && dialect4 === "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}`;
        let sql2 = "DO $$ BEGIN\n";
        sql2 += " " + alterStatement + ";\n";
        sql2 += "EXCEPTION\n";
        sql2 += " WHEN duplicate_object THEN null;\n";
        sql2 += "END $$;\n";
        return sql2;
      }
    };
    LibSQLCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_reference" && dialect4 === "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, dialect4) {
        return statement.type === "create_reference" && dialect4 === "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, dialect4) {
        return statement.type === "alter_reference" && dialect4 === "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 += "DO $$ BEGIN\n";
        sql2 += " " + alterStatement + ";\n";
        sql2 += "EXCEPTION\n";
        sql2 += " WHEN duplicate_object THEN null;\n";
        sql2 += "END $$;\n";
        return sql2;
      }
    };
    PgDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "delete_reference" && dialect4 === "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 Convertor {
      can(statement, dialect4) {
        return statement.type === "delete_reference" && dialect4 === "mysql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name: name2 } = MySqlSquasher.unsquashFK(statement.data);
        return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name2}\`;
`;
      }
    };
    CreatePgIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_index_pg" && dialect4 === "postgresql";
      }
      convert(statement) {
        const {
          name: name2,
          columns,
          isUnique,
          concurrently,
          with: withMap,
          method,
          where
        } = statement.data;
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const value = columns.map(
          (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
        ).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        function reverseLogic(mappedWith) {
          let reversedString = "";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}=${mappedWith[key]},`;
            }
          }
          reversedString = reversedString.slice(0, -1);
          return reversedString;
        }
        return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} IF NOT EXISTS "${name2}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
      }
    };
    CreateMySqlIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_index" && dialect4 === "mysql";
      }
      convert(statement) {
        const { name: name2, columns, isUnique } = MySqlSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name2]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name2}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSqliteIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_index" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { name: name2, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const whereStatement = where ? ` WHERE ${where}` : "";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name2]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name2}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
      }
    };
    PgDropIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_index" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { name: name2 } = PgSquasher.unsquashIdx(statement.data);
        return `DROP INDEX IF EXISTS "${name2}";`;
      }
    };
    PgCreateSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "create_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { name: name2 } = statement;
        return `CREATE SCHEMA "${name2}";
`;
      }
    };
    PgRenameSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "rename_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { from, to } = statement;
        return `ALTER SCHEMA "${from}" RENAME TO "${to}";
`;
      }
    };
    PgDropSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { name: name2 } = statement;
        return `DROP SCHEMA "${name2}";
`;
      }
    };
    PgAlterTableSetSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_set_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, schemaFrom, schemaTo } = statement;
        return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
`;
      }
    };
    PgAlterTableSetNewSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_set_new_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, to, from } = statement;
        const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
`;
      }
    };
    PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "alter_table_remove_from_schema" && dialect4 === "postgresql";
      }
      convert(statement) {
        const { tableName, schema: schema4 } = statement;
        const tableNameWithSchema = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
`;
      }
    };
    SqliteDropIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_index" && (dialect4 === "sqlite" || dialect4 === "turso");
      }
      convert(statement) {
        const { name: name2 } = PgSquasher.unsquashIdx(statement.data);
        return `DROP INDEX IF EXISTS \`${name2}\`;`;
      }
    };
    MySqlDropIndexConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "drop_index" && dialect4 === "mysql";
      }
      convert(statement) {
        const { name: name2 } = MySqlSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name2}\` ON \`${statement.tableName}\`;`;
      }
    };
    SQLiteRecreateTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "recreate_table" && dialect4 === "sqlite";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
        );
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    LibSQLRecreateTableConvertor = class extends Convertor {
      can(statement, dialect4) {
        return statement.type === "recreate_table" && dialect4 === "turso";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
        );
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    convertors = [];
    convertors.push(new PgCreateTableConvertor());
    convertors.push(new MySqlCreateTableConvertor());
    convertors.push(new SQLiteCreateTableConvertor());
    convertors.push(new SQLiteRecreateTableConvertor());
    convertors.push(new LibSQLRecreateTableConvertor());
    convertors.push(new PgCreateViewConvertor());
    convertors.push(new PgDropViewConvertor());
    convertors.push(new PgRenameViewConvertor());
    convertors.push(new PgAlterViewSchemaConvertor());
    convertors.push(new PgAlterViewAddWithOptionConvertor());
    convertors.push(new PgAlterViewDropWithOptionConvertor());
    convertors.push(new PgAlterViewAlterTablespaceConvertor());
    convertors.push(new PgAlterViewAlterUsingConvertor());
    convertors.push(new MySqlCreateViewConvertor());
    convertors.push(new MySqlDropViewConvertor());
    convertors.push(new MySqlRenameViewConvertor());
    convertors.push(new MySqlAlterViewConvertor());
    convertors.push(new SqliteCreateViewConvertor());
    convertors.push(new SqliteDropViewConvertor());
    convertors.push(new CreateTypeEnumConvertor());
    convertors.push(new DropTypeEnumConvertor());
    convertors.push(new AlterTypeAddValueConvertor());
    convertors.push(new AlterTypeSetSchemaConvertor());
    convertors.push(new AlterRenameTypeConvertor());
    convertors.push(new AlterTypeDropValueConvertor());
    convertors.push(new CreatePgSequenceConvertor());
    convertors.push(new DropPgSequenceConvertor());
    convertors.push(new RenamePgSequenceConvertor());
    convertors.push(new MovePgSequenceConvertor());
    convertors.push(new AlterPgSequenceConvertor());
    convertors.push(new PgDropTableConvertor());
    convertors.push(new MySQLDropTableConvertor());
    convertors.push(new SQLiteDropTableConvertor());
    convertors.push(new PgRenameTableConvertor());
    convertors.push(new MySqlRenameTableConvertor());
    convertors.push(new SqliteRenameTableConvertor());
    convertors.push(new PgAlterTableRenameColumnConvertor());
    convertors.push(new MySqlAlterTableRenameColumnConvertor());
    convertors.push(new SQLiteAlterTableRenameColumnConvertor());
    convertors.push(new PgAlterTableDropColumnConvertor());
    convertors.push(new MySqlAlterTableDropColumnConvertor());
    convertors.push(new SQLiteAlterTableDropColumnConvertor());
    convertors.push(new PgAlterTableAddColumnConvertor());
    convertors.push(new MySqlAlterTableAddColumnConvertor());
    convertors.push(new SQLiteAlterTableAddColumnConvertor());
    convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
    convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
    convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
    convertors.push(new PgAlterTableAddCheckConstraintConvertor());
    convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
    convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
    convertors.push(new CreatePgIndexConvertor());
    convertors.push(new CreateMySqlIndexConvertor());
    convertors.push(new CreateSqliteIndexConvertor());
    convertors.push(new PgDropIndexConvertor());
    convertors.push(new SqliteDropIndexConvertor());
    convertors.push(new MySqlDropIndexConvertor());
    convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
    convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
    convertors.push(new PgAlterPolicyConvertor());
    convertors.push(new PgCreatePolicyConvertor());
    convertors.push(new PgDropPolicyConvertor());
    convertors.push(new PgRenamePolicyConvertor());
    convertors.push(new PgAlterIndPolicyConvertor());
    convertors.push(new PgCreateIndPolicyConvertor());
    convertors.push(new PgDropIndPolicyConvertor());
    convertors.push(new PgRenameIndPolicyConvertor());
    convertors.push(new PgEnableRlsConvertor());
    convertors.push(new PgDisableRlsConvertor());
    convertors.push(new PgDropRoleConvertor());
    convertors.push(new PgAlterRoleConvertor());
    convertors.push(new PgCreateRoleConvertor());
    convertors.push(new PgRenameRoleConvertor());
    convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new MySqlModifyColumn());
    convertors.push(new LibSQLModifyColumn());
    convertors.push(new PgCreateForeignKeyConvertor());
    convertors.push(new MySqlCreateForeignKeyConvertor());
    convertors.push(new PgAlterForeignKeyConvertor());
    convertors.push(new PgDeleteForeignKeyConvertor());
    convertors.push(new MySqlDeleteForeignKeyConvertor());
    convertors.push(new PgCreateSchemaConvertor());
    convertors.push(new PgRenameSchemaConvertor());
    convertors.push(new PgDropSchemaConvertor());
    convertors.push(new PgAlterTableSetSchemaConvertor());
    convertors.push(new PgAlterTableSetNewSchemaConvertor());
    convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
    convertors.push(new LibSQLCreateForeignKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGenerated());
    convertors.push(new PgAlterTableAlterColumnSetGenerated());
    convertors.push(new PgAlterTableAlterColumnAlterGenerated());
    convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDropPk());
    convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableAddPk());
    convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
    https: `
create table users (
	id int,
    name character varying(128)
);

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

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

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

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

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

drop type __venum;
`;
  }
});

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

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

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

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

// src/utils/words.ts
var init_words = __esm({
  "src/utils/words.ts"() {
    "use strict";
  }
});

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

// src/cli/validations/common.ts
var sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema;
var init_common = __esm({
  "src/cli/validations/common.ts"() {
    "use strict";
    init_lib();
    init_schemaValidator();
    init_outputs();
    sqliteDriversLiterals = [
      literalType("d1-http"),
      literalType("expo")
    ];
    postgresqlDriversLiterals = [
      literalType("aws-data-api"),
      literalType("pglite")
    ];
    prefixes = [
      "index",
      "timestamp",
      "supabase",
      "unix",
      "none"
    ];
    prefix = enumType(prefixes);
    {
      const _2 = "";
    }
    casingTypes = ["snake_case", "camelCase"];
    casingType = enumType(casingTypes);
    sqliteDriver = unionType(sqliteDriversLiterals);
    postgresDriver = unionType(postgresqlDriversLiterals);
    driver = unionType([sqliteDriver, postgresDriver]);
    configMigrations = objectType({
      table: stringType().optional(),
      schema: stringType().optional(),
      prefix: prefix.optional().default("index")
    }).optional();
    configCommonSchema = objectType({
      dialect: dialect3,
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional(),
      breakpoints: booleanType().optional().default(true),
      verbose: booleanType().optional().default(false),
      driver: driver.optional(),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      migrations: configMigrations,
      dbCredentials: anyType().optional(),
      casing: casingType.optional()
    }).passthrough();
    casing = unionType([literalType("camel"), literalType("preserve")]).default(
      "camel"
    );
    introspectParams = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspect: objectType({
        casing
      }).default({ casing: "camel" })
    });
    configIntrospectCliSchema = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
        "camel"
      )
    });
    configGenerateSchema = objectType({
      schema: unionType([stringType(), stringType().array()]),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true)
    });
    configPushSchema = objectType({
      dialect: dialect3,
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      verbose: booleanType().default(false),
      strict: booleanType().default(false),
      out: stringType().optional()
    });
  }
});

// src/cli/validations/outputs.ts
var withStyle;
var init_outputs = __esm({
  "src/cli/validations/outputs.ts"() {
    "use strict";
    init_source();
    init_common();
    withStyle = {
      error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
      warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
      errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
      fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
      suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
      info: (str) => `${source_default.grey(str)}`
    };
  }
});

// src/cli/commands/migrate.ts
var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
var init_migrate = __esm({
  "src/cli/commands/migrate.ts"() {
    "use strict";
    init_migrationPreparator();
    init_source();
    import_hanji2 = __toESM(require_hanji());
    init_mysqlSchema();
    init_pgSchema();
    init_sqliteSchema();
    init_snapshotsDiffer();
    init_utils();
    init_words();
    init_outputs();
    init_views();
    schemasResolver = async (input) => {
      try {
        const { created, deleted, renamed } = await promptSchemasConflict(
          input.created,
          input.deleted
        );
        return { created, deleted, renamed };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    tablesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "table"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    viewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    mySqlViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    sqliteViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    sequencesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "sequence"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    roleResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "role"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    policyResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    indPolicyResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "policy"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    enumsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "enum"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    columnsResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
      if (newColumns.length === 0 || missingColumns.length === 0) {
        return { created: newColumns, renamed: [], deleted: missingColumns };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index4 = 0;
      let leftMissing = [...missingColumns];
      do {
        const created = newColumns[index4];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveColumnSelect(tableName, created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "column will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "column will be created"
            )}`
          );
          result.created.push(created);
        }
        index4 += 1;
      } while (index4 < newColumns.length);
      console.log(
        source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
`)
      );
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], deleted: [] };
      let index4 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index4];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelectNamed(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index4 += 1;
      } while (index4 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          moved: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], moved: [], deleted: [] };
      let index4 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index4];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelect(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
          const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
          console.log(
            `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          if (data.from.schema !== data.to.schema) {
            result.moved.push({
              name: data.from.name,
              schemaFrom: data.from.schema || "public",
              schemaTo: data.to.schema || "public"
            });
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index4 += 1;
      } while (index4 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptSchemasConflict = async (newSchemas, missingSchemas) => {
      if (missingSchemas.length === 0 || newSchemas.length === 0) {
        return { created: newSchemas, renamed: [], deleted: missingSchemas };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index4 = 0;
      let leftMissing = [...missingSchemas];
      do {
        const created = newSchemas[index4];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSchemasSelect(created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "schema will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "schema will be created"
            )}`
          );
          result.created.push(created);
        }
        index4 += 1;
      } while (index4 < newSchemas.length);
      console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
      result.deleted.push(...leftMissing);
      return result;
    };
    BREAKPOINT = "--> statement-breakpoint\n";
  }
});

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

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

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

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

// ../drizzle-orm/dist/entity.js
function is(value, type) {
  if (!value || typeof value !== "object") {
    return false;
  }
  if (value instanceof type) {
    return true;
  }
  if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
    throw new Error(
      `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
    );
  }
  let cls = Object.getPrototypeOf(value).constructor;
  if (cls) {
    while (cls) {
      if (entityKind in cls && cls[entityKind] === type[entityKind]) {
        return true;
      }
      cls = Object.getPrototypeOf(cls);
    }
  }
  return false;
}
var entityKind, hasOwnEntityKind;
var init_entity = __esm({
  "../drizzle-orm/dist/entity.js"() {
    "use strict";
    entityKind = Symbol.for("drizzle:entityKind");
    hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
  }
});

// ../drizzle-orm/dist/column.js
var _a, Column2;
var init_column = __esm({
  "../drizzle-orm/dist/column.js"() {
    "use strict";
    init_entity();
    _a = entityKind;
    Column2 = class {
      constructor(table4, config) {
        __publicField(this, "name");
        __publicField(this, "keyAsName");
        __publicField(this, "primary");
        __publicField(this, "notNull");
        __publicField(this, "default");
        __publicField(this, "defaultFn");
        __publicField(this, "onUpdateFn");
        __publicField(this, "hasDefault");
        __publicField(this, "isUnique");
        __publicField(this, "uniqueName");
        __publicField(this, "uniqueType");
        __publicField(this, "dataType");
        __publicField(this, "columnType");
        __publicField(this, "enumValues");
        __publicField(this, "generated");
        __publicField(this, "generatedIdentity");
        __publicField(this, "config");
        this.table = table4;
        this.config = config;
        this.name = config.name;
        this.keyAsName = config.keyAsName;
        this.notNull = config.notNull;
        this.default = config.default;
        this.defaultFn = config.defaultFn;
        this.onUpdateFn = config.onUpdateFn;
        this.hasDefault = config.hasDefault;
        this.primary = config.primaryKey;
        this.isUnique = config.isUnique;
        this.uniqueName = config.uniqueName;
        this.uniqueType = config.uniqueType;
        this.dataType = config.dataType;
        this.columnType = config.columnType;
        this.generated = config.generated;
        this.generatedIdentity = config.generatedIdentity;
      }
      mapFromDriverValue(value) {
        return value;
      }
      mapToDriverValue(value) {
        return value;
      }
      // ** @internal */
      shouldDisableInsert() {
        return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
      }
    };
    __publicField(Column2, _a, "Column");
  }
});

// ../drizzle-orm/dist/column-builder.js
var _a2, ColumnBuilder;
var init_column_builder = __esm({
  "../drizzle-orm/dist/column-builder.js"() {
    "use strict";
    init_entity();
    _a2 = entityKind;
    ColumnBuilder = class {
      constructor(name2, dataType, columnType) {
        __publicField(this, "config");
        /**
         * Alias for {@link $defaultFn}.
         */
        __publicField(this, "$default", this.$defaultFn);
        /**
         * Alias for {@link $onUpdateFn}.
         */
        __publicField(this, "$onUpdate", this.$onUpdateFn);
        this.config = {
          name: name2,
          keyAsName: name2 === "",
          notNull: false,
          default: void 0,
          hasDefault: false,
          primaryKey: false,
          isUnique: false,
          uniqueName: void 0,
          uniqueType: void 0,
          dataType,
          columnType,
          generated: void 0
        };
      }
      /**
       * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
       *
       * @example
       * ```ts
       * const users = pgTable('users', {
       * 	id: integer('id').$type<UserId>().primaryKey(),
       * 	details: json('details').$type<UserDetails>().notNull(),
       * });
       * ```
       */
      $type() {
        return this;
      }
      /**
       * Adds a `not null` clause to the column definition.
       *
       * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
       */
      notNull() {
        this.config.notNull = true;
        return this;
      }
      /**
       * Adds a `default <value>` clause to the column definition.
       *
       * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
       *
       * If you need to set a dynamic default value, use {@link $defaultFn} instead.
       */
      default(value) {
        this.config.default = value;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a dynamic default value to the column.
       * The function will be called when the row is inserted, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $defaultFn(fn) {
        this.config.defaultFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a dynamic update value to the column.
       * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
       * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $onUpdateFn(fn) {
        this.config.onUpdateFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
       *
       * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
       */
      primaryKey() {
        this.config.primaryKey = true;
        this.config.notNull = true;
        return this;
      }
      /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
      setName(name2) {
        if (this.config.name !== "")
          return;
        this.config.name = name2;
      }
    };
    __publicField(ColumnBuilder, _a2, "ColumnBuilder");
  }
});

// ../drizzle-orm/dist/table.utils.js
var TableName;
var init_table_utils = __esm({
  "../drizzle-orm/dist/table.utils.js"() {
    "use strict";
    TableName = Symbol.for("drizzle:Name");
  }
});

// ../drizzle-orm/dist/pg-core/foreign-keys.js
var _a3, ForeignKeyBuilder, _a4, ForeignKey;
var init_foreign_keys = __esm({
  "../drizzle-orm/dist/pg-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a3 = entityKind;
    ForeignKeyBuilder = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate", "no action");
        /** @internal */
        __publicField(this, "_onDelete", "no action");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action === void 0 ? "no action" : action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action === void 0 ? "no action" : action;
        return this;
      }
      /** @internal */
      build(table4) {
        return new ForeignKey(table4, this);
      }
    };
    __publicField(ForeignKeyBuilder, _a3, "PgForeignKeyBuilder");
    _a4 = entityKind;
    ForeignKey = class {
      constructor(table4, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table4;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column4) => column4.name);
        const foreignColumnNames = foreignColumns.map((column4) => column4.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey, _a4, "PgForeignKey");
  }
});

// ../drizzle-orm/dist/tracing-utils.js
function iife(fn, ...args) {
  return fn(...args);
}
var init_tracing_utils = __esm({
  "../drizzle-orm/dist/tracing-utils.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/unique-constraint.js
function uniqueKeyName(table4, columns) {
  return `${table4[TableName]}_${columns.join("_")}_unique`;
}
var _a5, UniqueConstraintBuilder, _a6, UniqueOnConstraintBuilder, _a7, UniqueConstraint;
var init_unique_constraint = __esm({
  "../drizzle-orm/dist/pg-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a5 = entityKind;
    UniqueConstraintBuilder = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "nullsNotDistinctConfig", false);
        this.name = name2;
        this.columns = columns;
      }
      nullsNotDistinct() {
        this.nullsNotDistinctConfig = true;
        return this;
      }
      /** @internal */
      build(table4) {
        return new UniqueConstraint(table4, this.columns, this.nullsNotDistinctConfig, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder, _a5, "PgUniqueConstraintBuilder");
    _a6 = entityKind;
    UniqueOnConstraintBuilder = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder, _a6, "PgUniqueOnConstraintBuilder");
    _a7 = entityKind;
    UniqueConstraint = class {
      constructor(table4, columns, nullsNotDistinct, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        __publicField(this, "nullsNotDistinct", false);
        this.table = table4;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName(this.table, this.columns.map((column4) => column4.name));
        this.nullsNotDistinct = nullsNotDistinct;
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint, _a7, "PgUniqueConstraint");
  }
});

// ../drizzle-orm/dist/pg-core/utils/array.js
function parsePgArrayValue(arrayString, startFrom, inQuotes) {
  for (let i = startFrom; i < arrayString.length; i++) {
    const char3 = arrayString[i];
    if (char3 === "\\") {
      i++;
      continue;
    }
    if (char3 === '"') {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
    }
    if (inQuotes) {
      continue;
    }
    if (char3 === "," || char3 === "}") {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
    }
  }
  return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
}
function parsePgNestedArray(arrayString, startFrom = 0) {
  const result = [];
  let i = startFrom;
  let lastCharIsComma = false;
  while (i < arrayString.length) {
    const char3 = arrayString[i];
    if (char3 === ",") {
      if (lastCharIsComma || i === startFrom) {
        result.push("");
      }
      lastCharIsComma = true;
      i++;
      continue;
    }
    lastCharIsComma = false;
    if (char3 === "\\") {
      i += 2;
      continue;
    }
    if (char3 === '"') {
      const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    if (char3 === "}") {
      return [result, i + 1];
    }
    if (char3 === "{") {
      const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
    result.push(value);
    i = newStartFrom;
  }
  return [result, i];
}
function parsePgArray(arrayString) {
  const [result] = parsePgNestedArray(arrayString, 1);
  return result;
}
function makePgArray(array2) {
  return `{${array2.map((item) => {
    if (Array.isArray(item)) {
      return makePgArray(item);
    }
    if (typeof item === "string") {
      return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    return `${item}`;
  }).join(",")}}`;
}
var init_array = __esm({
  "../drizzle-orm/dist/pg-core/utils/array.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/columns/common.js
var _a8, _b, PgColumnBuilder, _a9, _b2, PgColumn, _a10, _b3, ExtraConfigColumn, _a11, IndexedColumn, _a12, _b4, PgArrayBuilder, _a13, _b5, _PgArray, PgArray;
var init_common2 = __esm({
  "../drizzle-orm/dist/pg-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys();
    init_tracing_utils();
    init_unique_constraint();
    init_array();
    PgColumnBuilder = class extends (_b = ColumnBuilder, _a8 = entityKind, _b) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      array(size) {
        return new PgArrayBuilder(this.config.name, this, size);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2, config) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        this.config.uniqueType = config?.nulls;
        return this;
      }
      generatedAlwaysAs(as) {
        this.config.generated = {
          as,
          type: "always",
          mode: "stored"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column4, table4) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return iife(
            (ref2, actions2) => {
              const builder = new ForeignKeyBuilder(() => {
                const foreignColumn = ref2();
                return { columns: [column4], foreignColumns: [foreignColumn] };
              });
              if (actions2.onUpdate) {
                builder.onUpdate(actions2.onUpdate);
              }
              if (actions2.onDelete) {
                builder.onDelete(actions2.onDelete);
              }
              return builder.build(table4);
            },
            ref,
            actions
          );
        });
      }
      /** @internal */
      buildExtraConfigColumn(table4) {
        return new ExtraConfigColumn(table4, this.config);
      }
    };
    __publicField(PgColumnBuilder, _a8, "PgColumnBuilder");
    PgColumn = class extends (_b2 = Column2, _a9 = entityKind, _b2) {
      constructor(table4, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName(table4, [config.name]);
        }
        super(table4, config);
        this.table = table4;
      }
    };
    __publicField(PgColumn, _a9, "PgColumn");
    ExtraConfigColumn = class extends (_b3 = PgColumn, _a10 = entityKind, _b3) {
      constructor() {
        super(...arguments);
        __publicField(this, "indexConfig", {
          order: this.config.order ?? "asc",
          nulls: this.config.nulls ?? "last",
          opClass: this.config.opClass
        });
        __publicField(this, "defaultConfig", {
          order: "asc",
          nulls: "last",
          opClass: void 0
        });
      }
      getSQLType() {
        return this.getSQLType();
      }
      asc() {
        this.indexConfig.order = "asc";
        return this;
      }
      desc() {
        this.indexConfig.order = "desc";
        return this;
      }
      nullsFirst() {
        this.indexConfig.nulls = "first";
        return this;
      }
      nullsLast() {
        this.indexConfig.nulls = "last";
        return this;
      }
      /**
       * ### PostgreSQL documentation quote
       *
       * > An operator class with optional parameters can be specified for each column of an index.
       * The operator class identifies the operators to be used by the index for that column.
       * For example, a B-tree index on four-byte integers would use the int4_ops class;
       * this operator class includes comparison functions for four-byte integers.
       * In practice the default operator class for the column's data type is usually sufficient.
       * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
       * For example, we might want to sort a complex-number data type either by absolute value or by real part.
       * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
       * More information about operator classes check:
       *
       * ### Useful links
       * https://www.postgresql.org/docs/current/sql-createindex.html
       *
       * https://www.postgresql.org/docs/current/indexes-opclass.html
       *
       * https://www.postgresql.org/docs/current/xindex.html
       *
       * ### Additional types
       * If you have the `pg_vector` extension installed in your database, you can use the
       * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
       *
       * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
       *
       * @param opClass
       * @returns
       */
      op(opClass) {
        this.indexConfig.opClass = opClass;
        return this;
      }
    };
    __publicField(ExtraConfigColumn, _a10, "ExtraConfigColumn");
    _a11 = entityKind;
    IndexedColumn = class {
      constructor(name2, keyAsName, type, indexConfig) {
        __publicField(this, "name");
        __publicField(this, "keyAsName");
        __publicField(this, "type");
        __publicField(this, "indexConfig");
        this.name = name2;
        this.keyAsName = keyAsName;
        this.type = type;
        this.indexConfig = indexConfig;
      }
    };
    __publicField(IndexedColumn, _a11, "IndexedColumn");
    PgArrayBuilder = class extends (_b4 = PgColumnBuilder, _a12 = entityKind, _b4) {
      constructor(name2, baseBuilder, size) {
        super(name2, "array", "PgArray");
        this.config.baseBuilder = baseBuilder;
        this.config.size = size;
      }
      /** @internal */
      build(table4) {
        const baseColumn = this.config.baseBuilder.build(table4);
        return new PgArray(
          table4,
          this.config,
          baseColumn
        );
      }
    };
    __publicField(PgArrayBuilder, _a12, "PgArrayBuilder");
    _PgArray = class _PgArray extends (_b5 = PgColumn, _a13 = entityKind, _b5) {
      constructor(table4, config, baseColumn, range) {
        super(table4, config);
        __publicField(this, "size");
        this.baseColumn = baseColumn;
        this.range = range;
        this.size = config.size;
      }
      getSQLType() {
        return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          value = parsePgArray(value);
        }
        return value.map((v) => this.baseColumn.mapFromDriverValue(v));
      }
      mapToDriverValue(value, isNestedArray = false) {
        const a = value.map(
          (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
        );
        if (isNestedArray)
          return a;
        return makePgArray(a);
      }
    };
    __publicField(_PgArray, _a13, "PgArray");
    PgArray = _PgArray;
  }
});

// ../drizzle-orm/dist/pg-core/columns/enum.js
function isPgEnum(obj) {
  return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
}
function pgEnumWithSchema(enumName, values, schema4) {
  const enumInstance = Object.assign(
    (name2) => new PgEnumColumnBuilder(name2 ?? "", enumInstance),
    {
      enumName,
      enumValues: values,
      schema: schema4,
      [isPgEnumSym]: true
    }
  );
  return enumInstance;
}
var isPgEnumSym, _a14, _b6, PgEnumColumnBuilder, _a15, _b7, PgEnumColumn;
var init_enum = __esm({
  "../drizzle-orm/dist/pg-core/columns/enum.js"() {
    "use strict";
    init_entity();
    init_common2();
    isPgEnumSym = Symbol.for("drizzle:isPgEnum");
    PgEnumColumnBuilder = class extends (_b6 = PgColumnBuilder, _a14 = entityKind, _b6) {
      constructor(name2, enumInstance) {
        super(name2, "string", "PgEnumColumn");
        this.config.enum = enumInstance;
      }
      /** @internal */
      build(table4) {
        return new PgEnumColumn(
          table4,
          this.config
        );
      }
    };
    __publicField(PgEnumColumnBuilder, _a14, "PgEnumColumnBuilder");
    PgEnumColumn = class extends (_b7 = PgColumn, _a15 = entityKind, _b7) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "enum", this.config.enum);
        __publicField(this, "enumValues", this.config.enum.enumValues);
        this.enum = config.enum;
      }
      getSQLType() {
        return this.enum.enumName;
      }
    };
    __publicField(PgEnumColumn, _a15, "PgEnumColumn");
  }
});

// ../drizzle-orm/dist/subquery.js
var _a16, Subquery, _a17, _b8, WithSubquery;
var init_subquery = __esm({
  "../drizzle-orm/dist/subquery.js"() {
    "use strict";
    init_entity();
    _a16 = entityKind;
    Subquery = class {
      constructor(sql2, selection, alias, isWith = false) {
        this._ = {
          brand: "Subquery",
          sql: sql2,
          selectedFields: selection,
          alias,
          isWith
        };
      }
      // getSQL(): SQL<unknown> {
      // 	return new SQL([this]);
      // }
    };
    __publicField(Subquery, _a16, "Subquery");
    WithSubquery = class extends (_b8 = Subquery, _a17 = entityKind, _b8) {
    };
    __publicField(WithSubquery, _a17, "WithSubquery");
  }
});

// ../drizzle-orm/dist/version.js
var version;
var init_version = __esm({
  "../drizzle-orm/dist/version.js"() {
    "use strict";
    version = "0.36.2";
  }
});

// ../drizzle-orm/dist/tracing.js
var otel, rawTracer, tracer;
var init_tracing = __esm({
  "../drizzle-orm/dist/tracing.js"() {
    "use strict";
    init_tracing_utils();
    init_version();
    tracer = {
      startActiveSpan(name2, fn) {
        if (!otel) {
          return fn();
        }
        if (!rawTracer) {
          rawTracer = otel.trace.getTracer("drizzle-orm", version);
        }
        return iife(
          (otel2, rawTracer2) => rawTracer2.startActiveSpan(
            name2,
            (span) => {
              try {
                return fn(span);
              } catch (e) {
                span.setStatus({
                  code: otel2.SpanStatusCode.ERROR,
                  message: e instanceof Error ? e.message : "Unknown error"
                  // eslint-disable-line no-instanceof/no-instanceof
                });
                throw e;
              } finally {
                span.end();
              }
            }
          ),
          otel,
          rawTracer
        );
      }
    };
  }
});

// ../drizzle-orm/dist/view-common.js
var ViewBaseConfig;
var init_view_common = __esm({
  "../drizzle-orm/dist/view-common.js"() {
    "use strict";
    ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
  }
});

// ../drizzle-orm/dist/table.js
function isTable(table4) {
  return typeof table4 === "object" && table4 !== null && IsDrizzleTable in table4;
}
function getTableName(table4) {
  return table4[TableName];
}
function getTableUniqueName(table4) {
  return `${table4[Schema] ?? "public"}.${table4[TableName]}`;
}
var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, _a18, _b9, _c, _d, _e, _f, _g, _h, _i, _j, Table2;
var init_table = __esm({
  "../drizzle-orm/dist/table.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    Schema = Symbol.for("drizzle:Schema");
    Columns = Symbol.for("drizzle:Columns");
    ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
    OriginalName = Symbol.for("drizzle:OriginalName");
    BaseName = Symbol.for("drizzle:BaseName");
    IsAlias = Symbol.for("drizzle:IsAlias");
    ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
    IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
    _j = entityKind, _i = TableName, _h = OriginalName, _g = Schema, _f = Columns, _e = ExtraConfigColumns, _d = BaseName, _c = IsAlias, _b9 = IsDrizzleTable, _a18 = ExtraConfigBuilder;
    Table2 = class {
      constructor(name2, schema4, baseName) {
        /**
         * @internal
         * Can be changed if the table is aliased.
         */
        __publicField(this, _i);
        /**
         * @internal
         * Used to store the original name of the table, before any aliasing.
         */
        __publicField(this, _h);
        /** @internal */
        __publicField(this, _g);
        /** @internal */
        __publicField(this, _f);
        /** @internal */
        __publicField(this, _e);
        /**
         *  @internal
         * Used to store the table name before the transformation via the `tableCreator` functions.
         */
        __publicField(this, _d);
        /** @internal */
        __publicField(this, _c, false);
        /** @internal */
        __publicField(this, _b9, true);
        /** @internal */
        __publicField(this, _a18);
        this[TableName] = this[OriginalName] = name2;
        this[Schema] = schema4;
        this[BaseName] = baseName;
      }
    };
    __publicField(Table2, _j, "Table");
    /** @internal */
    __publicField(Table2, "Symbol", {
      Name: TableName,
      Schema,
      OriginalName,
      Columns,
      ExtraConfigColumns,
      BaseName,
      IsAlias,
      ExtraConfigBuilder
    });
  }
});

// ../drizzle-orm/dist/sql/sql.js
function isSQLWrapper(value) {
  return value !== null && value !== void 0 && typeof value.getSQL === "function";
}
function mergeQueries(queries) {
  const result = { sql: "", params: [] };
  for (const query of queries) {
    result.sql += query.sql;
    result.params.push(...query.params);
    if (query.typings?.length) {
      if (!result.typings) {
        result.typings = [];
      }
      result.typings.push(...query.typings);
    }
  }
  return result;
}
function name(value) {
  return new Name(value);
}
function isDriverValueEncoder(value) {
  return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
}
function param(value, encoder) {
  return new Param(value, encoder);
}
function sql(strings, ...params) {
  const queryChunks = [];
  if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
    queryChunks.push(new StringChunk(strings[0]));
  }
  for (const [paramIndex, param2] of params.entries()) {
    queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
  }
  return new SQL(queryChunks);
}
function placeholder(name2) {
  return new Placeholder(name2);
}
function fillPlaceholders(params, values) {
  return params.map((p) => {
    if (is(p, Placeholder)) {
      if (!(p.name in values)) {
        throw new Error(`No value for placeholder "${p.name}" was provided`);
      }
      return values[p.name];
    }
    if (is(p, Param) && is(p.value, Placeholder)) {
      if (!(p.value.name in values)) {
        throw new Error(`No value for placeholder "${p.value.name}" was provided`);
      }
      return p.encoder.mapToDriverValue(values[p.value.name]);
    }
    return p;
  });
}
var _a19, FakePrimitiveParam, _a20, StringChunk, _a21, _SQL, SQL, _a22, Name, noopDecoder, noopEncoder, noopMapper, _a23, Param, _a24, Placeholder, _a25, _b10, View3;
var init_sql = __esm({
  "../drizzle-orm/dist/sql/sql.js"() {
    "use strict";
    init_entity();
    init_enum();
    init_subquery();
    init_tracing();
    init_view_common();
    init_column();
    init_table();
    _a19 = entityKind;
    FakePrimitiveParam = class {
    };
    __publicField(FakePrimitiveParam, _a19, "FakePrimitiveParam");
    _a20 = entityKind;
    StringChunk = class {
      constructor(value) {
        __publicField(this, "value");
        this.value = Array.isArray(value) ? value : [value];
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(StringChunk, _a20, "StringChunk");
    _a21 = entityKind;
    _SQL = class _SQL {
      constructor(queryChunks) {
        /** @internal */
        __publicField(this, "decoder", noopDecoder);
        __publicField(this, "shouldInlineParams", false);
        this.queryChunks = queryChunks;
      }
      append(query) {
        this.queryChunks.push(...query.queryChunks);
        return this;
      }
      toQuery(config) {
        return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
          const query = this.buildQueryFromSourceParams(this.queryChunks, config);
          span?.setAttributes({
            "drizzle.query.text": query.sql,
            "drizzle.query.params": JSON.stringify(query.params)
          });
          return query;
        });
      }
      buildQueryFromSourceParams(chunks, _config) {
        const config = Object.assign({}, _config, {
          inlineParams: _config.inlineParams || this.shouldInlineParams,
          paramStartIndex: _config.paramStartIndex || { value: 0 }
        });
        const {
          casing: casing2,
          escapeName,
          escapeParam,
          prepareTyping,
          inlineParams,
          paramStartIndex
        } = config;
        return mergeQueries(chunks.map((chunk) => {
          if (is(chunk, StringChunk)) {
            return { sql: chunk.value.join(""), params: [] };
          }
          if (is(chunk, Name)) {
            return { sql: escapeName(chunk.value), params: [] };
          }
          if (chunk === void 0) {
            return { sql: "", params: [] };
          }
          if (Array.isArray(chunk)) {
            const result = [new StringChunk("(")];
            for (const [i, p] of chunk.entries()) {
              result.push(p);
              if (i < chunk.length - 1) {
                result.push(new StringChunk(", "));
              }
            }
            result.push(new StringChunk(")"));
            return this.buildQueryFromSourceParams(result, config);
          }
          if (is(chunk, _SQL)) {
            return this.buildQueryFromSourceParams(chunk.queryChunks, {
              ...config,
              inlineParams: inlineParams || chunk.shouldInlineParams
            });
          }
          if (is(chunk, Table2)) {
            const schemaName = chunk[Table2.Symbol.Schema];
            const tableName = chunk[Table2.Symbol.Name];
            return {
              sql: schemaName === void 0 ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
              params: []
            };
          }
          if (is(chunk, Column2)) {
            const columnName = casing2.getColumnCasing(chunk);
            if (_config.invokeSource === "indexes") {
              return { sql: escapeName(columnName), params: [] };
            }
            const schemaName = chunk.table[Table2.Symbol.Schema];
            return {
              sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName),
              params: []
            };
          }
          if (is(chunk, View3)) {
            const schemaName = chunk[ViewBaseConfig].schema;
            const viewName = chunk[ViewBaseConfig].name;
            return {
              sql: schemaName === void 0 ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
              params: []
            };
          }
          if (is(chunk, Param)) {
            if (is(chunk.value, Placeholder)) {
              return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
            }
            const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
            if (is(mappedValue, _SQL)) {
              return this.buildQueryFromSourceParams([mappedValue], config);
            }
            if (inlineParams) {
              return { sql: this.mapInlineParam(mappedValue, config), params: [] };
            }
            let typings = ["none"];
            if (prepareTyping) {
              typings = [prepareTyping(chunk.encoder)];
            }
            return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
          }
          if (is(chunk, Placeholder)) {
            return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
          }
          if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) {
            return { sql: escapeName(chunk.fieldAlias), params: [] };
          }
          if (is(chunk, Subquery)) {
            if (chunk._.isWith) {
              return { sql: escapeName(chunk._.alias), params: [] };
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk._.sql,
              new StringChunk(") "),
              new Name(chunk._.alias)
            ], config);
          }
          if (isPgEnum(chunk)) {
            if (chunk.schema) {
              return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
            }
            return { sql: escapeName(chunk.enumName), params: [] };
          }
          if (isSQLWrapper(chunk)) {
            if (chunk.shouldOmitSQLParens?.()) {
              return this.buildQueryFromSourceParams([chunk.getSQL()], config);
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk.getSQL(),
              new StringChunk(")")
            ], config);
          }
          if (inlineParams) {
            return { sql: this.mapInlineParam(chunk, config), params: [] };
          }
          return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
        }));
      }
      mapInlineParam(chunk, { escapeString }) {
        if (chunk === null) {
          return "null";
        }
        if (typeof chunk === "number" || typeof chunk === "boolean") {
          return chunk.toString();
        }
        if (typeof chunk === "string") {
          return escapeString(chunk);
        }
        if (typeof chunk === "object") {
          const mappedValueAsString = chunk.toString();
          if (mappedValueAsString === "[object Object]") {
            return escapeString(JSON.stringify(chunk));
          }
          return escapeString(mappedValueAsString);
        }
        throw new Error("Unexpected param value: " + chunk);
      }
      getSQL() {
        return this;
      }
      as(alias) {
        if (alias === void 0) {
          return this;
        }
        return new _SQL.Aliased(this, alias);
      }
      mapWith(decoder) {
        this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
        return this;
      }
      inlineParams() {
        this.shouldInlineParams = true;
        return this;
      }
      /**
       * This method is used to conditionally include a part of the query.
       *
       * @param condition - Condition to check
       * @returns itself if the condition is `true`, otherwise `undefined`
       */
      if(condition) {
        return condition ? this : void 0;
      }
    };
    __publicField(_SQL, _a21, "SQL");
    SQL = _SQL;
    _a22 = entityKind;
    Name = class {
      constructor(value) {
        __publicField(this, "brand");
        this.value = value;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Name, _a22, "Name");
    noopDecoder = {
      mapFromDriverValue: (value) => value
    };
    noopEncoder = {
      mapToDriverValue: (value) => value
    };
    noopMapper = {
      ...noopDecoder,
      ...noopEncoder
    };
    _a23 = entityKind;
    Param = class {
      /**
       * @param value - Parameter value
       * @param encoder - Encoder to convert the value to a driver parameter
       */
      constructor(value, encoder = noopEncoder) {
        __publicField(this, "brand");
        this.value = value;
        this.encoder = encoder;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Param, _a23, "Param");
    ((sql2) => {
      function empty() {
        return new SQL([]);
      }
      sql2.empty = empty;
      function fromList(list) {
        return new SQL(list);
      }
      sql2.fromList = fromList;
      function raw(str) {
        return new SQL([new StringChunk(str)]);
      }
      sql2.raw = raw;
      function join(chunks, separator) {
        const result = [];
        for (const [i, chunk] of chunks.entries()) {
          if (i > 0 && separator !== void 0) {
            result.push(separator);
          }
          result.push(chunk);
        }
        return new SQL(result);
      }
      sql2.join = join;
      function identifier(value) {
        return new Name(value);
      }
      sql2.identifier = identifier;
      function placeholder2(name2) {
        return new Placeholder(name2);
      }
      sql2.placeholder = placeholder2;
      function param2(value, encoder) {
        return new Param(value, encoder);
      }
      sql2.param = param2;
    })(sql || (sql = {}));
    ((SQL2) => {
      var _a326;
      _a326 = entityKind;
      const _Aliased = class _Aliased {
        constructor(sql2, fieldAlias) {
          /** @internal */
          __publicField(this, "isSelectionField", false);
          this.sql = sql2;
          this.fieldAlias = fieldAlias;
        }
        getSQL() {
          return this.sql;
        }
        /** @internal */
        clone() {
          return new _Aliased(this.sql, this.fieldAlias);
        }
      };
      __publicField(_Aliased, _a326, "SQL.Aliased");
      let Aliased = _Aliased;
      SQL2.Aliased = Aliased;
    })(SQL || (SQL = {}));
    _a24 = entityKind;
    Placeholder = class {
      constructor(name2) {
        this.name = name2;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Placeholder, _a24, "Placeholder");
    _b10 = entityKind, _a25 = ViewBaseConfig;
    View3 = class {
      constructor({ name: name2, schema: schema4, selectedFields, query }) {
        /** @internal */
        __publicField(this, _a25);
        this[ViewBaseConfig] = {
          name: name2,
          originalName: name2,
          schema: schema4,
          selectedFields,
          query,
          isExisting: !query,
          isAlias: false
        };
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(View3, _b10, "View");
    Column2.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Table2.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Subquery.prototype.getSQL = function() {
      return new SQL([this]);
    };
  }
});

// ../drizzle-orm/dist/alias.js
function aliasedTable(table4, tableAlias) {
  return new Proxy(table4, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedRelation(relation, tableAlias) {
  return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
}
function aliasedTableColumn(column4, tableAlias) {
  return new Proxy(
    column4,
    new ColumnAliasProxyHandler(new Proxy(column4.table, new TableAliasProxyHandler(tableAlias, false)))
  );
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
  return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
}
function mapColumnsInSQLToAlias(query, alias) {
  return sql.join(query.queryChunks.map((c) => {
    if (is(c, Column2)) {
      return aliasedTableColumn(c, alias);
    }
    if (is(c, SQL)) {
      return mapColumnsInSQLToAlias(c, alias);
    }
    if (is(c, SQL.Aliased)) {
      return mapColumnsInAliasedSQLToAlias(c, alias);
    }
    return c;
  }));
}
var _a26, ColumnAliasProxyHandler, _a27, TableAliasProxyHandler, _a28, RelationTableAliasProxyHandler;
var init_alias = __esm({
  "../drizzle-orm/dist/alias.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
    init_table();
    init_view_common();
    _a26 = entityKind;
    ColumnAliasProxyHandler = class {
      constructor(table4) {
        this.table = table4;
      }
      get(columnObj, prop) {
        if (prop === "table") {
          return this.table;
        }
        return columnObj[prop];
      }
    };
    __publicField(ColumnAliasProxyHandler, _a26, "ColumnAliasProxyHandler");
    _a27 = entityKind;
    TableAliasProxyHandler = class {
      constructor(alias, replaceOriginalName) {
        this.alias = alias;
        this.replaceOriginalName = replaceOriginalName;
      }
      get(target, prop) {
        if (prop === Table2.Symbol.IsAlias) {
          return true;
        }
        if (prop === Table2.Symbol.Name) {
          return this.alias;
        }
        if (this.replaceOriginalName && prop === Table2.Symbol.OriginalName) {
          return this.alias;
        }
        if (prop === ViewBaseConfig) {
          return {
            ...target[ViewBaseConfig],
            name: this.alias,
            isAlias: true
          };
        }
        if (prop === Table2.Symbol.Columns) {
          const columns = target[Table2.Symbol.Columns];
          if (!columns) {
            return columns;
          }
          const proxiedColumns = {};
          Object.keys(columns).map((key) => {
            proxiedColumns[key] = new Proxy(
              columns[key],
              new ColumnAliasProxyHandler(new Proxy(target, this))
            );
          });
          return proxiedColumns;
        }
        const value = target[prop];
        if (is(value, Column2)) {
          return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
        }
        return value;
      }
    };
    __publicField(TableAliasProxyHandler, _a27, "TableAliasProxyHandler");
    _a28 = entityKind;
    RelationTableAliasProxyHandler = class {
      constructor(alias) {
        this.alias = alias;
      }
      get(target, prop) {
        if (prop === "sourceTable") {
          return aliasedTable(target.sourceTable, this.alias);
        }
        return target[prop];
      }
    };
    __publicField(RelationTableAliasProxyHandler, _a28, "RelationTableAliasProxyHandler");
  }
});

// ../drizzle-orm/dist/errors.js
var _a29, _b11, DrizzleError, _a30, _b12, TransactionRollbackError;
var init_errors = __esm({
  "../drizzle-orm/dist/errors.js"() {
    "use strict";
    init_entity();
    DrizzleError = class extends (_b11 = Error, _a29 = entityKind, _b11) {
      constructor({ message, cause }) {
        super(message);
        this.name = "DrizzleError";
        this.cause = cause;
      }
    };
    __publicField(DrizzleError, _a29, "DrizzleError");
    TransactionRollbackError = class extends (_b12 = DrizzleError, _a30 = entityKind, _b12) {
      constructor() {
        super({ message: "Rollback" });
      }
    };
    __publicField(TransactionRollbackError, _a30, "TransactionRollbackError");
  }
});

// ../drizzle-orm/dist/sql/expressions/conditions.js
function bindIfParam(value, column4) {
  if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table2) && !is(value, View3)) {
    return new Param(value, column4);
  }
  return value;
}
function and(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" and ")),
    new StringChunk(")")
  ]);
}
function or(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" or ")),
    new StringChunk(")")
  ]);
}
function not(condition) {
  return sql`not ${condition}`;
}
function inArray(column4, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`false`;
    }
    return sql`${column4} in ${values.map((v) => bindIfParam(v, column4))}`;
  }
  return sql`${column4} in ${bindIfParam(values, column4)}`;
}
function notInArray(column4, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`true`;
    }
    return sql`${column4} not in ${values.map((v) => bindIfParam(v, column4))}`;
  }
  return sql`${column4} not in ${bindIfParam(values, column4)}`;
}
function isNull(value) {
  return sql`${value} is null`;
}
function isNotNull(value) {
  return sql`${value} is not null`;
}
function exists(subquery) {
  return sql`exists ${subquery}`;
}
function notExists(subquery) {
  return sql`not exists ${subquery}`;
}
function between(column4, min2, max2) {
  return sql`${column4} between ${bindIfParam(min2, column4)} and ${bindIfParam(
    max2,
    column4
  )}`;
}
function notBetween(column4, min2, max2) {
  return sql`${column4} not between ${bindIfParam(
    min2,
    column4
  )} and ${bindIfParam(max2, column4)}`;
}
function like(column4, value) {
  return sql`${column4} like ${value}`;
}
function notLike(column4, value) {
  return sql`${column4} not like ${value}`;
}
function ilike(column4, value) {
  return sql`${column4} ilike ${value}`;
}
function notIlike(column4, value) {
  return sql`${column4} not ilike ${value}`;
}
function arrayContains(column4, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayContains requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column4)}`;
    return sql`${column4} @> ${array2}`;
  }
  return sql`${column4} @> ${bindIfParam(values, column4)}`;
}
function arrayContained(column4, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayContained requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column4)}`;
    return sql`${column4} <@ ${array2}`;
  }
  return sql`${column4} <@ ${bindIfParam(values, column4)}`;
}
function arrayOverlaps(column4, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayOverlaps requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column4)}`;
    return sql`${column4} && ${array2}`;
  }
  return sql`${column4} && ${bindIfParam(values, column4)}`;
}
var eq, ne, gt, gte, lt, lte;
var init_conditions = __esm({
  "../drizzle-orm/dist/sql/expressions/conditions.js"() {
    "use strict";
    init_column();
    init_entity();
    init_table();
    init_sql();
    eq = (left, right) => {
      return sql`${left} = ${bindIfParam(right, left)}`;
    };
    ne = (left, right) => {
      return sql`${left} <> ${bindIfParam(right, left)}`;
    };
    gt = (left, right) => {
      return sql`${left} > ${bindIfParam(right, left)}`;
    };
    gte = (left, right) => {
      return sql`${left} >= ${bindIfParam(right, left)}`;
    };
    lt = (left, right) => {
      return sql`${left} < ${bindIfParam(right, left)}`;
    };
    lte = (left, right) => {
      return sql`${left} <= ${bindIfParam(right, left)}`;
    };
  }
});

// ../drizzle-orm/dist/sql/expressions/select.js
function asc(column4) {
  return sql`${column4} asc`;
}
function desc(column4) {
  return sql`${column4} desc`;
}
var init_select = __esm({
  "../drizzle-orm/dist/sql/expressions/select.js"() {
    "use strict";
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/expressions/index.js
var init_expressions = __esm({
  "../drizzle-orm/dist/sql/expressions/index.js"() {
    "use strict";
    init_conditions();
    init_select();
  }
});

// ../drizzle-orm/dist/expressions.js
var init_expressions2 = __esm({
  "../drizzle-orm/dist/expressions.js"() {
    "use strict";
    init_expressions();
  }
});

// ../drizzle-orm/dist/logger.js
var _a31, ConsoleLogWriter, _a32, DefaultLogger, _a33, NoopLogger;
var init_logger = __esm({
  "../drizzle-orm/dist/logger.js"() {
    "use strict";
    init_entity();
    _a31 = entityKind;
    ConsoleLogWriter = class {
      write(message) {
        console.log(message);
      }
    };
    __publicField(ConsoleLogWriter, _a31, "ConsoleLogWriter");
    _a32 = entityKind;
    DefaultLogger = class {
      constructor(config) {
        __publicField(this, "writer");
        this.writer = config?.writer ?? new ConsoleLogWriter();
      }
      logQuery(query, params) {
        const stringifiedParams = params.map((p) => {
          try {
            return JSON.stringify(p);
          } catch {
            return String(p);
          }
        });
        const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
        this.writer.write(`Query: ${query}${paramsStr}`);
      }
    };
    __publicField(DefaultLogger, _a32, "DefaultLogger");
    _a33 = entityKind;
    NoopLogger = class {
      logQuery() {
      }
    };
    __publicField(NoopLogger, _a33, "NoopLogger");
  }
});

// ../drizzle-orm/dist/operations.js
var init_operations = __esm({
  "../drizzle-orm/dist/operations.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/query-promise.js
var _a34, _b13, QueryPromise;
var init_query_promise = __esm({
  "../drizzle-orm/dist/query-promise.js"() {
    "use strict";
    init_entity();
    _b13 = entityKind, _a34 = Symbol.toStringTag;
    QueryPromise = class {
      constructor() {
        __publicField(this, _a34, "QueryPromise");
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
      then(onFulfilled, onRejected) {
        return this.execute().then(onFulfilled, onRejected);
      }
    };
    __publicField(QueryPromise, _b13, "QueryPromise");
  }
});

// ../drizzle-orm/dist/utils.js
function mapResultRow(columns, row, joinsNotNullableMap) {
  const nullifyMap = {};
  const result = columns.reduce(
    (result2, { path: path2, field }, columnIndex) => {
      let decoder;
      if (is(field, Column2)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      let node = result2;
      for (const [pathChunkIndex, pathChunk] of path2.entries()) {
        if (pathChunkIndex < path2.length - 1) {
          if (!(pathChunk in node)) {
            node[pathChunk] = {};
          }
          node = node[pathChunk];
        } else {
          const rawValue = row[columnIndex];
          const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
          if (joinsNotNullableMap && is(field, Column2) && path2.length === 2) {
            const objectName = path2[0];
            if (!(objectName in nullifyMap)) {
              nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
            } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
              nullifyMap[objectName] = false;
            }
          }
        }
      }
      return result2;
    },
    {}
  );
  if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
    for (const [objectName, tableName] of Object.entries(nullifyMap)) {
      if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
        result[objectName] = null;
      }
    }
  }
  return result;
}
function orderSelectedFields(fields, pathPrefix) {
  return Object.entries(fields).reduce((result, [name2, field]) => {
    if (typeof name2 !== "string") {
      return result;
    }
    const newPath = pathPrefix ? [...pathPrefix, name2] : [name2];
    if (is(field, Column2) || is(field, SQL) || is(field, SQL.Aliased)) {
      result.push({ path: newPath, field });
    } else if (is(field, Table2)) {
      result.push(...orderSelectedFields(field[Table2.Symbol.Columns], newPath));
    } else {
      result.push(...orderSelectedFields(field, newPath));
    }
    return result;
  }, []);
}
function haveSameKeys(left, right) {
  const leftKeys = Object.keys(left);
  const rightKeys = Object.keys(right);
  if (leftKeys.length !== rightKeys.length) {
    return false;
  }
  for (const [index4, key] of leftKeys.entries()) {
    if (key !== rightKeys[index4]) {
      return false;
    }
  }
  return true;
}
function mapUpdateSet(table4, values) {
  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
    if (is(value, SQL)) {
      return [key, value];
    } else {
      return [key, new Param(value, table4[Table2.Symbol.Columns][key])];
    }
  });
  if (entries.length === 0) {
    throw new Error("No values to set");
  }
  return Object.fromEntries(entries);
}
function applyMixins(baseClass, extendedClasses) {
  for (const extendedClass of extendedClasses) {
    for (const name2 of Object.getOwnPropertyNames(extendedClass.prototype)) {
      if (name2 === "constructor")
        continue;
      Object.defineProperty(
        baseClass.prototype,
        name2,
        Object.getOwnPropertyDescriptor(extendedClass.prototype, name2) || /* @__PURE__ */ Object.create(null)
      );
    }
  }
}
function getTableColumns(table4) {
  return table4[Table2.Symbol.Columns];
}
function getTableLikeName(table4) {
  return is(table4, Subquery) ? table4._.alias : is(table4, View3) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : table4[Table2.Symbol.IsAlias] ? table4[Table2.Symbol.Name] : table4[Table2.Symbol.BaseName];
}
function getColumnNameAndConfig(a, b) {
  return {
    name: typeof a === "string" && a.length > 0 ? a : "",
    config: typeof a === "object" ? a : b
  };
}
function isConfig(data) {
  if (typeof data !== "object" || data === null)
    return false;
  if (data.constructor.name !== "Object")
    return false;
  if ("logger" in data) {
    const type = typeof data["logger"];
    if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
      return false;
    return true;
  }
  if ("schema" in data) {
    const type = typeof data["logger"];
    if (type !== "object" && type !== "undefined")
      return false;
    return true;
  }
  if ("casing" in data) {
    const type = typeof data["logger"];
    if (type !== "string" && type !== "undefined")
      return false;
    return true;
  }
  if ("mode" in data) {
    if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== void 0)
      return false;
    return true;
  }
  if ("connection" in data) {
    const type = typeof data["connection"];
    if (type !== "string" && type !== "object" && type !== "undefined")
      return false;
    return true;
  }
  if ("client" in data) {
    const type = typeof data["client"];
    if (type !== "object" && type !== "function" && type !== "undefined")
      return false;
    return true;
  }
  if (Object.keys(data).length === 0)
    return true;
  return false;
}
var init_utils2 = __esm({
  "../drizzle-orm/dist/utils.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_table();
    init_view_common();
  }
});

// ../drizzle-orm/dist/pg-core/columns/int.common.js
var _a35, _b14, PgIntColumnBaseBuilder;
var init_int_common = __esm({
  "../drizzle-orm/dist/pg-core/columns/int.common.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgIntColumnBaseBuilder = class extends (_b14 = PgColumnBuilder, _a35 = entityKind, _b14) {
      generatedAlwaysAsIdentity(sequence) {
        if (sequence) {
          const { name: name2, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "always",
            sequenceName: name2,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "always"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
      generatedByDefaultAsIdentity(sequence) {
        if (sequence) {
          const { name: name2, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "byDefault",
            sequenceName: name2,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "byDefault"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
    };
    __publicField(PgIntColumnBaseBuilder, _a35, "PgIntColumnBaseBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/columns/bigint.js
function bigint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new PgBigInt53Builder(name2);
  }
  return new PgBigInt64Builder(name2);
}
var _a36, _b15, PgBigInt53Builder, _a37, _b16, PgBigInt53, _a38, _b17, PgBigInt64Builder, _a39, _b18, PgBigInt64;
var init_bigint = __esm({
  "../drizzle-orm/dist/pg-core/columns/bigint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_int_common();
    PgBigInt53Builder = class extends (_b15 = PgIntColumnBaseBuilder, _a36 = entityKind, _b15) {
      constructor(name2) {
        super(name2, "number", "PgBigInt53");
      }
      /** @internal */
      build(table4) {
        return new PgBigInt53(table4, this.config);
      }
    };
    __publicField(PgBigInt53Builder, _a36, "PgBigInt53Builder");
    PgBigInt53 = class extends (_b16 = PgColumn, _a37 = entityKind, _b16) {
      getSQLType() {
        return "bigint";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(PgBigInt53, _a37, "PgBigInt53");
    PgBigInt64Builder = class extends (_b17 = PgIntColumnBaseBuilder, _a38 = entityKind, _b17) {
      constructor(name2) {
        super(name2, "bigint", "PgBigInt64");
      }
      /** @internal */
      build(table4) {
        return new PgBigInt64(
          table4,
          this.config
        );
      }
    };
    __publicField(PgBigInt64Builder, _a38, "PgBigInt64Builder");
    PgBigInt64 = class extends (_b18 = PgColumn, _a39 = entityKind, _b18) {
      getSQLType() {
        return "bigint";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(PgBigInt64, _a39, "PgBigInt64");
  }
});

// ../drizzle-orm/dist/pg-core/columns/bigserial.js
function bigserial(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new PgBigSerial53Builder(name2);
  }
  return new PgBigSerial64Builder(name2);
}
var _a40, _b19, PgBigSerial53Builder, _a41, _b20, PgBigSerial53, _a42, _b21, PgBigSerial64Builder, _a43, _b22, PgBigSerial64;
var init_bigserial = __esm({
  "../drizzle-orm/dist/pg-core/columns/bigserial.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgBigSerial53Builder = class extends (_b19 = PgColumnBuilder, _a40 = entityKind, _b19) {
      constructor(name2) {
        super(name2, "number", "PgBigSerial53");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table4) {
        return new PgBigSerial53(
          table4,
          this.config
        );
      }
    };
    __publicField(PgBigSerial53Builder, _a40, "PgBigSerial53Builder");
    PgBigSerial53 = class extends (_b20 = PgColumn, _a41 = entityKind, _b20) {
      getSQLType() {
        return "bigserial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(PgBigSerial53, _a41, "PgBigSerial53");
    PgBigSerial64Builder = class extends (_b21 = PgColumnBuilder, _a42 = entityKind, _b21) {
      constructor(name2) {
        super(name2, "bigint", "PgBigSerial64");
        this.config.hasDefault = true;
      }
      /** @internal */
      build(table4) {
        return new PgBigSerial64(
          table4,
          this.config
        );
      }
    };
    __publicField(PgBigSerial64Builder, _a42, "PgBigSerial64Builder");
    PgBigSerial64 = class extends (_b22 = PgColumn, _a43 = entityKind, _b22) {
      getSQLType() {
        return "bigserial";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(PgBigSerial64, _a43, "PgBigSerial64");
  }
});

// ../drizzle-orm/dist/pg-core/columns/boolean.js
function boolean(name2) {
  return new PgBooleanBuilder(name2 ?? "");
}
var _a44, _b23, PgBooleanBuilder, _a45, _b24, PgBoolean;
var init_boolean = __esm({
  "../drizzle-orm/dist/pg-core/columns/boolean.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgBooleanBuilder = class extends (_b23 = PgColumnBuilder, _a44 = entityKind, _b23) {
      constructor(name2) {
        super(name2, "boolean", "PgBoolean");
      }
      /** @internal */
      build(table4) {
        return new PgBoolean(table4, this.config);
      }
    };
    __publicField(PgBooleanBuilder, _a44, "PgBooleanBuilder");
    PgBoolean = class extends (_b24 = PgColumn, _a45 = entityKind, _b24) {
      getSQLType() {
        return "boolean";
      }
    };
    __publicField(PgBoolean, _a45, "PgBoolean");
  }
});

// ../drizzle-orm/dist/pg-core/columns/char.js
function char(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgCharBuilder(name2, config);
}
var _a46, _b25, PgCharBuilder, _a47, _b26, PgChar;
var init_char = __esm({
  "../drizzle-orm/dist/pg-core/columns/char.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgCharBuilder = class extends (_b25 = PgColumnBuilder, _a46 = entityKind, _b25) {
      constructor(name2, config) {
        super(name2, "string", "PgChar");
        this.config.length = config.length;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table4) {
        return new PgChar(table4, this.config);
      }
    };
    __publicField(PgCharBuilder, _a46, "PgCharBuilder");
    PgChar = class extends (_b26 = PgColumn, _a47 = entityKind, _b26) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
    __publicField(PgChar, _a47, "PgChar");
  }
});

// ../drizzle-orm/dist/pg-core/columns/cidr.js
function cidr(name2) {
  return new PgCidrBuilder(name2 ?? "");
}
var _a48, _b27, PgCidrBuilder, _a49, _b28, PgCidr;
var init_cidr = __esm({
  "../drizzle-orm/dist/pg-core/columns/cidr.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgCidrBuilder = class extends (_b27 = PgColumnBuilder, _a48 = entityKind, _b27) {
      constructor(name2) {
        super(name2, "string", "PgCidr");
      }
      /** @internal */
      build(table4) {
        return new PgCidr(table4, this.config);
      }
    };
    __publicField(PgCidrBuilder, _a48, "PgCidrBuilder");
    PgCidr = class extends (_b28 = PgColumn, _a49 = entityKind, _b28) {
      getSQLType() {
        return "cidr";
      }
    };
    __publicField(PgCidr, _a49, "PgCidr");
  }
});

// ../drizzle-orm/dist/pg-core/columns/custom.js
function customType(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new PgCustomColumnBuilder(name2, config, customTypeParams);
  };
}
var _a50, _b29, PgCustomColumnBuilder, _a51, _b30, PgCustomColumn;
var init_custom = __esm({
  "../drizzle-orm/dist/pg-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgCustomColumnBuilder = class extends (_b29 = PgColumnBuilder, _a50 = entityKind, _b29) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "PgCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table4) {
        return new PgCustomColumn(
          table4,
          this.config
        );
      }
    };
    __publicField(PgCustomColumnBuilder, _a50, "PgCustomColumnBuilder");
    PgCustomColumn = class extends (_b30 = PgColumn, _a51 = entityKind, _b30) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(PgCustomColumn, _a51, "PgCustomColumn");
  }
});

// ../drizzle-orm/dist/pg-core/columns/date.common.js
var _a52, _b31, PgDateColumnBaseBuilder;
var init_date_common = __esm({
  "../drizzle-orm/dist/pg-core/columns/date.common.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common2();
    PgDateColumnBaseBuilder = class extends (_b31 = PgColumnBuilder, _a52 = entityKind, _b31) {
      defaultNow() {
        return this.default(sql`now()`);
      }
    };
    __publicField(PgDateColumnBaseBuilder, _a52, "PgDateColumnBaseBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/columns/date.js
function date(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "date") {
    return new PgDateBuilder(name2);
  }
  return new PgDateStringBuilder(name2);
}
var _a53, _b32, PgDateBuilder, _a54, _b33, PgDate, _a55, _b34, PgDateStringBuilder, _a56, _b35, PgDateString;
var init_date = __esm({
  "../drizzle-orm/dist/pg-core/columns/date.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgDateBuilder = class extends (_b32 = PgDateColumnBaseBuilder, _a53 = entityKind, _b32) {
      constructor(name2) {
        super(name2, "date", "PgDate");
      }
      /** @internal */
      build(table4) {
        return new PgDate(table4, this.config);
      }
    };
    __publicField(PgDateBuilder, _a53, "PgDateBuilder");
    PgDate = class extends (_b33 = PgColumn, _a54 = entityKind, _b33) {
      getSQLType() {
        return "date";
      }
      mapFromDriverValue(value) {
        return new Date(value);
      }
      mapToDriverValue(value) {
        return value.toISOString();
      }
    };
    __publicField(PgDate, _a54, "PgDate");
    PgDateStringBuilder = class extends (_b34 = PgDateColumnBaseBuilder, _a55 = entityKind, _b34) {
      constructor(name2) {
        super(name2, "string", "PgDateString");
      }
      /** @internal */
      build(table4) {
        return new PgDateString(
          table4,
          this.config
        );
      }
    };
    __publicField(PgDateStringBuilder, _a55, "PgDateStringBuilder");
    PgDateString = class extends (_b35 = PgColumn, _a56 = entityKind, _b35) {
      getSQLType() {
        return "date";
      }
    };
    __publicField(PgDateString, _a56, "PgDateString");
  }
});

// ../drizzle-orm/dist/pg-core/columns/double-precision.js
function doublePrecision(name2) {
  return new PgDoublePrecisionBuilder(name2 ?? "");
}
var _a57, _b36, PgDoublePrecisionBuilder, _a58, _b37, PgDoublePrecision;
var init_double_precision = __esm({
  "../drizzle-orm/dist/pg-core/columns/double-precision.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgDoublePrecisionBuilder = class extends (_b36 = PgColumnBuilder, _a57 = entityKind, _b36) {
      constructor(name2) {
        super(name2, "number", "PgDoublePrecision");
      }
      /** @internal */
      build(table4) {
        return new PgDoublePrecision(
          table4,
          this.config
        );
      }
    };
    __publicField(PgDoublePrecisionBuilder, _a57, "PgDoublePrecisionBuilder");
    PgDoublePrecision = class extends (_b37 = PgColumn, _a58 = entityKind, _b37) {
      getSQLType() {
        return "double precision";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseFloat(value);
        }
        return value;
      }
    };
    __publicField(PgDoublePrecision, _a58, "PgDoublePrecision");
  }
});

// ../drizzle-orm/dist/pg-core/columns/inet.js
function inet(name2) {
  return new PgInetBuilder(name2 ?? "");
}
var _a59, _b38, PgInetBuilder, _a60, _b39, PgInet;
var init_inet = __esm({
  "../drizzle-orm/dist/pg-core/columns/inet.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgInetBuilder = class extends (_b38 = PgColumnBuilder, _a59 = entityKind, _b38) {
      constructor(name2) {
        super(name2, "string", "PgInet");
      }
      /** @internal */
      build(table4) {
        return new PgInet(table4, this.config);
      }
    };
    __publicField(PgInetBuilder, _a59, "PgInetBuilder");
    PgInet = class extends (_b39 = PgColumn, _a60 = entityKind, _b39) {
      getSQLType() {
        return "inet";
      }
    };
    __publicField(PgInet, _a60, "PgInet");
  }
});

// ../drizzle-orm/dist/pg-core/columns/integer.js
function integer(name2) {
  return new PgIntegerBuilder(name2 ?? "");
}
var _a61, _b40, PgIntegerBuilder, _a62, _b41, PgInteger;
var init_integer = __esm({
  "../drizzle-orm/dist/pg-core/columns/integer.js"() {
    "use strict";
    init_entity();
    init_common2();
    init_int_common();
    PgIntegerBuilder = class extends (_b40 = PgIntColumnBaseBuilder, _a61 = entityKind, _b40) {
      constructor(name2) {
        super(name2, "number", "PgInteger");
      }
      /** @internal */
      build(table4) {
        return new PgInteger(table4, this.config);
      }
    };
    __publicField(PgIntegerBuilder, _a61, "PgIntegerBuilder");
    PgInteger = class extends (_b41 = PgColumn, _a62 = entityKind, _b41) {
      getSQLType() {
        return "integer";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseInt(value);
        }
        return value;
      }
    };
    __publicField(PgInteger, _a62, "PgInteger");
  }
});

// ../drizzle-orm/dist/pg-core/columns/interval.js
function interval(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgIntervalBuilder(name2, config);
}
var _a63, _b42, PgIntervalBuilder, _a64, _b43, PgInterval;
var init_interval = __esm({
  "../drizzle-orm/dist/pg-core/columns/interval.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgIntervalBuilder = class extends (_b42 = PgColumnBuilder, _a63 = entityKind, _b42) {
      constructor(name2, intervalConfig) {
        super(name2, "string", "PgInterval");
        this.config.intervalConfig = intervalConfig;
      }
      /** @internal */
      build(table4) {
        return new PgInterval(table4, this.config);
      }
    };
    __publicField(PgIntervalBuilder, _a63, "PgIntervalBuilder");
    PgInterval = class extends (_b43 = PgColumn, _a64 = entityKind, _b43) {
      constructor() {
        super(...arguments);
        __publicField(this, "fields", this.config.intervalConfig.fields);
        __publicField(this, "precision", this.config.intervalConfig.precision);
      }
      getSQLType() {
        const fields = this.fields ? ` ${this.fields}` : "";
        const precision = this.precision ? `(${this.precision})` : "";
        return `interval${fields}${precision}`;
      }
    };
    __publicField(PgInterval, _a64, "PgInterval");
  }
});

// ../drizzle-orm/dist/pg-core/columns/json.js
function json(name2) {
  return new PgJsonBuilder(name2 ?? "");
}
var _a65, _b44, PgJsonBuilder, _a66, _b45, PgJson;
var init_json = __esm({
  "../drizzle-orm/dist/pg-core/columns/json.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgJsonBuilder = class extends (_b44 = PgColumnBuilder, _a65 = entityKind, _b44) {
      constructor(name2) {
        super(name2, "json", "PgJson");
      }
      /** @internal */
      build(table4) {
        return new PgJson(table4, this.config);
      }
    };
    __publicField(PgJsonBuilder, _a65, "PgJsonBuilder");
    PgJson = class extends (_b45 = PgColumn, _a66 = entityKind, _b45) {
      constructor(table4, config) {
        super(table4, config);
      }
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
    __publicField(PgJson, _a66, "PgJson");
  }
});

// ../drizzle-orm/dist/pg-core/columns/jsonb.js
function jsonb(name2) {
  return new PgJsonbBuilder(name2 ?? "");
}
var _a67, _b46, PgJsonbBuilder, _a68, _b47, PgJsonb;
var init_jsonb = __esm({
  "../drizzle-orm/dist/pg-core/columns/jsonb.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgJsonbBuilder = class extends (_b46 = PgColumnBuilder, _a67 = entityKind, _b46) {
      constructor(name2) {
        super(name2, "json", "PgJsonb");
      }
      /** @internal */
      build(table4) {
        return new PgJsonb(table4, this.config);
      }
    };
    __publicField(PgJsonbBuilder, _a67, "PgJsonbBuilder");
    PgJsonb = class extends (_b47 = PgColumn, _a68 = entityKind, _b47) {
      constructor(table4, config) {
        super(table4, config);
      }
      getSQLType() {
        return "jsonb";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
    __publicField(PgJsonb, _a68, "PgJsonb");
  }
});

// ../drizzle-orm/dist/pg-core/columns/line.js
function line(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgLineBuilder(name2);
  }
  return new PgLineABCBuilder(name2);
}
var _a69, _b48, PgLineBuilder, _a70, _b49, PgLineTuple, _a71, _b50, PgLineABCBuilder, _a72, _b51, PgLineABC;
var init_line = __esm({
  "../drizzle-orm/dist/pg-core/columns/line.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgLineBuilder = class extends (_b48 = PgColumnBuilder, _a69 = entityKind, _b48) {
      constructor(name2) {
        super(name2, "array", "PgLine");
      }
      /** @internal */
      build(table4) {
        return new PgLineTuple(
          table4,
          this.config
        );
      }
    };
    __publicField(PgLineBuilder, _a69, "PgLineBuilder");
    PgLineTuple = class extends (_b49 = PgColumn, _a70 = entityKind, _b49) {
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];
      }
      mapToDriverValue(value) {
        return `{${value[0]},${value[1]},${value[2]}}`;
      }
    };
    __publicField(PgLineTuple, _a70, "PgLine");
    PgLineABCBuilder = class extends (_b50 = PgColumnBuilder, _a71 = entityKind, _b50) {
      constructor(name2) {
        super(name2, "json", "PgLineABC");
      }
      /** @internal */
      build(table4) {
        return new PgLineABC(
          table4,
          this.config
        );
      }
    };
    __publicField(PgLineABCBuilder, _a71, "PgLineABCBuilder");
    PgLineABC = class extends (_b51 = PgColumn, _a72 = entityKind, _b51) {
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };
      }
      mapToDriverValue(value) {
        return `{${value.a},${value.b},${value.c}}`;
      }
    };
    __publicField(PgLineABC, _a72, "PgLineABC");
  }
});

// ../drizzle-orm/dist/pg-core/columns/macaddr.js
function macaddr(name2) {
  return new PgMacaddrBuilder(name2 ?? "");
}
var _a73, _b52, PgMacaddrBuilder, _a74, _b53, PgMacaddr;
var init_macaddr = __esm({
  "../drizzle-orm/dist/pg-core/columns/macaddr.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgMacaddrBuilder = class extends (_b52 = PgColumnBuilder, _a73 = entityKind, _b52) {
      constructor(name2) {
        super(name2, "string", "PgMacaddr");
      }
      /** @internal */
      build(table4) {
        return new PgMacaddr(table4, this.config);
      }
    };
    __publicField(PgMacaddrBuilder, _a73, "PgMacaddrBuilder");
    PgMacaddr = class extends (_b53 = PgColumn, _a74 = entityKind, _b53) {
      getSQLType() {
        return "macaddr";
      }
    };
    __publicField(PgMacaddr, _a74, "PgMacaddr");
  }
});

// ../drizzle-orm/dist/pg-core/columns/macaddr8.js
function macaddr8(name2) {
  return new PgMacaddr8Builder(name2 ?? "");
}
var _a75, _b54, PgMacaddr8Builder, _a76, _b55, PgMacaddr8;
var init_macaddr8 = __esm({
  "../drizzle-orm/dist/pg-core/columns/macaddr8.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgMacaddr8Builder = class extends (_b54 = PgColumnBuilder, _a75 = entityKind, _b54) {
      constructor(name2) {
        super(name2, "string", "PgMacaddr8");
      }
      /** @internal */
      build(table4) {
        return new PgMacaddr8(table4, this.config);
      }
    };
    __publicField(PgMacaddr8Builder, _a75, "PgMacaddr8Builder");
    PgMacaddr8 = class extends (_b55 = PgColumn, _a76 = entityKind, _b55) {
      getSQLType() {
        return "macaddr8";
      }
    };
    __publicField(PgMacaddr8, _a76, "PgMacaddr8");
  }
});

// ../drizzle-orm/dist/pg-core/columns/numeric.js
function numeric(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgNumericBuilder(name2, config?.precision, config?.scale);
}
var _a77, _b56, PgNumericBuilder, _a78, _b57, PgNumeric;
var init_numeric = __esm({
  "../drizzle-orm/dist/pg-core/columns/numeric.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgNumericBuilder = class extends (_b56 = PgColumnBuilder, _a77 = entityKind, _b56) {
      constructor(name2, precision, scale) {
        super(name2, "string", "PgNumeric");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table4) {
        return new PgNumeric(table4, this.config);
      }
    };
    __publicField(PgNumericBuilder, _a77, "PgNumericBuilder");
    PgNumeric = class extends (_b57 = PgColumn, _a78 = entityKind, _b57) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "precision");
        __publicField(this, "scale");
        this.precision = config.precision;
        this.scale = config.scale;
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    __publicField(PgNumeric, _a78, "PgNumeric");
  }
});

// ../drizzle-orm/dist/pg-core/columns/point.js
function point(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgPointTupleBuilder(name2);
  }
  return new PgPointObjectBuilder(name2);
}
var _a79, _b58, PgPointTupleBuilder, _a80, _b59, PgPointTuple, _a81, _b60, PgPointObjectBuilder, _a82, _b61, PgPointObject;
var init_point = __esm({
  "../drizzle-orm/dist/pg-core/columns/point.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgPointTupleBuilder = class extends (_b58 = PgColumnBuilder, _a79 = entityKind, _b58) {
      constructor(name2) {
        super(name2, "array", "PgPointTuple");
      }
      /** @internal */
      build(table4) {
        return new PgPointTuple(
          table4,
          this.config
        );
      }
    };
    __publicField(PgPointTupleBuilder, _a79, "PgPointTupleBuilder");
    PgPointTuple = class extends (_b59 = PgColumn, _a80 = entityKind, _b59) {
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return [Number.parseFloat(x), Number.parseFloat(y)];
        }
        return [value.x, value.y];
      }
      mapToDriverValue(value) {
        return `(${value[0]},${value[1]})`;
      }
    };
    __publicField(PgPointTuple, _a80, "PgPointTuple");
    PgPointObjectBuilder = class extends (_b60 = PgColumnBuilder, _a81 = entityKind, _b60) {
      constructor(name2) {
        super(name2, "json", "PgPointObject");
      }
      /** @internal */
      build(table4) {
        return new PgPointObject(
          table4,
          this.config
        );
      }
    };
    __publicField(PgPointObjectBuilder, _a81, "PgPointObjectBuilder");
    PgPointObject = class extends (_b61 = PgColumn, _a82 = entityKind, _b61) {
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return { x: Number.parseFloat(x), y: Number.parseFloat(y) };
        }
        return value;
      }
      mapToDriverValue(value) {
        return `(${value.x},${value.y})`;
      }
    };
    __publicField(PgPointObject, _a82, "PgPointObject");
  }
});

// ../drizzle-orm/dist/pg-core/columns/postgis_extension/utils.js
function hexToBytes(hex) {
  const bytes = [];
  for (let c = 0; c < hex.length; c += 2) {
    bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));
  }
  return new Uint8Array(bytes);
}
function bytesToFloat64(bytes, offset) {
  const buffer = new ArrayBuffer(8);
  const view4 = new DataView(buffer);
  for (let i = 0; i < 8; i++) {
    view4.setUint8(i, bytes[offset + i]);
  }
  return view4.getFloat64(0, true);
}
function parseEWKB(hex) {
  const bytes = hexToBytes(hex);
  let offset = 0;
  const byteOrder = bytes[offset];
  offset += 1;
  const view4 = new DataView(bytes.buffer);
  const geomType = view4.getUint32(offset, byteOrder === 1);
  offset += 4;
  let _srid;
  if (geomType & 536870912) {
    _srid = view4.getUint32(offset, byteOrder === 1);
    offset += 4;
  }
  if ((geomType & 65535) === 1) {
    const x = bytesToFloat64(bytes, offset);
    offset += 8;
    const y = bytesToFloat64(bytes, offset);
    offset += 8;
    return [x, y];
  }
  throw new Error("Unsupported geometry type");
}
var init_utils3 = __esm({
  "../drizzle-orm/dist/pg-core/columns/postgis_extension/utils.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/columns/postgis_extension/geometry.js
function geometry(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgGeometryBuilder(name2);
  }
  return new PgGeometryObjectBuilder(name2);
}
var _a83, _b62, PgGeometryBuilder, _a84, _b63, PgGeometry, _a85, _b64, PgGeometryObjectBuilder, _a86, _b65, PgGeometryObject;
var init_geometry = __esm({
  "../drizzle-orm/dist/pg-core/columns/postgis_extension/geometry.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_utils3();
    PgGeometryBuilder = class extends (_b62 = PgColumnBuilder, _a83 = entityKind, _b62) {
      constructor(name2) {
        super(name2, "array", "PgGeometry");
      }
      /** @internal */
      build(table4) {
        return new PgGeometry(
          table4,
          this.config
        );
      }
    };
    __publicField(PgGeometryBuilder, _a83, "PgGeometryBuilder");
    PgGeometry = class extends (_b63 = PgColumn, _a84 = entityKind, _b63) {
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        return parseEWKB(value);
      }
      mapToDriverValue(value) {
        return `point(${value[0]} ${value[1]})`;
      }
    };
    __publicField(PgGeometry, _a84, "PgGeometry");
    PgGeometryObjectBuilder = class extends (_b64 = PgColumnBuilder, _a85 = entityKind, _b64) {
      constructor(name2) {
        super(name2, "json", "PgGeometryObject");
      }
      /** @internal */
      build(table4) {
        return new PgGeometryObject(
          table4,
          this.config
        );
      }
    };
    __publicField(PgGeometryObjectBuilder, _a85, "PgGeometryObjectBuilder");
    PgGeometryObject = class extends (_b65 = PgColumn, _a86 = entityKind, _b65) {
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        const parsed = parseEWKB(value);
        return { x: parsed[0], y: parsed[1] };
      }
      mapToDriverValue(value) {
        return `point(${value.x} ${value.y})`;
      }
    };
    __publicField(PgGeometryObject, _a86, "PgGeometryObject");
  }
});

// ../drizzle-orm/dist/pg-core/columns/real.js
function real(name2) {
  return new PgRealBuilder(name2 ?? "");
}
var _a87, _b66, PgRealBuilder, _a88, _b67, PgReal;
var init_real = __esm({
  "../drizzle-orm/dist/pg-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgRealBuilder = class extends (_b66 = PgColumnBuilder, _a87 = entityKind, _b66) {
      constructor(name2, length) {
        super(name2, "number", "PgReal");
        this.config.length = length;
      }
      /** @internal */
      build(table4) {
        return new PgReal(table4, this.config);
      }
    };
    __publicField(PgRealBuilder, _a87, "PgRealBuilder");
    PgReal = class extends (_b67 = PgColumn, _a88 = entityKind, _b67) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "mapFromDriverValue", (value) => {
          if (typeof value === "string") {
            return Number.parseFloat(value);
          }
          return value;
        });
      }
      getSQLType() {
        return "real";
      }
    };
    __publicField(PgReal, _a88, "PgReal");
  }
});

// ../drizzle-orm/dist/pg-core/columns/serial.js
function serial(name2) {
  return new PgSerialBuilder(name2 ?? "");
}
var _a89, _b68, PgSerialBuilder, _a90, _b69, PgSerial;
var init_serial = __esm({
  "../drizzle-orm/dist/pg-core/columns/serial.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgSerialBuilder = class extends (_b68 = PgColumnBuilder, _a89 = entityKind, _b68) {
      constructor(name2) {
        super(name2, "number", "PgSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table4) {
        return new PgSerial(table4, this.config);
      }
    };
    __publicField(PgSerialBuilder, _a89, "PgSerialBuilder");
    PgSerial = class extends (_b69 = PgColumn, _a90 = entityKind, _b69) {
      getSQLType() {
        return "serial";
      }
    };
    __publicField(PgSerial, _a90, "PgSerial");
  }
});

// ../drizzle-orm/dist/pg-core/columns/smallint.js
function smallint(name2) {
  return new PgSmallIntBuilder(name2 ?? "");
}
var _a91, _b70, PgSmallIntBuilder, _a92, _b71, PgSmallInt;
var init_smallint = __esm({
  "../drizzle-orm/dist/pg-core/columns/smallint.js"() {
    "use strict";
    init_entity();
    init_common2();
    init_int_common();
    PgSmallIntBuilder = class extends (_b70 = PgIntColumnBaseBuilder, _a91 = entityKind, _b70) {
      constructor(name2) {
        super(name2, "number", "PgSmallInt");
      }
      /** @internal */
      build(table4) {
        return new PgSmallInt(table4, this.config);
      }
    };
    __publicField(PgSmallIntBuilder, _a91, "PgSmallIntBuilder");
    PgSmallInt = class extends (_b71 = PgColumn, _a92 = entityKind, _b71) {
      constructor() {
        super(...arguments);
        __publicField(this, "mapFromDriverValue", (value) => {
          if (typeof value === "string") {
            return Number(value);
          }
          return value;
        });
      }
      getSQLType() {
        return "smallint";
      }
    };
    __publicField(PgSmallInt, _a92, "PgSmallInt");
  }
});

// ../drizzle-orm/dist/pg-core/columns/smallserial.js
function smallserial(name2) {
  return new PgSmallSerialBuilder(name2 ?? "");
}
var _a93, _b72, PgSmallSerialBuilder, _a94, _b73, PgSmallSerial;
var init_smallserial = __esm({
  "../drizzle-orm/dist/pg-core/columns/smallserial.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgSmallSerialBuilder = class extends (_b72 = PgColumnBuilder, _a93 = entityKind, _b72) {
      constructor(name2) {
        super(name2, "number", "PgSmallSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table4) {
        return new PgSmallSerial(
          table4,
          this.config
        );
      }
    };
    __publicField(PgSmallSerialBuilder, _a93, "PgSmallSerialBuilder");
    PgSmallSerial = class extends (_b73 = PgColumn, _a94 = entityKind, _b73) {
      getSQLType() {
        return "smallserial";
      }
    };
    __publicField(PgSmallSerial, _a94, "PgSmallSerial");
  }
});

// ../drizzle-orm/dist/pg-core/columns/text.js
function text(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgTextBuilder(name2, config);
}
var _a95, _b74, PgTextBuilder, _a96, _b75, PgText;
var init_text = __esm({
  "../drizzle-orm/dist/pg-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgTextBuilder = class extends (_b74 = PgColumnBuilder, _a95 = entityKind, _b74) {
      constructor(name2, config) {
        super(name2, "string", "PgText");
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table4) {
        return new PgText(table4, this.config);
      }
    };
    __publicField(PgTextBuilder, _a95, "PgTextBuilder");
    PgText = class extends (_b75 = PgColumn, _a96 = entityKind, _b75) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return "text";
      }
    };
    __publicField(PgText, _a96, "PgText");
  }
});

// ../drizzle-orm/dist/pg-core/columns/time.js
function time(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgTimeBuilder(name2, config.withTimezone ?? false, config.precision);
}
var _a97, _b76, PgTimeBuilder, _a98, _b77, PgTime;
var init_time = __esm({
  "../drizzle-orm/dist/pg-core/columns/time.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgTimeBuilder = class extends (_b76 = PgDateColumnBaseBuilder, _a97 = entityKind, _b76) {
      constructor(name2, withTimezone, precision) {
        super(name2, "string", "PgTime");
        this.withTimezone = withTimezone;
        this.precision = precision;
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table4) {
        return new PgTime(table4, this.config);
      }
    };
    __publicField(PgTimeBuilder, _a97, "PgTimeBuilder");
    PgTime = class extends (_b77 = PgColumn, _a98 = entityKind, _b77) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `time${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTime, _a98, "PgTime");
  }
});

// ../drizzle-orm/dist/pg-core/columns/timestamp.js
function timestamp(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new PgTimestampStringBuilder(name2, config.withTimezone ?? false, config.precision);
  }
  return new PgTimestampBuilder(name2, config?.withTimezone ?? false, config?.precision);
}
var _a99, _b78, PgTimestampBuilder, _a100, _b79, PgTimestamp, _a101, _b80, PgTimestampStringBuilder, _a102, _b81, PgTimestampString;
var init_timestamp = __esm({
  "../drizzle-orm/dist/pg-core/columns/timestamp.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgTimestampBuilder = class extends (_b78 = PgDateColumnBaseBuilder, _a99 = entityKind, _b78) {
      constructor(name2, withTimezone, precision) {
        super(name2, "date", "PgTimestamp");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table4) {
        return new PgTimestamp(table4, this.config);
      }
    };
    __publicField(PgTimestampBuilder, _a99, "PgTimestampBuilder");
    PgTimestamp = class extends (_b79 = PgColumn, _a100 = entityKind, _b79) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        __publicField(this, "mapFromDriverValue", (value) => {
          return new Date(this.withTimezone ? value : value + "+0000");
        });
        __publicField(this, "mapToDriverValue", (value) => {
          return value.toISOString();
        });
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : ` (${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTimestamp, _a100, "PgTimestamp");
    PgTimestampStringBuilder = class extends (_b80 = PgDateColumnBaseBuilder, _a101 = entityKind, _b80) {
      constructor(name2, withTimezone, precision) {
        super(name2, "string", "PgTimestampString");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table4) {
        return new PgTimestampString(
          table4,
          this.config
        );
      }
    };
    __publicField(PgTimestampStringBuilder, _a101, "PgTimestampStringBuilder");
    PgTimestampString = class extends (_b81 = PgColumn, _a102 = entityKind, _b81) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTimestampString, _a102, "PgTimestampString");
  }
});

// ../drizzle-orm/dist/pg-core/columns/uuid.js
function uuid(name2) {
  return new PgUUIDBuilder(name2 ?? "");
}
var _a103, _b82, PgUUIDBuilder, _a104, _b83, PgUUID;
var init_uuid = __esm({
  "../drizzle-orm/dist/pg-core/columns/uuid.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common2();
    PgUUIDBuilder = class extends (_b82 = PgColumnBuilder, _a103 = entityKind, _b82) {
      constructor(name2) {
        super(name2, "string", "PgUUID");
      }
      /**
       * Adds `default gen_random_uuid()` to the column definition.
       */
      defaultRandom() {
        return this.default(sql`gen_random_uuid()`);
      }
      /** @internal */
      build(table4) {
        return new PgUUID(table4, this.config);
      }
    };
    __publicField(PgUUIDBuilder, _a103, "PgUUIDBuilder");
    PgUUID = class extends (_b83 = PgColumn, _a104 = entityKind, _b83) {
      getSQLType() {
        return "uuid";
      }
    };
    __publicField(PgUUID, _a104, "PgUUID");
  }
});

// ../drizzle-orm/dist/pg-core/columns/varchar.js
function varchar(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgVarcharBuilder(name2, config);
}
var _a105, _b84, PgVarcharBuilder, _a106, _b85, PgVarchar;
var init_varchar = __esm({
  "../drizzle-orm/dist/pg-core/columns/varchar.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgVarcharBuilder = class extends (_b84 = PgColumnBuilder, _a105 = entityKind, _b84) {
      constructor(name2, config) {
        super(name2, "string", "PgVarchar");
        this.config.length = config.length;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table4) {
        return new PgVarchar(table4, this.config);
      }
    };
    __publicField(PgVarcharBuilder, _a105, "PgVarcharBuilder");
    PgVarchar = class extends (_b85 = PgColumn, _a106 = entityKind, _b85) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
    __publicField(PgVarchar, _a106, "PgVarchar");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/bit.js
function bit(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgBinaryVectorBuilder(name2, config);
}
var _a107, _b86, PgBinaryVectorBuilder, _a108, _b87, PgBinaryVector;
var init_bit = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/bit.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgBinaryVectorBuilder = class extends (_b86 = PgColumnBuilder, _a107 = entityKind, _b86) {
      constructor(name2, config) {
        super(name2, "string", "PgBinaryVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table4) {
        return new PgBinaryVector(
          table4,
          this.config
        );
      }
    };
    __publicField(PgBinaryVectorBuilder, _a107, "PgBinaryVectorBuilder");
    PgBinaryVector = class extends (_b87 = PgColumn, _a108 = entityKind, _b87) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `bit(${this.dimensions})`;
      }
    };
    __publicField(PgBinaryVector, _a108, "PgBinaryVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/halfvec.js
function halfvec(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgHalfVectorBuilder(name2, config);
}
var _a109, _b88, PgHalfVectorBuilder, _a110, _b89, PgHalfVector;
var init_halfvec = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/halfvec.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgHalfVectorBuilder = class extends (_b88 = PgColumnBuilder, _a109 = entityKind, _b88) {
      constructor(name2, config) {
        super(name2, "array", "PgHalfVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table4) {
        return new PgHalfVector(
          table4,
          this.config
        );
      }
    };
    __publicField(PgHalfVectorBuilder, _a109, "PgHalfVectorBuilder");
    PgHalfVector = class extends (_b89 = PgColumn, _a110 = entityKind, _b89) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `halfvec(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
    __publicField(PgHalfVector, _a110, "PgHalfVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/sparsevec.js
function sparsevec(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgSparseVectorBuilder(name2, config);
}
var _a111, _b90, PgSparseVectorBuilder, _a112, _b91, PgSparseVector;
var init_sparsevec = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/sparsevec.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgSparseVectorBuilder = class extends (_b90 = PgColumnBuilder, _a111 = entityKind, _b90) {
      constructor(name2, config) {
        super(name2, "string", "PgSparseVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table4) {
        return new PgSparseVector(
          table4,
          this.config
        );
      }
    };
    __publicField(PgSparseVectorBuilder, _a111, "PgSparseVectorBuilder");
    PgSparseVector = class extends (_b91 = PgColumn, _a112 = entityKind, _b91) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `sparsevec(${this.dimensions})`;
      }
    };
    __publicField(PgSparseVector, _a112, "PgSparseVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/vector.js
function vector(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgVectorBuilder(name2, config);
}
var _a113, _b92, PgVectorBuilder, _a114, _b93, PgVector;
var init_vector = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/vector.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgVectorBuilder = class extends (_b92 = PgColumnBuilder, _a113 = entityKind, _b92) {
      constructor(name2, config) {
        super(name2, "array", "PgVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table4) {
        return new PgVector(table4, this.config);
      }
    };
    __publicField(PgVectorBuilder, _a113, "PgVectorBuilder");
    PgVector = class extends (_b93 = PgColumn, _a114 = entityKind, _b93) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `vector(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
    __publicField(PgVector, _a114, "PgVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/all.js
function getPgColumnBuilders() {
  return {
    bigint,
    bigserial,
    boolean,
    char,
    cidr,
    customType,
    date,
    doublePrecision,
    inet,
    integer,
    interval,
    json,
    jsonb,
    line,
    macaddr,
    macaddr8,
    numeric,
    point,
    geometry,
    real,
    serial,
    smallint,
    smallserial,
    text,
    time,
    timestamp,
    uuid,
    varchar,
    bit,
    halfvec,
    sparsevec,
    vector
  };
}
var init_all = __esm({
  "../drizzle-orm/dist/pg-core/columns/all.js"() {
    "use strict";
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_custom();
    init_date();
    init_double_precision();
    init_inet();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../drizzle-orm/dist/pg-core/table.js
function pgTableWithSchema(name2, columns, extraConfig, schema4, baseName = name2) {
  const rawTable = new PgTable(name2, schema4, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column4 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column4, rawTable));
      return [name22, column4];
    })
  );
  const builtColumnsForExtraConfig = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column4 = colBuilder.buildExtraConfigColumn(rawTable);
      return [name22, column4];
    })
  );
  const table4 = Object.assign(rawTable, builtColumns);
  table4[Table2.Symbol.Columns] = builtColumns;
  table4[Table2.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
  if (extraConfig) {
    table4[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return Object.assign(table4, {
    enableRLS: () => {
      table4[PgTable.Symbol.EnableRLS] = true;
      return table4;
    }
  });
}
var InlineForeignKeys, EnableRLS, _a115, _b94, _c2, _d2, _e2, PgTable, pgTable;
var init_table2 = __esm({
  "../drizzle-orm/dist/pg-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all();
    InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
    EnableRLS = Symbol.for("drizzle:EnableRLS");
    PgTable = class extends (_e2 = Table2, _d2 = entityKind, _c2 = InlineForeignKeys, _b94 = EnableRLS, _a115 = Table2.Symbol.ExtraConfigBuilder, _e2) {
      constructor() {
        super(...arguments);
        /**@internal */
        __publicField(this, _c2, []);
        /** @internal */
        __publicField(this, _b94, false);
        /** @internal */
        __publicField(this, _a115);
      }
    };
    __publicField(PgTable, _d2, "PgTable");
    /** @internal */
    __publicField(PgTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys,
      EnableRLS
    }));
    pgTable = (name2, columns, extraConfig) => {
      return pgTableWithSchema(name2, columns, extraConfig, void 0);
    };
  }
});

// ../drizzle-orm/dist/pg-core/primary-keys.js
var _a116, PrimaryKeyBuilder, _a117, PrimaryKey;
var init_primary_keys = __esm({
  "../drizzle-orm/dist/pg-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table2();
    _a116 = entityKind;
    PrimaryKeyBuilder = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table4) {
        return new PrimaryKey(table4, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder, _a116, "PgPrimaryKeyBuilder");
    _a117 = entityKind;
    PrimaryKey = class {
      constructor(table4, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table4;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column4) => column4.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey, _a117, "PgPrimaryKey");
  }
});

// ../drizzle-orm/dist/relations.js
function getOperators() {
  return {
    and,
    between,
    eq,
    exists,
    gt,
    gte,
    ilike,
    inArray,
    isNull,
    isNotNull,
    like,
    lt,
    lte,
    ne,
    not,
    notBetween,
    notExists,
    notLike,
    notIlike,
    notInArray,
    or,
    sql
  };
}
function getOrderByOperators() {
  return {
    sql,
    asc,
    desc
  };
}
function extractTablesRelationalConfig(schema4, configHelpers) {
  if (Object.keys(schema4).length === 1 && "default" in schema4 && !is(schema4["default"], Table2)) {
    schema4 = schema4["default"];
  }
  const tableNamesMap = {};
  const relationsBuffer = {};
  const tablesConfig = {};
  for (const [key, value] of Object.entries(schema4)) {
    if (is(value, Table2)) {
      const dbName = getTableUniqueName(value);
      const bufferedRelations = relationsBuffer[dbName];
      tableNamesMap[dbName] = key;
      tablesConfig[key] = {
        tsName: key,
        dbName: value[Table2.Symbol.Name],
        schema: value[Table2.Symbol.Schema],
        columns: value[Table2.Symbol.Columns],
        relations: bufferedRelations?.relations ?? {},
        primaryKey: bufferedRelations?.primaryKey ?? []
      };
      for (const column4 of Object.values(
        value[Table2.Symbol.Columns]
      )) {
        if (column4.primary) {
          tablesConfig[key].primaryKey.push(column4);
        }
      }
      const extraConfig = value[Table2.Symbol.ExtraConfigBuilder]?.(value[Table2.Symbol.ExtraConfigColumns]);
      if (extraConfig) {
        for (const configEntry of Object.values(extraConfig)) {
          if (is(configEntry, PrimaryKeyBuilder)) {
            tablesConfig[key].primaryKey.push(...configEntry.columns);
          }
        }
      }
    } else if (is(value, Relations)) {
      const dbName = getTableUniqueName(value.table);
      const tableName = tableNamesMap[dbName];
      const relations2 = value.config(
        configHelpers(value.table)
      );
      let primaryKey;
      for (const [relationName, relation] of Object.entries(relations2)) {
        if (tableName) {
          const tableConfig = tablesConfig[tableName];
          tableConfig.relations[relationName] = relation;
          if (primaryKey) {
            tableConfig.primaryKey.push(...primaryKey);
          }
        } else {
          if (!(dbName in relationsBuffer)) {
            relationsBuffer[dbName] = {
              relations: {},
              primaryKey
            };
          }
          relationsBuffer[dbName].relations[relationName] = relation;
        }
      }
    }
  }
  return { tables: tablesConfig, tableNamesMap };
}
function relations(table4, relations2) {
  return new Relations(
    table4,
    (helpers) => Object.fromEntries(
      Object.entries(relations2(helpers)).map(([key, value]) => [
        key,
        value.withFieldName(key)
      ])
    )
  );
}
function createOne(sourceTable) {
  return function one(table4, config) {
    return new One(
      sourceTable,
      table4,
      config,
      config?.fields.reduce((res, f) => res && f.notNull, true) ?? false
    );
  };
}
function createMany(sourceTable) {
  return function many(referencedTable, config) {
    return new Many(sourceTable, referencedTable, config);
  };
}
function normalizeRelation(schema4, tableNamesMap, relation) {
  if (is(relation, One) && relation.config) {
    return {
      fields: relation.config.fields,
      references: relation.config.references
    };
  }
  const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
  if (!referencedTableTsName) {
    throw new Error(
      `Table "${relation.referencedTable[Table2.Symbol.Name]}" not found in schema`
    );
  }
  const referencedTableConfig = schema4[referencedTableTsName];
  if (!referencedTableConfig) {
    throw new Error(`Table "${referencedTableTsName}" not found in schema`);
  }
  const sourceTable = relation.sourceTable;
  const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
  if (!sourceTableTsName) {
    throw new Error(
      `Table "${sourceTable[Table2.Symbol.Name]}" not found in schema`
    );
  }
  const reverseRelations = [];
  for (const referencedTableRelation of Object.values(
    referencedTableConfig.relations
  )) {
    if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
      reverseRelations.push(referencedTableRelation);
    }
  }
  if (reverseRelations.length > 1) {
    throw relation.relationName ? new Error(
      `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
    ) : new Error(
      `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table2.Symbol.Name]}". Please specify relation name`
    );
  }
  if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
    return {
      fields: reverseRelations[0].config.references,
      references: reverseRelations[0].config.fields
    };
  }
  throw new Error(
    `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
  );
}
function createTableRelationsHelpers(sourceTable) {
  return {
    one: createOne(sourceTable),
    many: createMany(sourceTable)
  };
}
function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
  const result = {};
  for (const [
    selectionItemIndex,
    selectionItem
  ] of buildQueryResultSelection.entries()) {
    if (selectionItem.isJson) {
      const relation = tableConfig.relations[selectionItem.tsKey];
      const rawSubRows = row[selectionItemIndex];
      const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
      result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(
        tablesConfig,
        tablesConfig[selectionItem.relationTableTsKey],
        subRows,
        selectionItem.selection,
        mapColumnValue
      ) : subRows.map(
        (subRow) => mapRelationalRow(
          tablesConfig,
          tablesConfig[selectionItem.relationTableTsKey],
          subRow,
          selectionItem.selection,
          mapColumnValue
        )
      );
    } else {
      const value = mapColumnValue(row[selectionItemIndex]);
      const field = selectionItem.field;
      let decoder;
      if (is(field, Column2)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
    }
  }
  return result;
}
var _a118, Relation, _a119, Relations, _a120, _b95, _One, One, _a121, _b96, _Many, Many;
var init_relations = __esm({
  "../drizzle-orm/dist/relations.js"() {
    "use strict";
    init_table();
    init_column();
    init_entity();
    init_primary_keys();
    init_expressions();
    init_sql();
    _a118 = entityKind;
    Relation = class {
      constructor(sourceTable, referencedTable, relationName) {
        __publicField(this, "referencedTableName");
        __publicField(this, "fieldName");
        this.sourceTable = sourceTable;
        this.referencedTable = referencedTable;
        this.relationName = relationName;
        this.referencedTableName = referencedTable[Table2.Symbol.Name];
      }
    };
    __publicField(Relation, _a118, "Relation");
    _a119 = entityKind;
    Relations = class {
      constructor(table4, config) {
        this.table = table4;
        this.config = config;
      }
    };
    __publicField(Relations, _a119, "Relations");
    _One = class _One extends (_b95 = Relation, _a120 = entityKind, _b95) {
      constructor(sourceTable, referencedTable, config, isNullable) {
        super(sourceTable, referencedTable, config?.relationName);
        this.config = config;
        this.isNullable = isNullable;
      }
      withFieldName(fieldName) {
        const relation = new _One(
          this.sourceTable,
          this.referencedTable,
          this.config,
          this.isNullable
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
    __publicField(_One, _a120, "One");
    One = _One;
    _Many = class _Many extends (_b96 = Relation, _a121 = entityKind, _b96) {
      constructor(sourceTable, referencedTable, config) {
        super(sourceTable, referencedTable, config?.relationName);
        this.config = config;
      }
      withFieldName(fieldName) {
        const relation = new _Many(
          this.sourceTable,
          this.referencedTable,
          this.config
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
    __publicField(_Many, _a121, "Many");
    Many = _Many;
  }
});

// ../drizzle-orm/dist/sql/functions/aggregate.js
function count(expression) {
  return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
}
function countDistinct(expression) {
  return sql`count(distinct ${expression})`.mapWith(Number);
}
function avg(expression) {
  return sql`avg(${expression})`.mapWith(String);
}
function avgDistinct(expression) {
  return sql`avg(distinct ${expression})`.mapWith(String);
}
function sum(expression) {
  return sql`sum(${expression})`.mapWith(String);
}
function sumDistinct(expression) {
  return sql`sum(distinct ${expression})`.mapWith(String);
}
function max(expression) {
  return sql`max(${expression})`.mapWith(is(expression, Column2) ? expression : String);
}
function min(expression) {
  return sql`min(${expression})`.mapWith(is(expression, Column2) ? expression : String);
}
var init_aggregate = __esm({
  "../drizzle-orm/dist/sql/functions/aggregate.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/functions/vector.js
function toSql(value) {
  return JSON.stringify(value);
}
function l2Distance(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <-> ${toSql(value)}`;
  }
  return sql`${column4} <-> ${value}`;
}
function l1Distance(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <+> ${toSql(value)}`;
  }
  return sql`${column4} <+> ${value}`;
}
function innerProduct(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <#> ${toSql(value)}`;
  }
  return sql`${column4} <#> ${value}`;
}
function cosineDistance(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <=> ${toSql(value)}`;
  }
  return sql`${column4} <=> ${value}`;
}
function hammingDistance(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <~> ${toSql(value)}`;
  }
  return sql`${column4} <~> ${value}`;
}
function jaccardDistance(column4, value) {
  if (Array.isArray(value)) {
    return sql`${column4} <%> ${toSql(value)}`;
  }
  return sql`${column4} <%> ${value}`;
}
var init_vector2 = __esm({
  "../drizzle-orm/dist/sql/functions/vector.js"() {
    "use strict";
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/functions/index.js
var init_functions = __esm({
  "../drizzle-orm/dist/sql/functions/index.js"() {
    "use strict";
    init_aggregate();
    init_vector2();
  }
});

// ../drizzle-orm/dist/sql/index.js
var init_sql2 = __esm({
  "../drizzle-orm/dist/sql/index.js"() {
    "use strict";
    init_expressions();
    init_functions();
    init_sql();
  }
});

// ../drizzle-orm/dist/index.js
var dist_exports = {};
__export(dist_exports, {
  BaseName: () => BaseName,
  Column: () => Column2,
  ColumnAliasProxyHandler: () => ColumnAliasProxyHandler,
  ColumnBuilder: () => ColumnBuilder,
  Columns: () => Columns,
  ConsoleLogWriter: () => ConsoleLogWriter,
  DefaultLogger: () => DefaultLogger,
  DrizzleError: () => DrizzleError,
  ExtraConfigBuilder: () => ExtraConfigBuilder,
  ExtraConfigColumns: () => ExtraConfigColumns,
  FakePrimitiveParam: () => FakePrimitiveParam,
  IsAlias: () => IsAlias,
  Many: () => Many,
  Name: () => Name,
  NoopLogger: () => NoopLogger,
  One: () => One,
  OriginalName: () => OriginalName,
  Param: () => Param,
  Placeholder: () => Placeholder,
  QueryPromise: () => QueryPromise,
  Relation: () => Relation,
  RelationTableAliasProxyHandler: () => RelationTableAliasProxyHandler,
  Relations: () => Relations,
  SQL: () => SQL,
  Schema: () => Schema,
  StringChunk: () => StringChunk,
  Subquery: () => Subquery,
  Table: () => Table2,
  TableAliasProxyHandler: () => TableAliasProxyHandler,
  TransactionRollbackError: () => TransactionRollbackError,
  View: () => View3,
  ViewBaseConfig: () => ViewBaseConfig,
  WithSubquery: () => WithSubquery,
  aliasedRelation: () => aliasedRelation,
  aliasedTable: () => aliasedTable,
  aliasedTableColumn: () => aliasedTableColumn,
  and: () => and,
  applyMixins: () => applyMixins,
  arrayContained: () => arrayContained,
  arrayContains: () => arrayContains,
  arrayOverlaps: () => arrayOverlaps,
  asc: () => asc,
  avg: () => avg,
  avgDistinct: () => avgDistinct,
  between: () => between,
  bindIfParam: () => bindIfParam,
  cosineDistance: () => cosineDistance,
  count: () => count,
  countDistinct: () => countDistinct,
  createMany: () => createMany,
  createOne: () => createOne,
  createTableRelationsHelpers: () => createTableRelationsHelpers,
  desc: () => desc,
  entityKind: () => entityKind,
  eq: () => eq,
  exists: () => exists,
  extractTablesRelationalConfig: () => extractTablesRelationalConfig,
  fillPlaceholders: () => fillPlaceholders,
  getColumnNameAndConfig: () => getColumnNameAndConfig,
  getOperators: () => getOperators,
  getOrderByOperators: () => getOrderByOperators,
  getTableColumns: () => getTableColumns,
  getTableLikeName: () => getTableLikeName,
  getTableName: () => getTableName,
  getTableUniqueName: () => getTableUniqueName,
  gt: () => gt,
  gte: () => gte,
  hammingDistance: () => hammingDistance,
  hasOwnEntityKind: () => hasOwnEntityKind,
  haveSameKeys: () => haveSameKeys,
  ilike: () => ilike,
  inArray: () => inArray,
  innerProduct: () => innerProduct,
  is: () => is,
  isConfig: () => isConfig,
  isDriverValueEncoder: () => isDriverValueEncoder,
  isNotNull: () => isNotNull,
  isNull: () => isNull,
  isSQLWrapper: () => isSQLWrapper,
  isTable: () => isTable,
  jaccardDistance: () => jaccardDistance,
  l1Distance: () => l1Distance,
  l2Distance: () => l2Distance,
  like: () => like,
  lt: () => lt,
  lte: () => lte,
  mapColumnsInAliasedSQLToAlias: () => mapColumnsInAliasedSQLToAlias,
  mapColumnsInSQLToAlias: () => mapColumnsInSQLToAlias,
  mapRelationalRow: () => mapRelationalRow,
  mapResultRow: () => mapResultRow,
  mapUpdateSet: () => mapUpdateSet,
  max: () => max,
  min: () => min,
  name: () => name,
  ne: () => ne,
  noopDecoder: () => noopDecoder,
  noopEncoder: () => noopEncoder,
  noopMapper: () => noopMapper,
  normalizeRelation: () => normalizeRelation,
  not: () => not,
  notBetween: () => notBetween,
  notExists: () => notExists,
  notIlike: () => notIlike,
  notInArray: () => notInArray,
  notLike: () => notLike,
  or: () => or,
  orderSelectedFields: () => orderSelectedFields,
  param: () => param,
  placeholder: () => placeholder,
  relations: () => relations,
  sql: () => sql,
  sum: () => sum,
  sumDistinct: () => sumDistinct
});
var init_dist = __esm({
  "../drizzle-orm/dist/index.js"() {
    "use strict";
    init_alias();
    init_column_builder();
    init_column();
    init_entity();
    init_errors();
    init_expressions2();
    init_logger();
    init_operations();
    init_query_promise();
    init_relations();
    init_sql2();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
  }
});

// ../drizzle-orm/dist/pg-core/alias.js
var init_alias2 = __esm({
  "../drizzle-orm/dist/pg-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/checks.js
var _a122, CheckBuilder, _a123, Check;
var init_checks = __esm({
  "../drizzle-orm/dist/pg-core/checks.js"() {
    "use strict";
    init_entity();
    _a122 = entityKind;
    CheckBuilder = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      /** @internal */
      build(table4) {
        return new Check(table4, this);
      }
    };
    __publicField(CheckBuilder, _a122, "PgCheckBuilder");
    _a123 = entityKind;
    Check = class {
      constructor(table4, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table4;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check, _a123, "PgCheck");
  }
});

// ../drizzle-orm/dist/pg-core/columns/index.js
var init_columns = __esm({
  "../drizzle-orm/dist/pg-core/columns/index.js"() {
    "use strict";
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_common2();
    init_custom();
    init_date();
    init_double_precision();
    init_enum();
    init_inet();
    init_int_common();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/delete.js
var _a124, _b97, PgDeleteBase;
var init_delete = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_table();
    init_tracing();
    init_utils2();
    PgDeleteBase = class extends (_b97 = QueryPromise, _a124 = entityKind, _b97) {
      constructor(table4, session, dialect4, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues);
          });
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields = this.config.table[Table2.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgDeleteBase, _a124, "PgDelete");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/insert.js
var _a125, PgInsertBuilder, _a126, _b98, PgInsertBase;
var init_insert = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table();
    init_tracing();
    init_utils2();
    _a125 = entityKind;
    PgInsertBuilder = class {
      constructor(table4, session, dialect4, withList) {
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.withList = withList;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
      }
    };
    __publicField(PgInsertBuilder, _a125, "PgInsertBuilder");
    PgInsertBase = class extends (_b98 = QueryPromise, _a126 = entityKind, _b98) {
      constructor(table4, values, session, dialect4, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues);
          });
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, values, withList };
      }
      returning(fields = this.config.table[Table2.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /**
       * Adds an `on conflict do nothing` clause to the query.
       *
       * Calling this method simply avoids inserting a row as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
       *
       * @param config The `target` and `where` clauses.
       *
       * @example
       * ```ts
       * // Insert one row and cancel the insert if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing();
       *
       * // Explicitly specify conflict target
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing({ target: cars.id });
       * ```
       */
      onConflictDoNothing(config = {}) {
        if (config.target === void 0) {
          this.config.onConflict = sql`do nothing`;
        } else {
          let targetColumn = "";
          targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
          const whereSql = config.where ? sql` where ${config.where}` : void 0;
          this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
        }
        return this;
      }
      /**
       * Adds an `on conflict do update` clause to the query.
       *
       * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
       *
       * @param config The `target`, `set` and `where` clauses.
       *
       * @example
       * ```ts
       * // Update the row if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'Porsche' }
       *   });
       *
       * // Upsert with 'where' clause
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'newBMW' },
       *     targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
       *   });
       * ```
       */
      onConflictDoUpdate(config) {
        if (config.where && (config.targetWhere || config.setWhere)) {
          throw new Error(
            'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
          );
        }
        const whereSql = config.where ? sql` where ${config.where}` : void 0;
        const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
        const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        let targetColumn = "";
        targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
        this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgInsertBase, _a126, "PgInsert");
  }
});

// ../drizzle-orm/dist/casing.js
function toSnakeCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.map((word) => word.toLowerCase()).join("_");
}
function toCamelCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.reduce((acc, word, i) => {
    const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
    return acc + formattedWord;
  }, "");
}
function noopCase(input) {
  return input;
}
var _a127, CasingCache;
var init_casing = __esm({
  "../drizzle-orm/dist/casing.js"() {
    "use strict";
    init_entity();
    init_table();
    _a127 = entityKind;
    CasingCache = class {
      constructor(casing2) {
        /** @internal */
        __publicField(this, "cache", {});
        __publicField(this, "cachedTables", {});
        __publicField(this, "convert");
        this.convert = casing2 === "snake_case" ? toSnakeCase : casing2 === "camelCase" ? toCamelCase : noopCase;
      }
      getColumnCasing(column4) {
        if (!column4.keyAsName)
          return column4.name;
        const schema4 = column4.table[Table2.Symbol.Schema] ?? "public";
        const tableName = column4.table[Table2.Symbol.OriginalName];
        const key = `${schema4}.${tableName}.${column4.name}`;
        if (!this.cache[key]) {
          this.cacheTable(column4.table);
        }
        return this.cache[key];
      }
      cacheTable(table4) {
        const schema4 = table4[Table2.Symbol.Schema] ?? "public";
        const tableName = table4[Table2.Symbol.OriginalName];
        const tableKey2 = `${schema4}.${tableName}`;
        if (!this.cachedTables[tableKey2]) {
          for (const column4 of Object.values(table4[Table2.Symbol.Columns])) {
            const columnKey = `${tableKey2}.${column4.name}`;
            this.cache[columnKey] = this.convert(column4.name);
          }
          this.cachedTables[tableKey2] = true;
        }
      }
      clearCache() {
        this.cache = {};
        this.cachedTables = {};
      }
    };
    __publicField(CasingCache, _a127, "CasingCache");
  }
});

// ../drizzle-orm/dist/pg-core/view-base.js
var _a128, _b99, PgViewBase;
var init_view_base = __esm({
  "../drizzle-orm/dist/pg-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    PgViewBase = class extends (_b99 = View3, _a128 = entityKind, _b99) {
    };
    __publicField(PgViewBase, _a128, "PgViewBase");
  }
});

// ../drizzle-orm/dist/pg-core/dialect.js
var _a129, PgDialect;
var init_dialect = __esm({
  "../drizzle-orm/dist/pg-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors();
    init_columns();
    init_table2();
    init_relations();
    init_sql2();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_view_base();
    _a129 = entityKind;
    PgDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      async migrate(migrations, session, config) {
        const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at bigint
			)
		`;
        await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for await (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name2) {
        return `"${name2}"`;
      }
      escapeParam(num) {
        return `$${num + 1}`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length)
          return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table4, where, returning, withList }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
      }
      buildUpdateSet(table4, set) {
        const tableColumns = table4[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table4, set, where, returning, withList }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table4, set);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, PgColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(field);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table4,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table4, Subquery) ? table4._.alias : is(table4, PgViewBase) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : getTableName(table4)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        let distinctSql;
        if (distinct) {
          distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
        }
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = (() => {
          if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
            let fullName = sql`${sql.identifier(table4[Table2.Symbol.OriginalName])}`;
            if (table4[Table2.Symbol.Schema]) {
              fullName = sql`${sql.identifier(table4[Table2.Symbol.Schema])}.${fullName}`;
            }
            return sql`${fullName} ${sql.identifier(table4[Table2.Symbol.Name])}`;
          }
          return table4;
        })();
        const joinsArray = [];
        if (joins) {
          for (const [index4, joinMeta] of joins.entries()) {
            if (index4 === 0) {
              joinsArray.push(sql` `);
            }
            const table22 = joinMeta.table;
            const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
            if (is(table22, PgTable)) {
              const tableName = table22[PgTable.Symbol.Name];
              const tableSchema = table22[PgTable.Symbol.Schema];
              const origTableName = table22[PgTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
              );
            } else if (is(table22, View3)) {
              const viewName = table22[ViewBaseConfig].name;
              const viewSchema = table22[ViewBaseConfig].schema;
              const origViewName = table22[ViewBaseConfig].originalName;
              const alias = viewName === origViewName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table22} on ${joinMeta.on}`
              );
            }
            if (index4 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        const joinsSql = sql.join(joinsArray);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
        }
        let groupBySql;
        if (groupBy && groupBy.length > 0) {
          groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const lockingClauseSql = sql.empty();
        if (lockingClause) {
          const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
          if (lockingClause.config.of) {
            clauseSql.append(
              sql` of ${sql.join(
                Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
                sql`, `
              )}`
            );
          }
          if (lockingClause.config.noWait) {
            clauseSql.append(sql` no wait`);
          } else if (lockingClause.config.skipLocked) {
            clauseSql.append(sql` skip locked`);
          }
          lockingClauseSql.append(clauseSql);
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const singleOrderBy of orderBy) {
            if (is(singleOrderBy, PgColumn)) {
              orderByValues.push(sql.identifier(singleOrderBy.name));
            } else if (is(singleOrderBy, SQL)) {
              for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
                const chunk = singleOrderBy.queryChunks[i];
                if (is(chunk, PgColumn)) {
                  singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
                }
              }
              orderByValues.push(sql`${singleOrderBy}`);
            } else {
              orderByValues.push(sql`${singleOrderBy}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table4, values, onConflict, returning, withList }) {
        const valuesSqlList = [];
        const columns = table4[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(([_2, col]) => !col.shouldDisableInsert());
        const insertOrder = colEntries.map(
          ([, column4]) => sql.identifier(this.casing.getColumnCasing(column4))
        );
        for (const [valueIndex, value] of values.entries()) {
          const valueList = [];
          for (const [fieldName, col] of colEntries) {
            const colValue = value[fieldName];
            if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
              if (col.defaultFn !== void 0) {
                const defaultFnResult = col.defaultFn();
                const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                valueList.push(defaultValue);
              } else if (!col.default && col.onUpdateFn !== void 0) {
                const onUpdateFnResult = col.onUpdateFn();
                const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                valueList.push(newValue);
              } else {
                valueList.push(sql`default`);
              }
            } else {
              valueList.push(colValue);
            }
          }
          valuesSqlList.push(valueList);
          if (valueIndex < values.length - 1) {
            valuesSqlList.push(sql`, `);
          }
        }
        const withSql = this.buildWithCTE(withList);
        const valuesSql = sql.join(valuesSqlList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
        return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
      }
      buildRefreshMaterializedViewQuery({ view: view4, concurrently, withNoData }) {
        const concurrentlySql = concurrently ? sql` concurrently` : void 0;
        const withNoDataSql = withNoData ? sql` with no data` : void 0;
        return sql`refresh materialized view${concurrentlySql} ${view4}${withNoDataSql}`;
      }
      prepareTyping(encoder) {
        if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
          return "json";
        } else if (is(encoder, PgNumeric)) {
          return "decimal";
        } else if (is(encoder, PgTime)) {
          return "time";
        } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
          return "timestamp";
        } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
          return "date";
        } else if (is(encoder, PgUUID)) {
          return "uuid";
        } else {
          return "none";
        }
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          prepareTyping: this.prepareTyping,
          invokeSource
        });
      }
      // buildRelationalQueryWithPK({
      // 	fullSchema,
      // 	schema,
      // 	tableNamesMap,
      // 	table,
      // 	tableConfig,
      // 	queryConfig: config,
      // 	tableAlias,
      // 	isRoot = false,
      // 	joinOn,
      // }: {
      // 	fullSchema: Record<string, unknown>;
      // 	schema: TablesRelationalConfig;
      // 	tableNamesMap: Record<string, string>;
      // 	table: PgTable;
      // 	tableConfig: TableRelationalConfig;
      // 	queryConfig: true | DBQueryConfig<'many', true>;
      // 	tableAlias: string;
      // 	isRoot?: boolean;
      // 	joinOn?: SQL;
      // }): BuildRelationalQueryResult<PgTable, PgColumn> {
      // 	// For { "<relation>": true }, return a table with selection of all columns
      // 	if (config === true) {
      // 		const selectionEntries = Object.entries(tableConfig.columns);
      // 		const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
      // 			[key, value],
      // 		) => ({
      // 			dbKey: value.name,
      // 			tsKey: key,
      // 			field: value as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection,
      // 		};
      // 	}
      // 	// let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// let selectionForBuild = selection;
      // 	const aliasedColumns = Object.fromEntries(
      // 		Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
      // 	);
      // 	const aliasedRelations = Object.fromEntries(
      // 		Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
      // 	);
      // 	const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
      // 	let where, hasUserDefinedWhere;
      // 	if (config.where) {
      // 		const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
      // 		where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
      // 		hasUserDefinedWhere = !!where;
      // 	}
      // 	where = and(joinOn, where);
      // 	// const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
      // 	let joins: Join[] = [];
      // 	let selectedColumns: string[] = [];
      // 	// Figure out which columns to select
      // 	if (config.columns) {
      // 		let isIncludeMode = false;
      // 		for (const [field, value] of Object.entries(config.columns)) {
      // 			if (value === undefined) {
      // 				continue;
      // 			}
      // 			if (field in tableConfig.columns) {
      // 				if (!isIncludeMode && value === true) {
      // 					isIncludeMode = true;
      // 				}
      // 				selectedColumns.push(field);
      // 			}
      // 		}
      // 		if (selectedColumns.length > 0) {
      // 			selectedColumns = isIncludeMode
      // 				? selectedColumns.filter((c) => config.columns?.[c] === true)
      // 				: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
      // 		}
      // 	} else {
      // 		// Select all columns if selection is not specified
      // 		selectedColumns = Object.keys(tableConfig.columns);
      // 	}
      // 	// for (const field of selectedColumns) {
      // 	// 	const column = tableConfig.columns[field]! as PgColumn;
      // 	// 	fieldsSelection.push({ tsKey: field, value: column });
      // 	// }
      // 	let initiallySelectedRelations: {
      // 		tsKey: string;
      // 		queryConfig: true | DBQueryConfig<'many', false>;
      // 		relation: Relation;
      // 	}[] = [];
      // 	// let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// Figure out which relations to select
      // 	if (config.with) {
      // 		initiallySelectedRelations = Object.entries(config.with)
      // 			.filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
      // 			.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
      // 	}
      // 	const manyRelations = initiallySelectedRelations.filter((r) =>
      // 		is(r.relation, Many)
      // 		&& (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
      // 	);
      // 	// If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
      // 	const isInnermostQuery = manyRelations.length < 2;
      // 	const selectedExtras: {
      // 		tsKey: string;
      // 		value: SQL.Aliased;
      // 	}[] = [];
      // 	// Figure out which extras to select
      // 	if (isInnermostQuery && config.extras) {
      // 		const extras = typeof config.extras === 'function'
      // 			? config.extras(aliasedFields, { sql })
      // 			: config.extras;
      // 		for (const [tsKey, value] of Object.entries(extras)) {
      // 			selectedExtras.push({
      // 				tsKey,
      // 				value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
      // 			});
      // 		}
      // 	}
      // 	// Transform `fieldsSelection` into `selection`
      // 	// `fieldsSelection` shouldn't be used after this point
      // 	// for (const { tsKey, value, isExtra } of fieldsSelection) {
      // 	// 	selection.push({
      // 	// 		dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
      // 	// 		tsKey,
      // 	// 		field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
      // 	// 		relationTableTsKey: undefined,
      // 	// 		isJson: false,
      // 	// 		isExtra,
      // 	// 		selection: [],
      // 	// 	});
      // 	// }
      // 	let orderByOrig = typeof config.orderBy === 'function'
      // 		? config.orderBy(aliasedFields, orderByOperators)
      // 		: config.orderBy ?? [];
      // 	if (!Array.isArray(orderByOrig)) {
      // 		orderByOrig = [orderByOrig];
      // 	}
      // 	const orderBy = orderByOrig.map((orderByValue) => {
      // 		if (is(orderByValue, Column)) {
      // 			return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
      // 		}
      // 		return mapColumnsInSQLToAlias(orderByValue, tableAlias);
      // 	});
      // 	const limit = isInnermostQuery ? config.limit : undefined;
      // 	const offset = isInnermostQuery ? config.offset : undefined;
      // 	// For non-root queries without additional config except columns, return a table with selection
      // 	if (
      // 		!isRoot
      // 		&& initiallySelectedRelations.length === 0
      // 		&& selectedExtras.length === 0
      // 		&& !where
      // 		&& orderBy.length === 0
      // 		&& limit === undefined
      // 		&& offset === undefined
      // 	) {
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection: selectedColumns.map((key) => ({
      // 				dbKey: tableConfig.columns[key]!.name,
      // 				tsKey: key,
      // 				field: tableConfig.columns[key] as PgColumn,
      // 				relationTableTsKey: undefined,
      // 				isJson: false,
      // 				selection: [],
      // 			})),
      // 		};
      // 	}
      // 	const selectedRelationsWithoutPK:
      // 	// Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of initiallySelectedRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length > 0) {
      // 			continue;
      // 		}
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithoutPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 			nestedQueryRelation: relation,
      // 		});
      // 		const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
      // 		joins.push({
      // 			on: sql`true`,
      // 			table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: true,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
      // 		is(r.relation, One)
      // 	);
      // 	// Process all One relations with PKs, because they can all be joined on the same level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of oneRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length === 0) {
      // 			continue;
      // 		}
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
      // 			sql.join(
      // 				builtRelation.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelation.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: is(builtRelation.sql, SQL)
      // 				? new Subquery(builtRelation.sql, {}, relationTableAlias)
      // 				: aliasedTable(builtRelation.sql, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: is(builtRelation.sql, SQL),
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	let distinct: PgSelectConfig['distinct'];
      // 	let tableFrom: PgTable | Subquery = table;
      // 	// Process first Many relation - each one requires a nested subquery
      // 	const manyRelation = manyRelations[0];
      // 	if (manyRelation) {
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			relation,
      // 		} = manyRelation;
      // 		distinct = {
      // 			on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
      // 		};
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelationJoin = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const builtRelationSelectionField = sql`case when ${
      // 			sql.identifier(relationTableAlias)
      // 		} is null then '[]' else json_agg(json_build_array(${
      // 			sql.join(
      // 				builtRelationJoin.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		})) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelationJoin.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: isLateralJoin
      // 				? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
      // 				: aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: isLateralJoin,
      // 		});
      // 		// Build the "from" subquery with the remaining Many relations
      // 		const builtTableFrom = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table,
      // 			tableConfig,
      // 			queryConfig: {
      // 				...config,
      // 				where: undefined,
      // 				orderBy: undefined,
      // 				limit: undefined,
      // 				offset: undefined,
      // 				with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
      // 					(result, { tsKey, queryConfig: configValue }) => {
      // 						result[tsKey] = configValue;
      // 						return result;
      // 					},
      // 					{},
      // 				),
      // 			},
      // 			tableAlias,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field: builtRelationSelectionField,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelationJoin.selection,
      // 		});
      // 		// selection = builtTableFrom.selection.map((item) =>
      // 		// 	is(item.field, SQL.Aliased)
      // 		// 		? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 		// 		: item
      // 		// );
      // 		// selectionForBuild = [{
      // 		// 	dbKey: '*',
      // 		// 	tsKey: '*',
      // 		// 	field: sql`${sql.identifier(tableAlias)}.*`,
      // 		// 	selection: [],
      // 		// 	isJson: false,
      // 		// 	relationTableTsKey: undefined,
      // 		// }];
      // 		// const newSelectionItem: (typeof selection)[number] = {
      // 		// 	dbKey: selectedRelationTsKey,
      // 		// 	tsKey: selectedRelationTsKey,
      // 		// 	field,
      // 		// 	relationTableTsKey: relationTableTsName,
      // 		// 	isJson: true,
      // 		// 	selection: builtRelationJoin.selection,
      // 		// };
      // 		// selection.push(newSelectionItem);
      // 		// selectionForBuild.push(newSelectionItem);
      // 		tableFrom = is(builtTableFrom.sql, PgTable)
      // 			? builtTableFrom.sql
      // 			: new Subquery(builtTableFrom.sql, {}, tableAlias);
      // 	}
      // 	if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
      // 		throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
      // 	}
      // 	let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
      // 	function prepareSelectedColumns() {
      // 		return selectedColumns.map((key) => ({
      // 			dbKey: tableConfig.columns[key]!.name,
      // 			tsKey: key,
      // 			field: tableConfig.columns[key] as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	function prepareSelectedExtras() {
      // 		return selectedExtras.map((item) => ({
      // 			dbKey: item.value.fieldAlias,
      // 			tsKey: item.tsKey,
      // 			field: item.value,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	if (isRoot) {
      // 		selection = [
      // 			...prepareSelectedColumns(),
      // 			...prepareSelectedExtras(),
      // 		];
      // 	}
      // 	if (hasUserDefinedWhere || orderBy.length > 0) {
      // 		tableFrom = new Subquery(
      // 			this.buildSelectQuery({
      // 				table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 				fields: {},
      // 				fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 					path: [],
      // 					field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 				})),
      // 				joins,
      // 				distinct,
      // 			}),
      // 			{},
      // 			tableAlias,
      // 		);
      // 		selectionForBuild = selection.map((item) =>
      // 			is(item.field, SQL.Aliased)
      // 				? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 				: item
      // 		);
      // 		joins = [];
      // 		distinct = undefined;
      // 	}
      // 	const result = this.buildSelectQuery({
      // 		table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 		fields: {},
      // 		fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 			path: [],
      // 			field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 		})),
      // 		where,
      // 		limit,
      // 		offset,
      // 		joins,
      // 		orderBy,
      // 		distinct,
      // 	});
      // 	return {
      // 		tableTsKey: tableConfig.tsName,
      // 		sql: result,
      // 		selection,
      // 	};
      // }
      buildRelationalQueryWithoutPK({
        fullSchema,
        schema: schema4,
        tableNamesMap,
        table: table4,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column4 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column4 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema4, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQueryWithoutPK({
              fullSchema,
              schema: schema4,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema4[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_build_array(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table4, tableAlias),
              fields: {},
              fieldsFlat: [{
                path: [],
                field: sql.raw("*")
              }],
              where,
              limit,
              offset,
              orderBy,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = [];
          } else {
            result = aliasedTable(table4, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table4, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(PgDialect, _a129, "PgDialect");
  }
});

// ../drizzle-orm/dist/selection-proxy.js
var _a130, _SelectionProxyHandler, SelectionProxyHandler;
var init_selection_proxy = __esm({
  "../drizzle-orm/dist/selection-proxy.js"() {
    "use strict";
    init_alias();
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_view_common();
    _a130 = entityKind;
    _SelectionProxyHandler = class _SelectionProxyHandler {
      constructor(config) {
        __publicField(this, "config");
        this.config = { ...config };
      }
      get(subquery, prop) {
        if (prop === "_") {
          return {
            ...subquery["_"],
            selectedFields: new Proxy(
              subquery._.selectedFields,
              this
            )
          };
        }
        if (prop === ViewBaseConfig) {
          return {
            ...subquery[ViewBaseConfig],
            selectedFields: new Proxy(
              subquery[ViewBaseConfig].selectedFields,
              this
            )
          };
        }
        if (typeof prop === "symbol") {
          return subquery[prop];
        }
        const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View3) ? subquery[ViewBaseConfig].selectedFields : subquery;
        const value = columns[prop];
        if (is(value, SQL.Aliased)) {
          if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
            return value.sql;
          }
          const newValue = value.clone();
          newValue.isSelectionField = true;
          return newValue;
        }
        if (is(value, SQL)) {
          if (this.config.sqlBehavior === "sql") {
            return value;
          }
          throw new Error(
            `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
          );
        }
        if (is(value, Column2)) {
          if (this.config.alias) {
            return new Proxy(
              value,
              new ColumnAliasProxyHandler(
                new Proxy(
                  value.table,
                  new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)
                )
              )
            );
          }
          return value;
        }
        if (typeof value !== "object" || value === null) {
          return value;
        }
        return new Proxy(value, new _SelectionProxyHandler(this.config));
      }
    };
    __publicField(_SelectionProxyHandler, _a130, "SelectionProxyHandler");
    SelectionProxyHandler = _SelectionProxyHandler;
  }
});

// ../drizzle-orm/dist/query-builders/query-builder.js
var _a131, TypedQueryBuilder;
var init_query_builder = __esm({
  "../drizzle-orm/dist/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    _a131 = entityKind;
    TypedQueryBuilder = class {
      /** @internal */
      getSelectedFields() {
        return this._.selectedFields;
      }
    };
    __publicField(TypedQueryBuilder, _a131, "TypedQueryBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/select.js
function createSetOperator(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a132, PgSelectBuilder, _a133, _b100, PgSelectQueryBuilderBase, _a134, _b101, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
var init_select2 = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_view_base();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_tracing();
    init_utils2();
    init_utils2();
    init_view_common();
    _a132 = entityKind;
    PgSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList", []);
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        if (config.withList) {
          this.withList = config.withList;
        }
        this.distinct = config.distinct;
      }
      /**
       * Specify the table, subquery, or other target that you're
       * building a select query against.
       *
       * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
       */
      from(source) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, PgViewBase)) {
          fields = source[ViewBaseConfig].selectedFields;
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        return new PgSelectBase({
          table: source,
          fields,
          isPartialSelect,
          session: this.session,
          dialect: this.dialect,
          withList: this.withList,
          distinct: this.distinct
        });
      }
    };
    __publicField(PgSelectBuilder, _a132, "PgSelectBuilder");
    PgSelectQueryBuilderBase = class extends (_b100 = TypedQueryBuilder, _a133 = entityKind, _b100) {
      constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
        super();
        __publicField(this, "_");
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        __publicField(this, "session");
        __publicField(this, "dialect");
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left"));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right"));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner"));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full"));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/pg-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/pg-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/pg-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `intersect all` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets including all duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
         *
         * @example
         *
         * ```ts
         * // Select all products and quantities that are ordered by both regular and VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered
         * })
         * .from(regularCustomerOrders)
         * .intersectAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { intersectAll } from 'drizzle-orm/pg-core'
         *
         * await intersectAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "intersectAll", this.createSetOperator("intersect", true));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/pg-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        /**
         * Adds `except all` set operator to the query.
         *
         * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
         *
         * @example
         *
         * ```ts
         * // Select all products that are ordered by regular customers but not by VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered,
         * })
         * .from(regularCustomerOrders)
         * .exceptAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered,
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { exceptAll } from 'drizzle-orm/pg-core'
         *
         * await exceptAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "exceptAll", this.createSetOperator("except", true));
        this.config = {
          withList,
          table: table4,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect4;
        this._ = {
          selectedFields: fields
        };
        this.tableName = getTableLikeName(table4);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
      }
      createJoin(joinType) {
        return (table4, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table4);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table4, SQL)) {
              const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table4, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config = {}) {
        this.config.lockingClause = { strength, config };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgSelectQueryBuilderBase, _a133, "PgSelectQueryBuilder");
    PgSelectBase = class extends (_b101 = PgSelectQueryBuilderBase, _a134 = entityKind, _b101) {
      constructor() {
        super(...arguments);
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues);
          });
        });
      }
      /** @internal */
      _prepare(name2) {
        const { session, config, dialect: dialect4, joinsNotNullableMap } = this;
        if (!session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const fieldsList = orderSelectedFields(config.fields);
          const query = session.prepareQuery(dialect4.sqlToQuery(this.getSQL()), fieldsList, name2, true);
          query.joinsNotNullableMap = joinsNotNullableMap;
          return query;
        });
      }
      /**
       * Create a prepared statement for this query. This allows
       * the database to remember this query for the given session
       * and call it by name, rather than specifying the full query.
       *
       * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
       */
      prepare(name2) {
        return this._prepare(name2);
      }
    };
    __publicField(PgSelectBase, _a134, "PgSelect");
    applyMixins(PgSelectBase, [QueryPromise]);
    getPgSetOperators = () => ({
      union,
      unionAll,
      intersect,
      intersectAll,
      except,
      exceptAll
    });
    union = createSetOperator("union", false);
    unionAll = createSetOperator("union", true);
    intersect = createSetOperator("intersect", false);
    intersectAll = createSetOperator("intersect", true);
    except = createSetOperator("except", false);
    exceptAll = createSetOperator("except", true);
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/query-builder.js
var _a135, QueryBuilder;
var init_query_builder2 = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_dialect();
    init_selection_proxy();
    init_subquery();
    init_select2();
    _a135 = entityKind;
    QueryBuilder = class {
      constructor(dialect4) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        this.dialect = is(dialect4, PgDialect) ? dialect4 : void 0;
        this.dialectConfig = is(dialect4, PgDialect) ? void 0 : dialect4;
      }
      $with(alias) {
        const queryBuilder = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            distinct: { on }
          });
        }
        return { select, selectDistinct, selectDistinctOn };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect()
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: { on }
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new PgDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder, _a135, "PgQueryBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
var _a136, _b102, PgRefreshMaterializedView;
var init_refresh_materialized_view = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_tracing();
    PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
      constructor(view4, session, dialect4) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues);
          });
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { view: view4 };
      }
      concurrently() {
        if (this.config.withNoData !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.concurrently = true;
        return this;
      }
      withNoData() {
        if (this.config.concurrently !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.withNoData = true;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildRefreshMaterializedViewQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name2, true);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
    };
    __publicField(PgRefreshMaterializedView, _a136, "PgRefreshMaterializedView");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/select.types.js
var init_select_types = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/update.js
var _a137, PgUpdateBuilder, _a138, _b103, PgUpdateBase;
var init_update = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_table();
    init_utils2();
    _a137 = entityKind;
    PgUpdateBuilder = class {
      constructor(table4, session, dialect4, withList) {
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.withList = withList;
      }
      set(values) {
        return new PgUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        );
      }
    };
    __publicField(PgUpdateBuilder, _a137, "PgUpdateBuilder");
    PgUpdateBase = class extends (_b103 = QueryPromise, _a138 = entityKind, _b103) {
      constructor(table4, set, session, dialect4, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this._prepare().execute(placeholderValues);
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { set, table: table4, withList };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * await db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * await db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields = this.config.table[Table2.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgUpdateBase, _a138, "PgUpdate");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/index.js
var init_query_builders = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/index.js"() {
    "use strict";
    init_delete();
    init_insert();
    init_query_builder2();
    init_refresh_materialized_view();
    init_select2();
    init_select_types();
    init_update();
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/count.js
var _a139, _b104, _c3, _PgCountBuilder, PgCountBuilder;
var init_count = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _PgCountBuilder = class _PgCountBuilder extends (_c3 = SQL, _b104 = entityKind, _a139 = Symbol.toStringTag, _c3) {
      constructor(params) {
        super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a139, "PgCountBuilder");
        __publicField(this, "session");
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _PgCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_PgCountBuilder, _b104, "PgCountBuilder");
    PgCountBuilder = _PgCountBuilder;
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/query.js
var _a140, RelationalQueryBuilder, _a141, _b105, PgRelationalQuery;
var init_query = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    init_tracing();
    _a140 = entityKind;
    RelationalQueryBuilder = class {
      constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session) {
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
      }
      findMany(config) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        );
      }
      findFirst(config) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        );
      }
    };
    __publicField(RelationalQueryBuilder, _a140, "PgRelationalQueryBuilder");
    PgRelationalQuery = class extends (_b105 = QueryPromise, _a141 = entityKind, _b105) {
      constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session, config, mode) {
        super();
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
        this.config = config;
        this.mode = mode;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const { query, builtQuery } = this._toSQL();
          return this.session.prepareQuery(
            builtQuery,
            void 0,
            name2,
            true,
            (rawRows, mapColumnValue) => {
              const rows = rawRows.map(
                (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
              );
              if (this.mode === "first") {
                return rows[0];
              }
              return rows;
            }
          );
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      _getQuery() {
        return this.dialect.buildRelationalQueryWithoutPK({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
      }
      /** @internal */
      getSQL() {
        return this._getQuery().sql;
      }
      _toSQL() {
        const query = this._getQuery();
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { query, builtQuery };
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      execute() {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute();
        });
      }
    };
    __publicField(PgRelationalQuery, _a141, "PgRelationalQuery");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/raw.js
var _a142, _b106, PgRaw;
var init_raw = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/raw.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    PgRaw = class extends (_b106 = QueryPromise, _a142 = entityKind, _b106) {
      constructor(execute, sql2, query, mapBatchResult) {
        super();
        this.execute = execute;
        this.sql = sql2;
        this.query = query;
        this.mapBatchResult = mapBatchResult;
      }
      /** @internal */
      getSQL() {
        return this.sql;
      }
      getQuery() {
        return this.query;
      }
      mapResult(result, isFromBatch) {
        return isFromBatch ? this.mapBatchResult(result) : result;
      }
      _prepare() {
        return this;
      }
      /** @internal */
      isResponseInArrayMode() {
        return false;
      }
    };
    __publicField(PgRaw, _a142, "PgRaw");
  }
});

// ../drizzle-orm/dist/pg-core/db.js
var _a143, PgDatabase;
var init_db = __esm({
  "../drizzle-orm/dist/pg-core/db.js"() {
    "use strict";
    init_entity();
    init_query_builders();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count();
    init_query();
    init_raw();
    init_refresh_materialized_view();
    _a143 = entityKind;
    PgDatabase = class {
      constructor(dialect4, session, schema4) {
        __publicField(this, "query");
        this.dialect = dialect4;
        this.session = session;
        this._ = schema4 ? {
          schema: schema4.schema,
          fullSchema: schema4.fullSchema,
          tableNamesMap: schema4.tableNamesMap,
          session
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {},
          session
        };
        this.query = {};
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            this.query[tableName] = new RelationalQueryBuilder(
              schema4.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema4.fullSchema[tableName],
              columns,
              dialect4,
              session
            );
          }
        }
      }
      /**
       * Creates a subquery that defines a temporary named result set as a CTE.
       *
       * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param alias The alias for the subquery.
       *
       * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
       *
       * @example
       *
       * ```ts
       * // Create a subquery with alias 'sq' and use it in the select query
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * const result = await db.with(sq).select().from(sq);
       * ```
       *
       * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
       *
       * ```ts
       * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
       * const sq = db.$with('sq').as(db.select({
       *   name: sql<string>`upper(${users.name})`.as('name'),
       * })
       * .from(users));
       *
       * const result = await db.with(sq).select({ name: sq.name }).from(sq);
       * ```
       */
      $with(alias) {
        const self2 = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      $count(source, filters) {
        return new PgCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: { on }
          });
        }
        function update(table4) {
          return new PgUpdateBuilder(table4, self2.session, self2.dialect, queries);
        }
        function insert(table4) {
          return new PgInsertBuilder(table4, self2.session, self2.dialect, queries);
        }
        function delete_(table4) {
          return new PgDeleteBase(table4, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: { on }
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       *
       * // Update with returning clause
       * const updatedCar: Car[] = await db.update(cars)
       *   .set({ color: 'red' })
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      update(table4) {
        return new PgUpdateBuilder(table4, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       *
       * // Insert with returning clause
       * const insertedCar: Car[] = await db.insert(cars)
       *   .values({ brand: 'BMW' })
       *   .returning();
       * ```
       */
      insert(table4) {
        return new PgInsertBuilder(table4, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       *
       * // Delete with returning clause
       * const deletedCar: Car[] = await db.delete(cars)
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      delete(table4) {
        return new PgDeleteBase(table4, this.session, this.dialect);
      }
      refreshMaterializedView(view4) {
        return new PgRefreshMaterializedView(view4, this.session, this.dialect);
      }
      execute(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        const builtQuery = this.dialect.sqlToQuery(sequel);
        const prepared = this.session.prepareQuery(
          builtQuery,
          void 0,
          void 0,
          false
        );
        return new PgRaw(
          () => prepared.execute(),
          sequel,
          builtQuery,
          (result) => prepared.mapResult(result, true)
        );
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(PgDatabase, _a143, "PgDatabase");
  }
});

// ../drizzle-orm/dist/pg-core/indexes.js
var _a144, IndexBuilderOn, _a145, IndexBuilder, _a146, Index2;
var init_indexes = __esm({
  "../drizzle-orm/dist/pg-core/indexes.js"() {
    "use strict";
    init_sql();
    init_entity();
    init_columns();
    _a144 = entityKind;
    IndexBuilderOn = class {
      constructor(unique, name2) {
        this.unique = unique;
        this.name = name2;
      }
      on(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          false,
          this.name
        );
      }
      onOnly(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = it.defaultConfig;
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name
        );
      }
      /**
       * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
       *
       * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
       *
       * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
       *
       * @param method The name of the index method to be used
       * @param columns
       * @returns
       */
      using(method, ...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name,
          method
        );
      }
    };
    __publicField(IndexBuilderOn, _a144, "PgIndexBuilderOn");
    _a145 = entityKind;
    IndexBuilder = class {
      constructor(columns, unique, only, name2, method = "btree") {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique,
          only,
          method
        };
      }
      concurrently() {
        this.config.concurrently = true;
        return this;
      }
      with(obj) {
        this.config.with = obj;
        return this;
      }
      where(condition) {
        this.config.where = condition;
        return this;
      }
      /** @internal */
      build(table4) {
        return new Index2(this.config, table4);
      }
    };
    __publicField(IndexBuilder, _a145, "PgIndexBuilder");
    _a146 = entityKind;
    Index2 = class {
      constructor(config, table4) {
        __publicField(this, "config");
        this.config = { ...config, table: table4 };
      }
    };
    __publicField(Index2, _a146, "PgIndex");
  }
});

// ../drizzle-orm/dist/pg-core/policies.js
var _a147, PgPolicy;
var init_policies = __esm({
  "../drizzle-orm/dist/pg-core/policies.js"() {
    "use strict";
    init_entity();
    _a147 = entityKind;
    PgPolicy = class {
      constructor(name2, config) {
        __publicField(this, "as");
        __publicField(this, "for");
        __publicField(this, "to");
        __publicField(this, "using");
        __publicField(this, "withCheck");
        /** @internal */
        __publicField(this, "_linkedTable");
        this.name = name2;
        if (config) {
          this.as = config.as;
          this.for = config.for;
          this.to = config.to;
          this.using = config.using;
          this.withCheck = config.withCheck;
        }
      }
      link(table4) {
        this._linkedTable = table4;
        return this;
      }
    };
    __publicField(PgPolicy, _a147, "PgPolicy");
  }
});

// ../drizzle-orm/dist/pg-core/roles.js
var _a148, PgRole;
var init_roles = __esm({
  "../drizzle-orm/dist/pg-core/roles.js"() {
    "use strict";
    init_entity();
    _a148 = entityKind;
    PgRole = class {
      constructor(name2, config) {
        /** @internal */
        __publicField(this, "_existing");
        /** @internal */
        __publicField(this, "createDb");
        /** @internal */
        __publicField(this, "createRole");
        /** @internal */
        __publicField(this, "inherit");
        this.name = name2;
        if (config) {
          this.createDb = config.createDb;
          this.createRole = config.createRole;
          this.inherit = config.inherit;
        }
      }
      existing() {
        this._existing = true;
        return this;
      }
    };
    __publicField(PgRole, _a148, "PgRole");
  }
});

// ../drizzle-orm/dist/pg-core/sequence.js
function pgSequenceWithSchema(name2, options, schema4) {
  return new PgSequence(name2, options, schema4);
}
function isPgSequence(obj) {
  return is(obj, PgSequence);
}
var _a149, PgSequence;
var init_sequence = __esm({
  "../drizzle-orm/dist/pg-core/sequence.js"() {
    "use strict";
    init_entity();
    _a149 = entityKind;
    PgSequence = class {
      constructor(seqName, seqOptions, schema4) {
        this.seqName = seqName;
        this.seqOptions = seqOptions;
        this.schema = schema4;
      }
    };
    __publicField(PgSequence, _a149, "PgSequence");
  }
});

// ../drizzle-orm/dist/pg-core/view-common.js
var PgViewConfig;
var init_view_common2 = __esm({
  "../drizzle-orm/dist/pg-core/view-common.js"() {
    "use strict";
    PgViewConfig = Symbol.for("drizzle:PgViewConfig");
  }
});

// ../drizzle-orm/dist/pg-core/view.js
function pgViewWithSchema(name2, selection, schema4) {
  if (selection) {
    return new ManualViewBuilder(name2, selection, schema4);
  }
  return new ViewBuilder(name2, schema4);
}
function pgMaterializedViewWithSchema(name2, selection, schema4) {
  if (selection) {
    return new ManualMaterializedViewBuilder(name2, selection, schema4);
  }
  return new MaterializedViewBuilder(name2, schema4);
}
function isPgView(obj) {
  return is(obj, PgView2);
}
function isPgMaterializedView(obj) {
  return is(obj, PgMaterializedView);
}
var _a150, DefaultViewBuilderCore, _a151, _b107, ViewBuilder, _a152, _b108, ManualViewBuilder, _a153, MaterializedViewBuilderCore, _a154, _b109, MaterializedViewBuilder, _a155, _b110, ManualMaterializedViewBuilder, _a156, _b111, _c4, PgView2, PgMaterializedViewConfig, _a157, _b112, _c5, PgMaterializedView;
var init_view = __esm({
  "../drizzle-orm/dist/pg-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder2();
    init_table2();
    init_view_base();
    init_view_common2();
    _a150 = entityKind;
    DefaultViewBuilderCore = class {
      constructor(name2, schema4) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema4;
      }
      with(config) {
        this.config.with = config;
        return this;
      }
    };
    __publicField(DefaultViewBuilderCore, _a150, "PgDefaultViewBuilderCore");
    ViewBuilder = class extends (_b107 = DefaultViewBuilderCore, _a151 = entityKind, _b107) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgView2({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder, _a151, "PgViewBuilder");
    ManualViewBuilder = class extends (_b108 = DefaultViewBuilderCore, _a152 = entityKind, _b108) {
      constructor(name2, columns, schema4) {
        super(name2, schema4);
        __publicField(this, "columns");
        this.columns = getTableColumns(pgTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new PgView2({
            pgConfig: void 0,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgView2({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder, _a152, "PgManualViewBuilder");
    _a153 = entityKind;
    MaterializedViewBuilderCore = class {
      constructor(name2, schema4) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema4;
      }
      using(using) {
        this.config.using = using;
        return this;
      }
      with(config) {
        this.config.with = config;
        return this;
      }
      tablespace(tablespace) {
        this.config.tablespace = tablespace;
        return this;
      }
      withNoData() {
        this.config.withNoData = true;
        return this;
      }
    };
    __publicField(MaterializedViewBuilderCore, _a153, "PgMaterializedViewBuilderCore");
    MaterializedViewBuilder = class extends (_b109 = MaterializedViewBuilderCore, _a154 = entityKind, _b109) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              with: this.config.with,
              using: this.config.using,
              tablespace: this.config.tablespace,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(MaterializedViewBuilder, _a154, "PgMaterializedViewBuilder");
    ManualMaterializedViewBuilder = class extends (_b110 = MaterializedViewBuilderCore, _a155 = entityKind, _b110) {
      constructor(name2, columns, schema4) {
        super(name2, schema4);
        __publicField(this, "columns");
        this.columns = getTableColumns(pgTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualMaterializedViewBuilder, _a155, "PgManualMaterializedViewBuilder");
    PgView2 = class extends (_c4 = PgViewBase, _b111 = entityKind, _a156 = PgViewConfig, _c4) {
      constructor({ pgConfig, config }) {
        super(config);
        __publicField(this, _a156);
        if (pgConfig) {
          this[PgViewConfig] = {
            with: pgConfig.with
          };
        }
      }
    };
    __publicField(PgView2, _b111, "PgView");
    PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
    PgMaterializedView = class extends (_c5 = PgViewBase, _b112 = entityKind, _a157 = PgMaterializedViewConfig, _c5) {
      constructor({ pgConfig, config }) {
        super(config);
        __publicField(this, _a157);
        this[PgMaterializedViewConfig] = {
          with: pgConfig?.with,
          using: pgConfig?.using,
          tablespace: pgConfig?.tablespace,
          withNoData: pgConfig?.withNoData
        };
      }
    };
    __publicField(PgMaterializedView, _b112, "PgMaterializedView");
  }
});

// ../drizzle-orm/dist/pg-core/schema.js
var _a158, PgSchema5;
var init_schema = __esm({
  "../drizzle-orm/dist/pg-core/schema.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_enum();
    init_sequence();
    init_table2();
    init_view();
    _a158 = entityKind;
    PgSchema5 = class {
      constructor(schemaName) {
        __publicField(this, "table", (name2, columns, extraConfig) => {
          return pgTableWithSchema(name2, columns, extraConfig, this.schemaName);
        });
        __publicField(this, "view", (name2, columns) => {
          return pgViewWithSchema(name2, columns, this.schemaName);
        });
        __publicField(this, "materializedView", (name2, columns) => {
          return pgMaterializedViewWithSchema(name2, columns, this.schemaName);
        });
        __publicField(this, "enum", (name2, values) => {
          return pgEnumWithSchema(name2, values, this.schemaName);
        });
        __publicField(this, "sequence", (name2, options) => {
          return pgSequenceWithSchema(name2, options, this.schemaName);
        });
        this.schemaName = schemaName;
      }
      getSQL() {
        return new SQL([sql.identifier(this.schemaName)]);
      }
      shouldOmitSQLParens() {
        return true;
      }
    };
    __publicField(PgSchema5, _a158, "PgSchema");
  }
});

// ../drizzle-orm/dist/pg-core/session.js
var _a159, PgPreparedQuery, _a160, PgSession, _a161, _b113, PgTransaction;
var init_session = __esm({
  "../drizzle-orm/dist/pg-core/session.js"() {
    "use strict";
    init_entity();
    init_errors();
    init_sql2();
    init_tracing();
    init_db();
    _a159 = entityKind;
    PgPreparedQuery = class {
      constructor(query) {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.query = query;
      }
      getQuery() {
        return this.query;
      }
      mapResult(response, _isFromBatch) {
        return response;
      }
    };
    __publicField(PgPreparedQuery, _a159, "PgPreparedQuery");
    _a160 = entityKind;
    PgSession = class {
      constructor(dialect4) {
        this.dialect = dialect4;
      }
      execute(query) {
        return tracer.startActiveSpan("drizzle.operation", () => {
          const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
            return this.prepareQuery(
              this.dialect.sqlToQuery(query),
              void 0,
              void 0,
              false
            );
          });
          return prepared.execute();
        });
      }
      all(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0,
          void 0,
          false
        ).all();
      }
      async count(sql2) {
        const res = await this.execute(sql2);
        return Number(
          res[0]["count"]
        );
      }
    };
    __publicField(PgSession, _a160, "PgSession");
    PgTransaction = class extends (_b113 = PgDatabase, _a161 = entityKind, _b113) {
      constructor(dialect4, session, schema4, nestedIndex = 0) {
        super(dialect4, session, schema4);
        this.schema = schema4;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
      /** @internal */
      getTransactionConfigSQL(config) {
        const chunks = [];
        if (config.isolationLevel) {
          chunks.push(`isolation level ${config.isolationLevel}`);
        }
        if (config.accessMode) {
          chunks.push(config.accessMode);
        }
        if (typeof config.deferrable === "boolean") {
          chunks.push(config.deferrable ? "deferrable" : "not deferrable");
        }
        return sql.raw(chunks.join(" "));
      }
      setTransaction(config) {
        return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
      }
    };
    __publicField(PgTransaction, _a161, "PgTransaction");
  }
});

// ../drizzle-orm/dist/pg-core/subquery.js
var init_subquery2 = __esm({
  "../drizzle-orm/dist/pg-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/utils.js
function getTableConfig(table4) {
  const columns = Object.values(table4[Table2.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const foreignKeys = Object.values(table4[PgTable.Symbol.InlineForeignKeys]);
  const uniqueConstraints = [];
  const name2 = table4[Table2.Symbol.Name];
  const schema4 = table4[Table2.Symbol.Schema];
  const policies = [];
  const enableRLS = table4[PgTable.Symbol.EnableRLS];
  const extraConfigBuilder = table4[PgTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table4[Table2.Symbol.ExtraConfigColumns]);
    const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
    for (const builder of extraValues) {
      if (is(builder, IndexBuilder)) {
        indexes.push(builder.build(table4));
      } else if (is(builder, CheckBuilder)) {
        checks.push(builder.build(table4));
      } else if (is(builder, UniqueConstraintBuilder)) {
        uniqueConstraints.push(builder.build(table4));
      } else if (is(builder, PrimaryKeyBuilder)) {
        primaryKeys.push(builder.build(table4));
      } else if (is(builder, ForeignKeyBuilder)) {
        foreignKeys.push(builder.build(table4));
      } else if (is(builder, PgPolicy)) {
        policies.push(builder);
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2,
    schema: schema4,
    policies,
    enableRLS
  };
}
function getViewConfig(view4) {
  return {
    ...view4[ViewBaseConfig],
    ...view4[PgViewConfig]
  };
}
function getMaterializedViewConfig(view4) {
  return {
    ...view4[ViewBaseConfig],
    ...view4[PgMaterializedViewConfig]
  };
}
var init_utils4 = __esm({
  "../drizzle-orm/dist/pg-core/utils.js"() {
    "use strict";
    init_entity();
    init_table2();
    init_table();
    init_view_common();
    init_checks();
    init_foreign_keys();
    init_indexes();
    init_policies();
    init_primary_keys();
    init_unique_constraint();
    init_view_common2();
    init_view();
  }
});

// ../drizzle-orm/dist/pg-core/utils/index.js
var init_utils5 = __esm({
  "../drizzle-orm/dist/pg-core/utils/index.js"() {
    "use strict";
    init_array();
  }
});

// ../drizzle-orm/dist/pg-core/index.js
var init_pg_core = __esm({
  "../drizzle-orm/dist/pg-core/index.js"() {
    "use strict";
    init_alias2();
    init_checks();
    init_columns();
    init_db();
    init_dialect();
    init_foreign_keys();
    init_indexes();
    init_policies();
    init_primary_keys();
    init_query_builders();
    init_roles();
    init_schema();
    init_sequence();
    init_session();
    init_subquery2();
    init_table2();
    init_unique_constraint();
    init_utils4();
    init_utils5();
    init_view_common2();
    init_view();
  }
});

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

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

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

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

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

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

// ../drizzle-orm/dist/sqlite-core/alias.js
var init_alias3 = __esm({
  "../drizzle-orm/dist/sqlite-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/checks.js
var _a162, CheckBuilder2, _a163, Check2;
var init_checks2 = __esm({
  "../drizzle-orm/dist/sqlite-core/checks.js"() {
    "use strict";
    init_entity();
    _a162 = entityKind;
    CheckBuilder2 = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      build(table4) {
        return new Check2(table4, this);
      }
    };
    __publicField(CheckBuilder2, _a162, "SQLiteCheckBuilder");
    _a163 = entityKind;
    Check2 = class {
      constructor(table4, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table4;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check2, _a163, "SQLiteCheck");
  }
});

// ../drizzle-orm/dist/sqlite-core/foreign-keys.js
var _a164, ForeignKeyBuilder2, _a165, ForeignKey2;
var init_foreign_keys2 = __esm({
  "../drizzle-orm/dist/sqlite-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a164 = entityKind;
    ForeignKeyBuilder2 = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate");
        /** @internal */
        __publicField(this, "_onDelete");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action;
        return this;
      }
      /** @internal */
      build(table4) {
        return new ForeignKey2(table4, this);
      }
    };
    __publicField(ForeignKeyBuilder2, _a164, "SQLiteForeignKeyBuilder");
    _a165 = entityKind;
    ForeignKey2 = class {
      constructor(table4, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table4;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column4) => column4.name);
        const foreignColumnNames = foreignColumns.map((column4) => column4.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey2, _a165, "SQLiteForeignKey");
  }
});

// ../drizzle-orm/dist/sqlite-core/unique-constraint.js
function uniqueKeyName2(table4, columns) {
  return `${table4[TableName]}_${columns.join("_")}_unique`;
}
var _a166, UniqueConstraintBuilder2, _a167, UniqueOnConstraintBuilder2, _a168, UniqueConstraint2;
var init_unique_constraint2 = __esm({
  "../drizzle-orm/dist/sqlite-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a166 = entityKind;
    UniqueConstraintBuilder2 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        this.name = name2;
        this.columns = columns;
      }
      /** @internal */
      build(table4) {
        return new UniqueConstraint2(table4, this.columns, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder2, _a166, "SQLiteUniqueConstraintBuilder");
    _a167 = entityKind;
    UniqueOnConstraintBuilder2 = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder2(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder2, _a167, "SQLiteUniqueOnConstraintBuilder");
    _a168 = entityKind;
    UniqueConstraint2 = class {
      constructor(table4, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table4;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName2(this.table, this.columns.map((column4) => column4.name));
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint2, _a168, "SQLiteUniqueConstraint");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/common.js
var _a169, _b114, SQLiteColumnBuilder, _a170, _b115, SQLiteColumn;
var init_common3 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys2();
    init_unique_constraint2();
    SQLiteColumnBuilder = class extends (_b114 = ColumnBuilder, _a169 = entityKind, _b114) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        return this;
      }
      generatedAlwaysAs(as, config) {
        this.config.generated = {
          as,
          type: "always",
          mode: config?.mode ?? "virtual"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column4, table4) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return ((ref2, actions2) => {
            const builder = new ForeignKeyBuilder2(() => {
              const foreignColumn = ref2();
              return { columns: [column4], foreignColumns: [foreignColumn] };
            });
            if (actions2.onUpdate) {
              builder.onUpdate(actions2.onUpdate);
            }
            if (actions2.onDelete) {
              builder.onDelete(actions2.onDelete);
            }
            return builder.build(table4);
          })(ref, actions);
        });
      }
    };
    __publicField(SQLiteColumnBuilder, _a169, "SQLiteColumnBuilder");
    SQLiteColumn = class extends (_b115 = Column2, _a170 = entityKind, _b115) {
      constructor(table4, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName2(table4, [config.name]);
        }
        super(table4, config);
        this.table = table4;
      }
    };
    __publicField(SQLiteColumn, _a170, "SQLiteColumn");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/blob.js
function blob(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "json") {
    return new SQLiteBlobJsonBuilder(name2);
  }
  if (config?.mode === "bigint") {
    return new SQLiteBigIntBuilder(name2);
  }
  return new SQLiteBlobBufferBuilder(name2);
}
var _a171, _b116, SQLiteBigIntBuilder, _a172, _b117, SQLiteBigInt, _a173, _b118, SQLiteBlobJsonBuilder, _a174, _b119, SQLiteBlobJson, _a175, _b120, SQLiteBlobBufferBuilder, _a176, _b121, SQLiteBlobBuffer;
var init_blob = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/blob.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteBigIntBuilder = class extends (_b116 = SQLiteColumnBuilder, _a171 = entityKind, _b116) {
      constructor(name2) {
        super(name2, "bigint", "SQLiteBigInt");
      }
      /** @internal */
      build(table4) {
        return new SQLiteBigInt(table4, this.config);
      }
    };
    __publicField(SQLiteBigIntBuilder, _a171, "SQLiteBigIntBuilder");
    SQLiteBigInt = class extends (_b117 = SQLiteColumn, _a172 = entityKind, _b117) {
      getSQLType() {
        return "blob";
      }
      mapFromDriverValue(value) {
        return BigInt(Buffer.isBuffer(value) ? value.toString() : String.fromCodePoint(...value));
      }
      mapToDriverValue(value) {
        return Buffer.from(value.toString());
      }
    };
    __publicField(SQLiteBigInt, _a172, "SQLiteBigInt");
    SQLiteBlobJsonBuilder = class extends (_b118 = SQLiteColumnBuilder, _a173 = entityKind, _b118) {
      constructor(name2) {
        super(name2, "json", "SQLiteBlobJson");
      }
      /** @internal */
      build(table4) {
        return new SQLiteBlobJson(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteBlobJsonBuilder, _a173, "SQLiteBlobJsonBuilder");
    SQLiteBlobJson = class extends (_b119 = SQLiteColumn, _a174 = entityKind, _b119) {
      getSQLType() {
        return "blob";
      }
      mapFromDriverValue(value) {
        return JSON.parse(Buffer.isBuffer(value) ? value.toString() : String.fromCodePoint(...value));
      }
      mapToDriverValue(value) {
        return Buffer.from(JSON.stringify(value));
      }
    };
    __publicField(SQLiteBlobJson, _a174, "SQLiteBlobJson");
    SQLiteBlobBufferBuilder = class extends (_b120 = SQLiteColumnBuilder, _a175 = entityKind, _b120) {
      constructor(name2) {
        super(name2, "buffer", "SQLiteBlobBuffer");
      }
      /** @internal */
      build(table4) {
        return new SQLiteBlobBuffer(table4, this.config);
      }
    };
    __publicField(SQLiteBlobBufferBuilder, _a175, "SQLiteBlobBufferBuilder");
    SQLiteBlobBuffer = class extends (_b121 = SQLiteColumn, _a176 = entityKind, _b121) {
      getSQLType() {
        return "blob";
      }
    };
    __publicField(SQLiteBlobBuffer, _a176, "SQLiteBlobBuffer");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/custom.js
function customType2(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new SQLiteCustomColumnBuilder(
      name2,
      config,
      customTypeParams
    );
  };
}
var _a177, _b122, SQLiteCustomColumnBuilder, _a178, _b123, SQLiteCustomColumn;
var init_custom2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteCustomColumnBuilder = class extends (_b122 = SQLiteColumnBuilder, _a177 = entityKind, _b122) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "SQLiteCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table4) {
        return new SQLiteCustomColumn(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteCustomColumnBuilder, _a177, "SQLiteCustomColumnBuilder");
    SQLiteCustomColumn = class extends (_b123 = SQLiteColumn, _a178 = entityKind, _b123) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(SQLiteCustomColumn, _a178, "SQLiteCustomColumn");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/integer.js
function integer2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
    return new SQLiteTimestampBuilder(name2, config.mode);
  }
  if (config?.mode === "boolean") {
    return new SQLiteBooleanBuilder(name2, config.mode);
  }
  return new SQLiteIntegerBuilder(name2);
}
var _a179, _b124, SQLiteBaseIntegerBuilder, _a180, _b125, SQLiteBaseInteger, _a181, _b126, SQLiteIntegerBuilder, _a182, _b127, SQLiteInteger, _a183, _b128, SQLiteTimestampBuilder, _a184, _b129, SQLiteTimestamp, _a185, _b130, SQLiteBooleanBuilder, _a186, _b131, SQLiteBoolean;
var init_integer2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/integer.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_utils2();
    init_common3();
    SQLiteBaseIntegerBuilder = class extends (_b124 = SQLiteColumnBuilder, _a179 = entityKind, _b124) {
      constructor(name2, dataType, columnType) {
        super(name2, dataType, columnType);
        this.config.autoIncrement = false;
      }
      primaryKey(config) {
        if (config?.autoIncrement) {
          this.config.autoIncrement = true;
        }
        this.config.hasDefault = true;
        return super.primaryKey();
      }
    };
    __publicField(SQLiteBaseIntegerBuilder, _a179, "SQLiteBaseIntegerBuilder");
    SQLiteBaseInteger = class extends (_b125 = SQLiteColumn, _a180 = entityKind, _b125) {
      constructor() {
        super(...arguments);
        __publicField(this, "autoIncrement", this.config.autoIncrement);
      }
      getSQLType() {
        return "integer";
      }
    };
    __publicField(SQLiteBaseInteger, _a180, "SQLiteBaseInteger");
    SQLiteIntegerBuilder = class extends (_b126 = SQLiteBaseIntegerBuilder, _a181 = entityKind, _b126) {
      constructor(name2) {
        super(name2, "number", "SQLiteInteger");
      }
      build(table4) {
        return new SQLiteInteger(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteIntegerBuilder, _a181, "SQLiteIntegerBuilder");
    SQLiteInteger = class extends (_b127 = SQLiteBaseInteger, _a182 = entityKind, _b127) {
    };
    __publicField(SQLiteInteger, _a182, "SQLiteInteger");
    SQLiteTimestampBuilder = class extends (_b128 = SQLiteBaseIntegerBuilder, _a183 = entityKind, _b128) {
      constructor(name2, mode) {
        super(name2, "date", "SQLiteTimestamp");
        this.config.mode = mode;
      }
      /**
       * @deprecated Use `default()` with your own expression instead.
       *
       * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.
       */
      defaultNow() {
        return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
      }
      build(table4) {
        return new SQLiteTimestamp(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteTimestampBuilder, _a183, "SQLiteTimestampBuilder");
    SQLiteTimestamp = class extends (_b129 = SQLiteBaseInteger, _a184 = entityKind, _b129) {
      constructor() {
        super(...arguments);
        __publicField(this, "mode", this.config.mode);
      }
      mapFromDriverValue(value) {
        if (this.config.mode === "timestamp") {
          return new Date(value * 1e3);
        }
        return new Date(value);
      }
      mapToDriverValue(value) {
        const unix = value.getTime();
        if (this.config.mode === "timestamp") {
          return Math.floor(unix / 1e3);
        }
        return unix;
      }
    };
    __publicField(SQLiteTimestamp, _a184, "SQLiteTimestamp");
    SQLiteBooleanBuilder = class extends (_b130 = SQLiteBaseIntegerBuilder, _a185 = entityKind, _b130) {
      constructor(name2, mode) {
        super(name2, "boolean", "SQLiteBoolean");
        this.config.mode = mode;
      }
      build(table4) {
        return new SQLiteBoolean(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteBooleanBuilder, _a185, "SQLiteBooleanBuilder");
    SQLiteBoolean = class extends (_b131 = SQLiteBaseInteger, _a186 = entityKind, _b131) {
      constructor() {
        super(...arguments);
        __publicField(this, "mode", this.config.mode);
      }
      mapFromDriverValue(value) {
        return Number(value) === 1;
      }
      mapToDriverValue(value) {
        return value ? 1 : 0;
      }
    };
    __publicField(SQLiteBoolean, _a186, "SQLiteBoolean");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/numeric.js
function numeric2(name2) {
  return new SQLiteNumericBuilder(name2 ?? "");
}
var _a187, _b132, SQLiteNumericBuilder, _a188, _b133, SQLiteNumeric;
var init_numeric2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/numeric.js"() {
    "use strict";
    init_entity();
    init_common3();
    SQLiteNumericBuilder = class extends (_b132 = SQLiteColumnBuilder, _a187 = entityKind, _b132) {
      constructor(name2) {
        super(name2, "string", "SQLiteNumeric");
      }
      /** @internal */
      build(table4) {
        return new SQLiteNumeric(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteNumericBuilder, _a187, "SQLiteNumericBuilder");
    SQLiteNumeric = class extends (_b133 = SQLiteColumn, _a188 = entityKind, _b133) {
      getSQLType() {
        return "numeric";
      }
    };
    __publicField(SQLiteNumeric, _a188, "SQLiteNumeric");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/real.js
function real2(name2) {
  return new SQLiteRealBuilder(name2 ?? "");
}
var _a189, _b134, SQLiteRealBuilder, _a190, _b135, SQLiteReal;
var init_real2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_common3();
    SQLiteRealBuilder = class extends (_b134 = SQLiteColumnBuilder, _a189 = entityKind, _b134) {
      constructor(name2) {
        super(name2, "number", "SQLiteReal");
      }
      /** @internal */
      build(table4) {
        return new SQLiteReal(table4, this.config);
      }
    };
    __publicField(SQLiteRealBuilder, _a189, "SQLiteRealBuilder");
    SQLiteReal = class extends (_b135 = SQLiteColumn, _a190 = entityKind, _b135) {
      getSQLType() {
        return "real";
      }
    };
    __publicField(SQLiteReal, _a190, "SQLiteReal");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/text.js
function text2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "json") {
    return new SQLiteTextJsonBuilder(name2);
  }
  return new SQLiteTextBuilder(name2, config);
}
var _a191, _b136, SQLiteTextBuilder, _a192, _b137, SQLiteText, _a193, _b138, SQLiteTextJsonBuilder, _a194, _b139, SQLiteTextJson;
var init_text2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteTextBuilder = class extends (_b136 = SQLiteColumnBuilder, _a191 = entityKind, _b136) {
      constructor(name2, config) {
        super(name2, "string", "SQLiteText");
        this.config.enumValues = config.enum;
        this.config.length = config.length;
      }
      /** @internal */
      build(table4) {
        return new SQLiteText(table4, this.config);
      }
    };
    __publicField(SQLiteTextBuilder, _a191, "SQLiteTextBuilder");
    SQLiteText = class extends (_b137 = SQLiteColumn, _a192 = entityKind, _b137) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "enumValues", this.config.enumValues);
        __publicField(this, "length", this.config.length);
      }
      getSQLType() {
        return `text${this.config.length ? `(${this.config.length})` : ""}`;
      }
    };
    __publicField(SQLiteText, _a192, "SQLiteText");
    SQLiteTextJsonBuilder = class extends (_b138 = SQLiteColumnBuilder, _a193 = entityKind, _b138) {
      constructor(name2) {
        super(name2, "json", "SQLiteTextJson");
      }
      /** @internal */
      build(table4) {
        return new SQLiteTextJson(
          table4,
          this.config
        );
      }
    };
    __publicField(SQLiteTextJsonBuilder, _a193, "SQLiteTextJsonBuilder");
    SQLiteTextJson = class extends (_b139 = SQLiteColumn, _a194 = entityKind, _b139) {
      getSQLType() {
        return "text";
      }
      mapFromDriverValue(value) {
        return JSON.parse(value);
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
    };
    __publicField(SQLiteTextJson, _a194, "SQLiteTextJson");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/index.js
var init_columns2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/index.js"() {
    "use strict";
    init_blob();
    init_common3();
    init_custom2();
    init_integer2();
    init_numeric2();
    init_real2();
    init_text2();
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/all.js
function getSQLiteColumnBuilders() {
  return {
    blob,
    customType: customType2,
    integer: integer2,
    numeric: numeric2,
    real: real2,
    text: text2
  };
}
var init_all2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/all.js"() {
    "use strict";
    init_blob();
    init_custom2();
    init_integer2();
    init_numeric2();
    init_real2();
    init_text2();
  }
});

// ../drizzle-orm/dist/sqlite-core/table.js
function sqliteTableBase(name2, columns, extraConfig, schema4, baseName = name2) {
  const rawTable = new SQLiteTable(name2, schema4, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column4 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column4, rawTable));
      return [name22, column4];
    })
  );
  const table4 = Object.assign(rawTable, builtColumns);
  table4[Table2.Symbol.Columns] = builtColumns;
  table4[Table2.Symbol.ExtraConfigColumns] = builtColumns;
  if (extraConfig) {
    table4[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return table4;
}
var InlineForeignKeys2, _a195, _b140, _c6, _d3, _e3, SQLiteTable, sqliteTable;
var init_table3 = __esm({
  "../drizzle-orm/dist/sqlite-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all2();
    InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
    SQLiteTable = class extends (_e3 = Table2, _d3 = entityKind, _c6 = Table2.Symbol.Columns, _b140 = InlineForeignKeys2, _a195 = Table2.Symbol.ExtraConfigBuilder, _e3) {
      constructor() {
        super(...arguments);
        /** @internal */
        __publicField(this, _c6);
        /** @internal */
        __publicField(this, _b140, []);
        /** @internal */
        __publicField(this, _a195);
      }
    };
    __publicField(SQLiteTable, _d3, "SQLiteTable");
    /** @internal */
    __publicField(SQLiteTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys: InlineForeignKeys2
    }));
    sqliteTable = (name2, columns, extraConfig) => {
      return sqliteTableBase(name2, columns, extraConfig);
    };
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/delete.js
var _a196, _b141, SQLiteDeleteBase;
var init_delete2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table3();
    init_table();
    init_utils2();
    SQLiteDeleteBase = class extends (_b141 = QueryPromise, _a196 = entityKind, _b141) {
      constructor(table4, session, dialect4, withList) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute(placeholderValues) {
        return this._prepare().execute(placeholderValues);
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteDeleteBase, _a196, "SQLiteDelete");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/insert.js
var _a197, SQLiteInsertBuilder, _a198, _b142, SQLiteInsertBase;
var init_insert2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table3();
    init_table();
    init_utils2();
    _a197 = entityKind;
    SQLiteInsertBuilder = class {
      constructor(table4, session, dialect4, withList) {
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.withList = withList;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
      }
    };
    __publicField(SQLiteInsertBuilder, _a197, "SQLiteInsertBuilder");
    SQLiteInsertBase = class extends (_b142 = QueryPromise, _a198 = entityKind, _b142) {
      constructor(table4, values, session, dialect4, withList) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, values, withList };
      }
      returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /**
       * Adds an `on conflict do nothing` clause to the query.
       *
       * Calling this method simply avoids inserting a row as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
       *
       * @param config The `target` and `where` clauses.
       *
       * @example
       * ```ts
       * // Insert one row and cancel the insert if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing();
       *
       * // Explicitly specify conflict target
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing({ target: cars.id });
       * ```
       */
      onConflictDoNothing(config = {}) {
        if (config.target === void 0) {
          this.config.onConflict = sql`do nothing`;
        } else {
          const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
          const whereSql = config.where ? sql` where ${config.where}` : sql``;
          this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
        }
        return this;
      }
      /**
       * Adds an `on conflict do update` clause to the query.
       *
       * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
       *
       * @param config The `target`, `set` and `where` clauses.
       *
       * @example
       * ```ts
       * // Update the row if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'Porsche' }
       *   });
       *
       * // Upsert with 'where' clause
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'newBMW' },
       *     where: sql`${cars.createdAt} > '2023-01-01'::date`,
       *   });
       * ```
       */
      onConflictDoUpdate(config) {
        if (config.where && (config.targetWhere || config.setWhere)) {
          throw new Error(
            'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
          );
        }
        const whereSql = config.where ? sql` where ${config.where}` : void 0;
        const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
        const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
        const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        this.config.onConflict = sql`${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.config.returning ? this.all() : this.run();
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteInsertBase, _a198, "SQLiteInsert");
  }
});

// ../drizzle-orm/dist/sqlite-core/view-base.js
var _a199, _b143, SQLiteViewBase;
var init_view_base2 = __esm({
  "../drizzle-orm/dist/sqlite-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    SQLiteViewBase = class extends (_b143 = View3, _a199 = entityKind, _b143) {
    };
    __publicField(SQLiteViewBase, _a199, "SQLiteViewBase");
  }
});

// ../drizzle-orm/dist/sqlite-core/dialect.js
var _a200, SQLiteDialect, _a201, _b144, SQLiteSyncDialect, _a202, _b145, SQLiteAsyncDialect;
var init_dialect2 = __esm({
  "../drizzle-orm/dist/sqlite-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors();
    init_relations();
    init_sql2();
    init_sql();
    init_columns2();
    init_table3();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_view_base2();
    _a200 = entityKind;
    SQLiteDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      escapeName(name2) {
        return `"${name2}"`;
      }
      escapeParam(_num) {
        return "?";
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length)
          return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}delete from ${table4}${whereSql}${returningSql}${orderBySql}${limitSql}`;
      }
      buildUpdateSet(table4, set) {
        const tableColumns = table4[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table4, set);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, Column2)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            const tableName = field.table[Table2.Symbol.Name];
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildLimit(limit) {
        return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
      }
      buildOrderBy(orderBy) {
        const orderByList = [];
        if (orderBy) {
          for (const [index4, orderByValue] of orderBy.entries()) {
            orderByList.push(orderByValue);
            if (index4 < orderBy.length - 1) {
              orderByList.push(sql`, `);
            }
          }
        }
        return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table4,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table4, Subquery) ? table4._.alias : is(table4, SQLiteViewBase) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : getTableName(table4)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        const distinctSql = distinct ? sql` distinct` : void 0;
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = (() => {
          if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
            return sql`${sql.identifier(table4[Table2.Symbol.OriginalName])} ${sql.identifier(table4[Table2.Symbol.Name])}`;
          }
          return table4;
        })();
        const joinsArray = [];
        if (joins) {
          for (const [index4, joinMeta] of joins.entries()) {
            if (index4 === 0) {
              joinsArray.push(sql` `);
            }
            const table22 = joinMeta.table;
            if (is(table22, SQLiteTable)) {
              const tableName = table22[SQLiteTable.Symbol.Name];
              const tableSchema = table22[SQLiteTable.Symbol.Schema];
              const origTableName = table22[SQLiteTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join ${table22} on ${joinMeta.on}`
              );
            }
            if (index4 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        const joinsSql = sql.join(joinsArray);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        const groupByList = [];
        if (groupBy) {
          for (const [index4, groupByValue] of groupBy.entries()) {
            groupByList.push(groupByValue);
            if (index4 < groupBy.length - 1) {
              groupByList.push(sql`, `);
            }
          }
        }
        const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`${leftSelect.getSQL()} `;
        const rightChunk = sql`${rightSelect.getSQL()}`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const singleOrderBy of orderBy) {
            if (is(singleOrderBy, SQLiteColumn)) {
              orderByValues.push(sql.identifier(singleOrderBy.name));
            } else if (is(singleOrderBy, SQL)) {
              for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
                const chunk = singleOrderBy.queryChunks[i];
                if (is(chunk, SQLiteColumn)) {
                  singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
                }
              }
              orderByValues.push(sql`${singleOrderBy}`);
            } else {
              orderByValues.push(sql`${singleOrderBy}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table4, values, onConflict, returning, withList }) {
        const valuesSqlList = [];
        const columns = table4[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(
          ([_2, col]) => !col.shouldDisableInsert()
        );
        const insertOrder = colEntries.map(([, column4]) => sql.identifier(this.casing.getColumnCasing(column4)));
        for (const [valueIndex, value] of values.entries()) {
          const valueList = [];
          for (const [fieldName, col] of colEntries) {
            const colValue = value[fieldName];
            if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
              let defaultValue;
              if (col.default !== null && col.default !== void 0) {
                defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
              } else if (col.defaultFn !== void 0) {
                const defaultFnResult = col.defaultFn();
                defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
              } else if (!col.default && col.onUpdateFn !== void 0) {
                const onUpdateFnResult = col.onUpdateFn();
                defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
              } else {
                defaultValue = sql`null`;
              }
              valueList.push(defaultValue);
            } else {
              valueList.push(colValue);
            }
          }
          valuesSqlList.push(valueList);
          if (valueIndex < values.length - 1) {
            valuesSqlList.push(sql`, `);
          }
        }
        const withSql = this.buildWithCTE(withList);
        const valuesSql = sql.join(valuesSqlList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
        return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          invokeSource
        });
      }
      buildRelationalQuery({
        fullSchema,
        schema: schema4,
        tableNamesMap,
        table: table4,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column4 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column4 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema4, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQuery({
              fullSchema,
              schema: schema4,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema4[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({
            message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
          });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_group_array(${field}), json_array())`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table4, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                }
              ],
              where,
              limit,
              offset,
              orderBy,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table4, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table4, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(SQLiteDialect, _a200, "SQLiteDialect");
    SQLiteSyncDialect = class extends (_b144 = SQLiteDialect, _a201 = entityKind, _b144) {
      migrate(migrations, session, config) {
        const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric
			)
		`;
        session.run(migrationTableCreate);
        const dbMigrations = session.values(
          sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
        );
        const lastDbMigration = dbMigrations[0] ?? void 0;
        session.run(sql`BEGIN`);
        try {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                session.run(sql.raw(stmt));
              }
              session.run(
                sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
          session.run(sql`COMMIT`);
        } catch (e) {
          session.run(sql`ROLLBACK`);
          throw e;
        }
      }
    };
    __publicField(SQLiteSyncDialect, _a201, "SQLiteSyncDialect");
    SQLiteAsyncDialect = class extends (_b145 = SQLiteDialect, _a202 = entityKind, _b145) {
      async migrate(migrations, session, config) {
        const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric
			)
		`;
        await session.run(migrationTableCreate);
        const dbMigrations = await session.values(
          sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
        );
        const lastDbMigration = dbMigrations[0] ?? void 0;
        await session.transaction(async (tx) => {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.run(sql.raw(stmt));
              }
              await tx.run(
                sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
    };
    __publicField(SQLiteAsyncDialect, _a202, "SQLiteAsyncDialect");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/select.js
function createSetOperator2(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a203, SQLiteSelectBuilder, _a204, _b146, SQLiteSelectQueryBuilderBase, _a205, _b147, SQLiteSelectBase, getSQLiteSetOperators, union2, unionAll2, intersect2, except2;
var init_select3 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_view_base2();
    _a203 = entityKind;
    SQLiteSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList");
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        this.withList = config.withList;
        this.distinct = config.distinct;
      }
      from(source) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, SQLiteViewBase)) {
          fields = source[ViewBaseConfig].selectedFields;
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        return new SQLiteSelectBase({
          table: source,
          fields,
          isPartialSelect,
          session: this.session,
          dialect: this.dialect,
          withList: this.withList,
          distinct: this.distinct
        });
      }
    };
    __publicField(SQLiteSelectBuilder, _a203, "SQLiteSelectBuilder");
    SQLiteSelectQueryBuilderBase = class extends (_b146 = TypedQueryBuilder, _a204 = entityKind, _b146) {
      constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
        super();
        __publicField(this, "_");
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        __publicField(this, "session");
        __publicField(this, "dialect");
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left"));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right"));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner"));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full"));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/sqlite-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/sqlite-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/sqlite-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/sqlite-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        this.config = {
          withList,
          table: table4,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect4;
        this._ = {
          selectedFields: fields
        };
        this.tableName = getTableLikeName(table4);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
      }
      createJoin(joinType) {
        return (table4, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table4);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table4, SQL)) {
              const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table4, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteSelectQueryBuilderBase, _a204, "SQLiteSelectQueryBuilder");
    SQLiteSelectBase = class extends (_b147 = SQLiteSelectQueryBuilderBase, _a205 = entityKind, _b147) {
      constructor() {
        super(...arguments);
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        if (!this.session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const fieldsList = orderSelectedFields(this.config.fields);
        const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          fieldsList,
          "all",
          true
        );
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.all();
      }
    };
    __publicField(SQLiteSelectBase, _a205, "SQLiteSelect");
    applyMixins(SQLiteSelectBase, [QueryPromise]);
    getSQLiteSetOperators = () => ({
      union: union2,
      unionAll: unionAll2,
      intersect: intersect2,
      except: except2
    });
    union2 = createSetOperator2("union", false);
    unionAll2 = createSetOperator2("union", true);
    intersect2 = createSetOperator2("intersect", false);
    except2 = createSetOperator2("except", false);
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js
var _a206, QueryBuilder2;
var init_query_builder3 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_dialect2();
    init_subquery();
    init_select3();
    _a206 = entityKind;
    QueryBuilder2 = class {
      constructor(dialect4) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        this.dialect = is(dialect4, SQLiteDialect) ? dialect4 : void 0;
        this.dialectConfig = is(dialect4, SQLiteDialect) ? void 0 : dialect4;
      }
      $with(alias) {
        const queryBuilder = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries,
            distinct: true
          });
        }
        return { select, selectDistinct };
      }
      select(fields) {
        return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
      }
      selectDistinct(fields) {
        return new SQLiteSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new SQLiteSyncDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder2, _a206, "SQLiteQueryBuilder");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/select.types.js
var init_select_types2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/update.js
var _a207, SQLiteUpdateBuilder, _a208, _b148, SQLiteUpdateBase;
var init_update2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table3();
    init_table();
    init_utils2();
    _a207 = entityKind;
    SQLiteUpdateBuilder = class {
      constructor(table4, session, dialect4, withList) {
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.withList = withList;
      }
      set(values) {
        return new SQLiteUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        );
      }
    };
    __publicField(SQLiteUpdateBuilder, _a207, "SQLiteUpdateBuilder");
    SQLiteUpdateBase = class extends (_b148 = QueryPromise, _a208 = entityKind, _b148) {
      constructor(table4, set, session, dialect4, withList) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.session = session;
        this.dialect = dialect4;
        this.config = { set, table: table4, withList };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.config.returning ? this.all() : this.run();
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteUpdateBase, _a208, "SQLiteUpdate");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/index.js
var init_query_builders2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/index.js"() {
    "use strict";
    init_delete2();
    init_insert2();
    init_query_builder3();
    init_select3();
    init_select_types2();
    init_update2();
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/count.js
var _a209, _b149, _c7, _SQLiteCountBuilder, SQLiteCountBuilder;
var init_count2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _SQLiteCountBuilder = class _SQLiteCountBuilder extends (_c7 = SQL, _b149 = entityKind, _a209 = Symbol.toStringTag, _c7) {
      constructor(params) {
        super(_SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a209, "SQLiteCountBuilderAsync");
        __publicField(this, "session");
        this.params = params;
        this.session = params.session;
        this.sql = _SQLiteCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_SQLiteCountBuilder, _b149, "SQLiteCountBuilderAsync");
    SQLiteCountBuilder = _SQLiteCountBuilder;
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/query.js
var _a210, RelationalQueryBuilder2, _a211, _b150, SQLiteRelationalQuery, _a212, _b151, SQLiteSyncRelationalQuery;
var init_query2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    _a210 = entityKind;
    RelationalQueryBuilder2 = class {
      constructor(mode, fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session) {
        this.mode = mode;
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
      }
      findMany(config) {
        return this.mode === "sync" ? new SQLiteSyncRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        ) : new SQLiteRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        );
      }
      findFirst(config) {
        return this.mode === "sync" ? new SQLiteSyncRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        ) : new SQLiteRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        );
      }
    };
    __publicField(RelationalQueryBuilder2, _a210, "SQLiteAsyncRelationalQueryBuilder");
    SQLiteRelationalQuery = class extends (_b150 = QueryPromise, _a211 = entityKind, _b150) {
      constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session, config, mode) {
        super();
        /** @internal */
        __publicField(this, "mode");
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
        this.config = config;
        this.mode = mode;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        }).sql;
      }
      /** @internal */
      _prepare(isOneTimeQuery = false) {
        const { query, builtQuery } = this._toSQL();
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          builtQuery,
          void 0,
          this.mode === "first" ? "get" : "all",
          true,
          (rawRows, mapColumnValue) => {
            const rows = rawRows.map(
              (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
            );
            if (this.mode === "first") {
              return rows[0];
            }
            return rows;
          }
        );
      }
      prepare() {
        return this._prepare(false);
      }
      _toSQL() {
        const query = this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { query, builtQuery };
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      /** @internal */
      executeRaw() {
        if (this.mode === "first") {
          return this._prepare(false).get();
        }
        return this._prepare(false).all();
      }
      async execute() {
        return this.executeRaw();
      }
    };
    __publicField(SQLiteRelationalQuery, _a211, "SQLiteAsyncRelationalQuery");
    SQLiteSyncRelationalQuery = class extends (_b151 = SQLiteRelationalQuery, _a212 = entityKind, _b151) {
      sync() {
        return this.executeRaw();
      }
    };
    __publicField(SQLiteSyncRelationalQuery, _a212, "SQLiteSyncRelationalQuery");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/raw.js
var _a213, _b152, SQLiteRaw;
var init_raw2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/raw.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    SQLiteRaw = class extends (_b152 = QueryPromise, _a213 = entityKind, _b152) {
      constructor(execute, getSQL, action, dialect4, mapBatchResult) {
        super();
        /** @internal */
        __publicField(this, "config");
        this.execute = execute;
        this.getSQL = getSQL;
        this.dialect = dialect4;
        this.mapBatchResult = mapBatchResult;
        this.config = { action };
      }
      getQuery() {
        return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };
      }
      mapResult(result, isFromBatch) {
        return isFromBatch ? this.mapBatchResult(result) : result;
      }
      _prepare() {
        return this;
      }
      /** @internal */
      isResponseInArrayMode() {
        return false;
      }
    };
    __publicField(SQLiteRaw, _a213, "SQLiteRaw");
  }
});

// ../drizzle-orm/dist/sqlite-core/db.js
var _a214, BaseSQLiteDatabase;
var init_db2 = __esm({
  "../drizzle-orm/dist/sqlite-core/db.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_sql();
    init_query_builders2();
    init_subquery();
    init_count2();
    init_query2();
    init_raw2();
    _a214 = entityKind;
    BaseSQLiteDatabase = class {
      constructor(resultKind, dialect4, session, schema4) {
        __publicField(this, "query");
        this.resultKind = resultKind;
        this.dialect = dialect4;
        this.session = session;
        this._ = schema4 ? {
          schema: schema4.schema,
          fullSchema: schema4.fullSchema,
          tableNamesMap: schema4.tableNamesMap
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {}
        };
        this.query = {};
        const query = this.query;
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            query[tableName] = new RelationalQueryBuilder2(
              resultKind,
              schema4.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema4.fullSchema[tableName],
              columns,
              dialect4,
              session
            );
          }
        }
      }
      /**
       * Creates a subquery that defines a temporary named result set as a CTE.
       *
       * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param alias The alias for the subquery.
       *
       * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
       *
       * @example
       *
       * ```ts
       * // Create a subquery with alias 'sq' and use it in the select query
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * const result = await db.with(sq).select().from(sq);
       * ```
       *
       * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
       *
       * ```ts
       * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
       * const sq = db.$with('sq').as(db.select({
       *   name: sql<string>`upper(${users.name})`.as('name'),
       * })
       * .from(users));
       *
       * const result = await db.with(sq).select({ name: sq.name }).from(sq);
       * ```
       */
      $with(alias) {
        const self2 = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder2(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      $count(source, filters) {
        return new SQLiteCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function update(table4) {
          return new SQLiteUpdateBuilder(table4, self2.session, self2.dialect, queries);
        }
        function insert(into) {
          return new SQLiteInsertBuilder(into, self2.session, self2.dialect, queries);
        }
        function delete_(from) {
          return new SQLiteDeleteBase(from, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, update, insert, delete: delete_ };
      }
      select(fields) {
        return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
      }
      selectDistinct(fields) {
        return new SQLiteSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       *
       * // Update with returning clause
       * const updatedCar: Car[] = await db.update(cars)
       *   .set({ color: 'red' })
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      update(table4) {
        return new SQLiteUpdateBuilder(table4, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       *
       * // Insert with returning clause
       * const insertedCar: Car[] = await db.insert(cars)
       *   .values({ brand: 'BMW' })
       *   .returning();
       * ```
       */
      insert(into) {
        return new SQLiteInsertBuilder(into, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       *
       * // Delete with returning clause
       * const deletedCar: Car[] = await db.delete(cars)
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      delete(from) {
        return new SQLiteDeleteBase(from, this.session, this.dialect);
      }
      run(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.run(sequel),
            () => sequel,
            "run",
            this.dialect,
            this.session.extractRawRunValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.run(sequel);
      }
      all(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.all(sequel),
            () => sequel,
            "all",
            this.dialect,
            this.session.extractRawAllValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.all(sequel);
      }
      get(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.get(sequel),
            () => sequel,
            "get",
            this.dialect,
            this.session.extractRawGetValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.get(sequel);
      }
      values(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.values(sequel),
            () => sequel,
            "values",
            this.dialect,
            this.session.extractRawValuesValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.values(sequel);
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(BaseSQLiteDatabase, _a214, "BaseSQLiteDatabase");
  }
});

// ../drizzle-orm/dist/sqlite-core/indexes.js
var _a215, IndexBuilderOn2, _a216, IndexBuilder2, _a217, Index4;
var init_indexes2 = __esm({
  "../drizzle-orm/dist/sqlite-core/indexes.js"() {
    "use strict";
    init_entity();
    _a215 = entityKind;
    IndexBuilderOn2 = class {
      constructor(name2, unique) {
        this.name = name2;
        this.unique = unique;
      }
      on(...columns) {
        return new IndexBuilder2(this.name, columns, this.unique);
      }
    };
    __publicField(IndexBuilderOn2, _a215, "SQLiteIndexBuilderOn");
    _a216 = entityKind;
    IndexBuilder2 = class {
      constructor(name2, columns, unique) {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique,
          where: void 0
        };
      }
      /**
       * Condition for partial index.
       */
      where(condition) {
        this.config.where = condition;
        return this;
      }
      /** @internal */
      build(table4) {
        return new Index4(this.config, table4);
      }
    };
    __publicField(IndexBuilder2, _a216, "SQLiteIndexBuilder");
    _a217 = entityKind;
    Index4 = class {
      constructor(config, table4) {
        __publicField(this, "config");
        this.config = { ...config, table: table4 };
      }
    };
    __publicField(Index4, _a217, "SQLiteIndex");
  }
});

// ../drizzle-orm/dist/sqlite-core/primary-keys.js
var _a218, PrimaryKeyBuilder2, _a219, PrimaryKey2;
var init_primary_keys2 = __esm({
  "../drizzle-orm/dist/sqlite-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table3();
    _a218 = entityKind;
    PrimaryKeyBuilder2 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table4) {
        return new PrimaryKey2(table4, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder2, _a218, "SQLitePrimaryKeyBuilder");
    _a219 = entityKind;
    PrimaryKey2 = class {
      constructor(table4, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table4;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column4) => column4.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey2, _a219, "SQLitePrimaryKey");
  }
});

// ../drizzle-orm/dist/sqlite-core/session.js
var _a220, _b153, ExecuteResultSync, _a221, SQLitePreparedQuery, _a222, SQLiteSession, _a223, _b154, SQLiteTransaction;
var init_session2 = __esm({
  "../drizzle-orm/dist/sqlite-core/session.js"() {
    "use strict";
    init_entity();
    init_errors();
    init_query_promise();
    init_db2();
    ExecuteResultSync = class extends (_b153 = QueryPromise, _a220 = entityKind, _b153) {
      constructor(resultCb) {
        super();
        this.resultCb = resultCb;
      }
      async execute() {
        return this.resultCb();
      }
      sync() {
        return this.resultCb();
      }
    };
    __publicField(ExecuteResultSync, _a220, "ExecuteResultSync");
    _a221 = entityKind;
    SQLitePreparedQuery = class {
      constructor(mode, executeMethod, query) {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.mode = mode;
        this.executeMethod = executeMethod;
        this.query = query;
      }
      getQuery() {
        return this.query;
      }
      mapRunResult(result, _isFromBatch) {
        return result;
      }
      mapAllResult(_result, _isFromBatch) {
        throw new Error("Not implemented");
      }
      mapGetResult(_result, _isFromBatch) {
        throw new Error("Not implemented");
      }
      execute(placeholderValues) {
        if (this.mode === "async") {
          return this[this.executeMethod](placeholderValues);
        }
        return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
      }
      mapResult(response, isFromBatch) {
        switch (this.executeMethod) {
          case "run": {
            return this.mapRunResult(response, isFromBatch);
          }
          case "all": {
            return this.mapAllResult(response, isFromBatch);
          }
          case "get": {
            return this.mapGetResult(response, isFromBatch);
          }
        }
      }
    };
    __publicField(SQLitePreparedQuery, _a221, "PreparedQuery");
    _a222 = entityKind;
    SQLiteSession = class {
      constructor(dialect4) {
        this.dialect = dialect4;
      }
      prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode) {
        return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode);
      }
      run(query) {
        const staticQuery = this.dialect.sqlToQuery(query);
        try {
          return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run();
        } catch (err) {
          throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });
        }
      }
      /** @internal */
      extractRawRunValueFromBatchResult(result) {
        return result;
      }
      all(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all();
      }
      /** @internal */
      extractRawAllValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
      get(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get();
      }
      /** @internal */
      extractRawGetValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
      values(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values();
      }
      async count(sql2) {
        const result = await this.values(sql2);
        return result[0][0];
      }
      /** @internal */
      extractRawValuesValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
    };
    __publicField(SQLiteSession, _a222, "SQLiteSession");
    SQLiteTransaction = class extends (_b154 = BaseSQLiteDatabase, _a223 = entityKind, _b154) {
      constructor(resultType, dialect4, session, schema4, nestedIndex = 0) {
        super(resultType, dialect4, session, schema4);
        this.schema = schema4;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
    };
    __publicField(SQLiteTransaction, _a223, "SQLiteTransaction");
  }
});

// ../drizzle-orm/dist/sqlite-core/subquery.js
var init_subquery3 = __esm({
  "../drizzle-orm/dist/sqlite-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/utils.js
function getTableConfig2(table4) {
  const columns = Object.values(table4[SQLiteTable.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const uniqueConstraints = [];
  const foreignKeys = Object.values(table4[SQLiteTable.Symbol.InlineForeignKeys]);
  const name2 = table4[Table2.Symbol.Name];
  const extraConfigBuilder = table4[SQLiteTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table4[SQLiteTable.Symbol.Columns]);
    for (const builder of Object.values(extraConfig)) {
      if (is(builder, IndexBuilder2)) {
        indexes.push(builder.build(table4));
      } else if (is(builder, CheckBuilder2)) {
        checks.push(builder.build(table4));
      } else if (is(builder, UniqueConstraintBuilder2)) {
        uniqueConstraints.push(builder.build(table4));
      } else if (is(builder, PrimaryKeyBuilder2)) {
        primaryKeys.push(builder.build(table4));
      } else if (is(builder, ForeignKeyBuilder2)) {
        foreignKeys.push(builder.build(table4));
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2
  };
}
function getViewConfig2(view4) {
  return {
    ...view4[ViewBaseConfig]
    // ...view[SQLiteViewConfig],
  };
}
var init_utils7 = __esm({
  "../drizzle-orm/dist/sqlite-core/utils.js"() {
    "use strict";
    init_entity();
    init_table();
    init_view_common();
    init_checks2();
    init_foreign_keys2();
    init_indexes2();
    init_primary_keys2();
    init_table3();
    init_unique_constraint2();
  }
});

// ../drizzle-orm/dist/sqlite-core/view.js
var _a224, ViewBuilderCore, _a225, _b155, ViewBuilder2, _a226, _b156, ManualViewBuilder2, _a227, _b157, SQLiteView2;
var init_view2 = __esm({
  "../drizzle-orm/dist/sqlite-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder3();
    init_table3();
    init_view_base2();
    _a224 = entityKind;
    ViewBuilderCore = class {
      constructor(name2) {
        __publicField(this, "config", {});
        this.name = name2;
      }
    };
    __publicField(ViewBuilderCore, _a224, "SQLiteViewBuilderCore");
    ViewBuilder2 = class extends (_b155 = ViewBuilderCore, _a225 = entityKind, _b155) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder2());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelectedFields = qb.getSelectedFields();
        return new Proxy(
          new SQLiteView2({
            // sqliteConfig: this.config,
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: aliasedSelectedFields,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder2, _a225, "SQLiteViewBuilder");
    ManualViewBuilder2 = class extends (_b156 = ViewBuilderCore, _a226 = entityKind, _b156) {
      constructor(name2, columns) {
        super(name2);
        __publicField(this, "columns");
        this.columns = getTableColumns(sqliteTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new SQLiteView2({
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new SQLiteView2({
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder2, _a226, "SQLiteManualViewBuilder");
    SQLiteView2 = class extends (_b157 = SQLiteViewBase, _a227 = entityKind, _b157) {
      constructor({ config }) {
        super(config);
      }
    };
    __publicField(SQLiteView2, _a227, "SQLiteView");
  }
});

// ../drizzle-orm/dist/sqlite-core/index.js
var init_sqlite_core = __esm({
  "../drizzle-orm/dist/sqlite-core/index.js"() {
    "use strict";
    init_alias3();
    init_checks2();
    init_columns2();
    init_db2();
    init_dialect2();
    init_foreign_keys2();
    init_indexes2();
    init_primary_keys2();
    init_query_builders2();
    init_session2();
    init_subquery3();
    init_table3();
    init_unique_constraint2();
    init_utils7();
    init_view2();
  }
});

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

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

// ../drizzle-orm/dist/mysql-core/alias.js
var init_alias4 = __esm({
  "../drizzle-orm/dist/mysql-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/checks.js
var _a228, CheckBuilder3, _a229, Check3;
var init_checks3 = __esm({
  "../drizzle-orm/dist/mysql-core/checks.js"() {
    "use strict";
    init_entity();
    _a228 = entityKind;
    CheckBuilder3 = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      /** @internal */
      build(table4) {
        return new Check3(table4, this);
      }
    };
    __publicField(CheckBuilder3, _a228, "MySqlCheckBuilder");
    _a229 = entityKind;
    Check3 = class {
      constructor(table4, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table4;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check3, _a229, "MySqlCheck");
  }
});

// ../drizzle-orm/dist/mysql-core/foreign-keys.js
var _a230, ForeignKeyBuilder3, _a231, ForeignKey3;
var init_foreign_keys3 = __esm({
  "../drizzle-orm/dist/mysql-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a230 = entityKind;
    ForeignKeyBuilder3 = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate");
        /** @internal */
        __publicField(this, "_onDelete");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action;
        return this;
      }
      /** @internal */
      build(table4) {
        return new ForeignKey3(table4, this);
      }
    };
    __publicField(ForeignKeyBuilder3, _a230, "MySqlForeignKeyBuilder");
    _a231 = entityKind;
    ForeignKey3 = class {
      constructor(table4, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table4;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column4) => column4.name);
        const foreignColumnNames = foreignColumns.map((column4) => column4.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey3, _a231, "MySqlForeignKey");
  }
});

// ../drizzle-orm/dist/mysql-core/unique-constraint.js
function uniqueKeyName3(table4, columns) {
  return `${table4[TableName]}_${columns.join("_")}_unique`;
}
var _a232, UniqueConstraintBuilder3, _a233, UniqueOnConstraintBuilder3, _a234, UniqueConstraint3;
var init_unique_constraint3 = __esm({
  "../drizzle-orm/dist/mysql-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a232 = entityKind;
    UniqueConstraintBuilder3 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        this.name = name2;
        this.columns = columns;
      }
      /** @internal */
      build(table4) {
        return new UniqueConstraint3(table4, this.columns, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder3, _a232, "MySqlUniqueConstraintBuilder");
    _a233 = entityKind;
    UniqueOnConstraintBuilder3 = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder3(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder3, _a233, "MySqlUniqueOnConstraintBuilder");
    _a234 = entityKind;
    UniqueConstraint3 = class {
      constructor(table4, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        __publicField(this, "nullsNotDistinct", false);
        this.table = table4;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName3(this.table, this.columns.map((column4) => column4.name));
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint3, _a234, "MySqlUniqueConstraint");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/common.js
var _a235, _b158, MySqlColumnBuilder, _a236, _b159, MySqlColumn, _a237, _b160, MySqlColumnBuilderWithAutoIncrement, _a238, _b161, MySqlColumnWithAutoIncrement;
var init_common4 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys3();
    init_unique_constraint3();
    MySqlColumnBuilder = class extends (_b158 = ColumnBuilder, _a235 = entityKind, _b158) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        return this;
      }
      generatedAlwaysAs(as, config) {
        this.config.generated = {
          as,
          type: "always",
          mode: config?.mode ?? "virtual"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column4, table4) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return ((ref2, actions2) => {
            const builder = new ForeignKeyBuilder3(() => {
              const foreignColumn = ref2();
              return { columns: [column4], foreignColumns: [foreignColumn] };
            });
            if (actions2.onUpdate) {
              builder.onUpdate(actions2.onUpdate);
            }
            if (actions2.onDelete) {
              builder.onDelete(actions2.onDelete);
            }
            return builder.build(table4);
          })(ref, actions);
        });
      }
    };
    __publicField(MySqlColumnBuilder, _a235, "MySqlColumnBuilder");
    MySqlColumn = class extends (_b159 = Column2, _a236 = entityKind, _b159) {
      constructor(table4, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName3(table4, [config.name]);
        }
        super(table4, config);
        this.table = table4;
      }
    };
    __publicField(MySqlColumn, _a236, "MySqlColumn");
    MySqlColumnBuilderWithAutoIncrement = class extends (_b160 = MySqlColumnBuilder, _a237 = entityKind, _b160) {
      constructor(name2, dataType, columnType) {
        super(name2, dataType, columnType);
        this.config.autoIncrement = false;
      }
      autoincrement() {
        this.config.autoIncrement = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(MySqlColumnBuilderWithAutoIncrement, _a237, "MySqlColumnBuilderWithAutoIncrement");
    MySqlColumnWithAutoIncrement = class extends (_b161 = MySqlColumn, _a238 = entityKind, _b161) {
      constructor() {
        super(...arguments);
        __publicField(this, "autoIncrement", this.config.autoIncrement);
      }
    };
    __publicField(MySqlColumnWithAutoIncrement, _a238, "MySqlColumnWithAutoIncrement");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/bigint.js
function bigint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new MySqlBigInt53Builder(name2, config.unsigned);
  }
  return new MySqlBigInt64Builder(name2, config.unsigned);
}
var _a239, _b162, MySqlBigInt53Builder, _a240, _b163, MySqlBigInt53, _a241, _b164, MySqlBigInt64Builder, _a242, _b165, MySqlBigInt64;
var init_bigint2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/bigint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlBigInt53Builder = class extends (_b162 = MySqlColumnBuilderWithAutoIncrement, _a239 = entityKind, _b162) {
      constructor(name2, unsigned = false) {
        super(name2, "number", "MySqlBigInt53");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table4) {
        return new MySqlBigInt53(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlBigInt53Builder, _a239, "MySqlBigInt53Builder");
    MySqlBigInt53 = class extends (_b163 = MySqlColumnWithAutoIncrement, _a240 = entityKind, _b163) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(MySqlBigInt53, _a240, "MySqlBigInt53");
    MySqlBigInt64Builder = class extends (_b164 = MySqlColumnBuilderWithAutoIncrement, _a241 = entityKind, _b164) {
      constructor(name2, unsigned = false) {
        super(name2, "bigint", "MySqlBigInt64");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table4) {
        return new MySqlBigInt64(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlBigInt64Builder, _a241, "MySqlBigInt64Builder");
    MySqlBigInt64 = class extends (_b165 = MySqlColumnWithAutoIncrement, _a242 = entityKind, _b165) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(MySqlBigInt64, _a242, "MySqlBigInt64");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/binary.js
function binary(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlBinaryBuilder(name2, config.length);
}
var _a243, _b166, MySqlBinaryBuilder, _a244, _b167, MySqlBinary;
var init_binary = __esm({
  "../drizzle-orm/dist/mysql-core/columns/binary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlBinaryBuilder = class extends (_b166 = MySqlColumnBuilder, _a243 = entityKind, _b166) {
      constructor(name2, length) {
        super(name2, "string", "MySqlBinary");
        this.config.length = length;
      }
      /** @internal */
      build(table4) {
        return new MySqlBinary(table4, this.config);
      }
    };
    __publicField(MySqlBinaryBuilder, _a243, "MySqlBinaryBuilder");
    MySqlBinary = class extends (_b167 = MySqlColumn, _a244 = entityKind, _b167) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      getSQLType() {
        return this.length === void 0 ? `binary` : `binary(${this.length})`;
      }
    };
    __publicField(MySqlBinary, _a244, "MySqlBinary");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/boolean.js
function boolean2(name2) {
  return new MySqlBooleanBuilder(name2 ?? "");
}
var _a245, _b168, MySqlBooleanBuilder, _a246, _b169, MySqlBoolean;
var init_boolean2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/boolean.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlBooleanBuilder = class extends (_b168 = MySqlColumnBuilder, _a245 = entityKind, _b168) {
      constructor(name2) {
        super(name2, "boolean", "MySqlBoolean");
      }
      /** @internal */
      build(table4) {
        return new MySqlBoolean(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlBooleanBuilder, _a245, "MySqlBooleanBuilder");
    MySqlBoolean = class extends (_b169 = MySqlColumn, _a246 = entityKind, _b169) {
      getSQLType() {
        return "boolean";
      }
      mapFromDriverValue(value) {
        if (typeof value === "boolean") {
          return value;
        }
        return value === 1;
      }
    };
    __publicField(MySqlBoolean, _a246, "MySqlBoolean");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/char.js
function char2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlCharBuilder(name2, config);
}
var _a247, _b170, MySqlCharBuilder, _a248, _b171, MySqlChar;
var init_char2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/char.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlCharBuilder = class extends (_b170 = MySqlColumnBuilder, _a247 = entityKind, _b170) {
      constructor(name2, config) {
        super(name2, "string", "MySqlChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table4) {
        return new MySqlChar(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlCharBuilder, _a247, "MySqlCharBuilder");
    MySqlChar = class extends (_b171 = MySqlColumn, _a248 = entityKind, _b171) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
    __publicField(MySqlChar, _a248, "MySqlChar");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/custom.js
function customType3(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new MySqlCustomColumnBuilder(name2, config, customTypeParams);
  };
}
var _a249, _b172, MySqlCustomColumnBuilder, _a250, _b173, MySqlCustomColumn;
var init_custom3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlCustomColumnBuilder = class extends (_b172 = MySqlColumnBuilder, _a249 = entityKind, _b172) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "MySqlCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table4) {
        return new MySqlCustomColumn(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlCustomColumnBuilder, _a249, "MySqlCustomColumnBuilder");
    MySqlCustomColumn = class extends (_b173 = MySqlColumn, _a250 = entityKind, _b173) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(MySqlCustomColumn, _a250, "MySqlCustomColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/date.js
function date2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlDateStringBuilder(name2);
  }
  return new MySqlDateBuilder(name2);
}
var _a251, _b174, MySqlDateBuilder, _a252, _b175, MySqlDate, _a253, _b176, MySqlDateStringBuilder, _a254, _b177, MySqlDateString;
var init_date2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/date.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDateBuilder = class extends (_b174 = MySqlColumnBuilder, _a251 = entityKind, _b174) {
      constructor(name2) {
        super(name2, "date", "MySqlDate");
      }
      /** @internal */
      build(table4) {
        return new MySqlDate(table4, this.config);
      }
    };
    __publicField(MySqlDateBuilder, _a251, "MySqlDateBuilder");
    MySqlDate = class extends (_b175 = MySqlColumn, _a252 = entityKind, _b175) {
      constructor(table4, config) {
        super(table4, config);
      }
      getSQLType() {
        return `date`;
      }
      mapFromDriverValue(value) {
        return new Date(value);
      }
    };
    __publicField(MySqlDate, _a252, "MySqlDate");
    MySqlDateStringBuilder = class extends (_b176 = MySqlColumnBuilder, _a253 = entityKind, _b176) {
      constructor(name2) {
        super(name2, "string", "MySqlDateString");
      }
      /** @internal */
      build(table4) {
        return new MySqlDateString(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlDateStringBuilder, _a253, "MySqlDateStringBuilder");
    MySqlDateString = class extends (_b177 = MySqlColumn, _a254 = entityKind, _b177) {
      constructor(table4, config) {
        super(table4, config);
      }
      getSQLType() {
        return `date`;
      }
    };
    __publicField(MySqlDateString, _a254, "MySqlDateString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/datetime.js
function datetime(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlDateTimeStringBuilder(name2, config);
  }
  return new MySqlDateTimeBuilder(name2, config);
}
var _a255, _b178, MySqlDateTimeBuilder, _a256, _b179, MySqlDateTime, _a257, _b180, MySqlDateTimeStringBuilder, _a258, _b181, MySqlDateTimeString;
var init_datetime = __esm({
  "../drizzle-orm/dist/mysql-core/columns/datetime.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDateTimeBuilder = class extends (_b178 = MySqlColumnBuilder, _a255 = entityKind, _b178) {
      constructor(name2, config) {
        super(name2, "date", "MySqlDateTime");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table4) {
        return new MySqlDateTime(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlDateTimeBuilder, _a255, "MySqlDateTimeBuilder");
    MySqlDateTime = class extends (_b179 = MySqlColumn, _a256 = entityKind, _b179) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "fsp");
        this.fsp = config.fsp;
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `datetime${precision}`;
      }
      mapToDriverValue(value) {
        return value.toISOString().replace("T", " ").replace("Z", "");
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value.replace(" ", "T") + "Z");
      }
    };
    __publicField(MySqlDateTime, _a256, "MySqlDateTime");
    MySqlDateTimeStringBuilder = class extends (_b180 = MySqlColumnBuilder, _a257 = entityKind, _b180) {
      constructor(name2, config) {
        super(name2, "string", "MySqlDateTimeString");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table4) {
        return new MySqlDateTimeString(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlDateTimeStringBuilder, _a257, "MySqlDateTimeStringBuilder");
    MySqlDateTimeString = class extends (_b181 = MySqlColumn, _a258 = entityKind, _b181) {
      constructor(table4, config) {
        super(table4, config);
        __publicField(this, "fsp");
        this.fsp = config.fsp;
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `datetime${precision}`;
      }
    };
    __publicField(MySqlDateTimeString, _a258, "MySqlDateTimeString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/decimal.js
function decimal(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlDecimalBuilder(name2, config);
}
var _a259, _b182, MySqlDecimalBuilder, _a260, _b183, MySqlDecimal;
var init_decimal = __esm({
  "../drizzle-orm/dist/mysql-core/columns/decimal.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDecimalBuilder = class extends (_b182 = MySqlColumnBuilderWithAutoIncrement, _a259 = entityKind, _b182) {
      constructor(name2, config) {
        super(name2, "string", "MySqlDecimal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table4) {
        return new MySqlDecimal(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlDecimalBuilder, _a259, "MySqlDecimalBuilder");
    MySqlDecimal = class extends (_b183 = MySqlColumnWithAutoIncrement, _a260 = entityKind, _b183) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDecimal, _a260, "MySqlDecimal");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/double.js
function double(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlDoubleBuilder(name2, config);
}
var _a261, _b184, MySqlDoubleBuilder, _a262, _b185, MySqlDouble;
var init_double = __esm({
  "../drizzle-orm/dist/mysql-core/columns/double.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDoubleBuilder = class extends (_b184 = MySqlColumnBuilderWithAutoIncrement, _a261 = entityKind, _b184) {
      constructor(name2, config) {
        super(name2, "number", "MySqlDouble");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table4) {
        return new MySqlDouble(table4, this.config);
      }
    };
    __publicField(MySqlDoubleBuilder, _a261, "MySqlDoubleBuilder");
    MySqlDouble = class extends (_b185 = MySqlColumnWithAutoIncrement, _a262 = entityKind, _b185) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `double(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "double";
        } else {
          type += `double(${this.precision})`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDouble, _a262, "MySqlDouble");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/enum.js
function mysqlEnum(a, b) {
  const { name: name2, config: values } = getColumnNameAndConfig(a, b);
  if (values.length === 0) {
    throw new Error(`You have an empty array for "${name2}" enum values`);
  }
  return new MySqlEnumColumnBuilder(name2, values);
}
var _a263, _b186, MySqlEnumColumnBuilder, _a264, _b187, MySqlEnumColumn;
var init_enum2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/enum.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlEnumColumnBuilder = class extends (_b186 = MySqlColumnBuilder, _a263 = entityKind, _b186) {
      constructor(name2, values) {
        super(name2, "string", "MySqlEnumColumn");
        this.config.enumValues = values;
      }
      /** @internal */
      build(table4) {
        return new MySqlEnumColumn(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlEnumColumnBuilder, _a263, "MySqlEnumColumnBuilder");
    MySqlEnumColumn = class extends (_b187 = MySqlColumn, _a264 = entityKind, _b187) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return `enum(${this.enumValues.map((value) => `'${value}'`).join(",")})`;
      }
    };
    __publicField(MySqlEnumColumn, _a264, "MySqlEnumColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/float.js
function float(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlFloatBuilder(name2, config);
}
var _a265, _b188, MySqlFloatBuilder, _a266, _b189, MySqlFloat;
var init_float = __esm({
  "../drizzle-orm/dist/mysql-core/columns/float.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlFloatBuilder = class extends (_b188 = MySqlColumnBuilderWithAutoIncrement, _a265 = entityKind, _b188) {
      constructor(name2, config) {
        super(name2, "number", "MySqlFloat");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table4) {
        return new MySqlFloat(table4, this.config);
      }
    };
    __publicField(MySqlFloatBuilder, _a265, "MySqlFloatBuilder");
    MySqlFloat = class extends (_b189 = MySqlColumnWithAutoIncrement, _a266 = entityKind, _b189) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `float(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "float";
        } else {
          type += `float(${this.precision})`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlFloat, _a266, "MySqlFloat");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/int.js
function int(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlIntBuilder(name2, config);
}
var _a267, _b190, MySqlIntBuilder, _a268, _b191, MySqlInt;
var init_int = __esm({
  "../drizzle-orm/dist/mysql-core/columns/int.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlIntBuilder = class extends (_b190 = MySqlColumnBuilderWithAutoIncrement, _a267 = entityKind, _b190) {
      constructor(name2, config) {
        super(name2, "number", "MySqlInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table4) {
        return new MySqlInt(table4, this.config);
      }
    };
    __publicField(MySqlIntBuilder, _a267, "MySqlIntBuilder");
    MySqlInt = class extends (_b191 = MySqlColumnWithAutoIncrement, _a268 = entityKind, _b191) {
      getSQLType() {
        return `int${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlInt, _a268, "MySqlInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/json.js
function json2(name2) {
  return new MySqlJsonBuilder(name2 ?? "");
}
var _a269, _b192, MySqlJsonBuilder, _a270, _b193, MySqlJson;
var init_json2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/json.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlJsonBuilder = class extends (_b192 = MySqlColumnBuilder, _a269 = entityKind, _b192) {
      constructor(name2) {
        super(name2, "json", "MySqlJson");
      }
      /** @internal */
      build(table4) {
        return new MySqlJson(table4, this.config);
      }
    };
    __publicField(MySqlJsonBuilder, _a269, "MySqlJsonBuilder");
    MySqlJson = class extends (_b193 = MySqlColumn, _a270 = entityKind, _b193) {
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
    };
    __publicField(MySqlJson, _a270, "MySqlJson");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/mediumint.js
function mediumint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlMediumIntBuilder(name2, config);
}
var _a271, _b194, MySqlMediumIntBuilder, _a272, _b195, MySqlMediumInt;
var init_mediumint = __esm({
  "../drizzle-orm/dist/mysql-core/columns/mediumint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlMediumIntBuilder = class extends (_b194 = MySqlColumnBuilderWithAutoIncrement, _a271 = entityKind, _b194) {
      constructor(name2, config) {
        super(name2, "number", "MySqlMediumInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table4) {
        return new MySqlMediumInt(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlMediumIntBuilder, _a271, "MySqlMediumIntBuilder");
    MySqlMediumInt = class extends (_b195 = MySqlColumnWithAutoIncrement, _a272 = entityKind, _b195) {
      getSQLType() {
        return `mediumint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlMediumInt, _a272, "MySqlMediumInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/real.js
function real3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlRealBuilder(name2, config);
}
var _a273, _b196, MySqlRealBuilder, _a274, _b197, MySqlReal;
var init_real3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlRealBuilder = class extends (_b196 = MySqlColumnBuilderWithAutoIncrement, _a273 = entityKind, _b196) {
      constructor(name2, config) {
        super(name2, "number", "MySqlReal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
      }
      /** @internal */
      build(table4) {
        return new MySqlReal(table4, this.config);
      }
    };
    __publicField(MySqlRealBuilder, _a273, "MySqlRealBuilder");
    MySqlReal = class extends (_b197 = MySqlColumnWithAutoIncrement, _a274 = entityKind, _b197) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `real(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "real";
        } else {
          return `real(${this.precision})`;
        }
      }
    };
    __publicField(MySqlReal, _a274, "MySqlReal");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/serial.js
function serial2(name2) {
  return new MySqlSerialBuilder(name2 ?? "");
}
var _a275, _b198, MySqlSerialBuilder, _a276, _b199, MySqlSerial;
var init_serial2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/serial.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlSerialBuilder = class extends (_b198 = MySqlColumnBuilderWithAutoIncrement, _a275 = entityKind, _b198) {
      constructor(name2) {
        super(name2, "number", "MySqlSerial");
        this.config.hasDefault = true;
        this.config.autoIncrement = true;
      }
      /** @internal */
      build(table4) {
        return new MySqlSerial(table4, this.config);
      }
    };
    __publicField(MySqlSerialBuilder, _a275, "MySqlSerialBuilder");
    MySqlSerial = class extends (_b199 = MySqlColumnWithAutoIncrement, _a276 = entityKind, _b199) {
      getSQLType() {
        return "serial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlSerial, _a276, "MySqlSerial");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/smallint.js
function smallint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlSmallIntBuilder(name2, config);
}
var _a277, _b200, MySqlSmallIntBuilder, _a278, _b201, MySqlSmallInt;
var init_smallint2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/smallint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlSmallIntBuilder = class extends (_b200 = MySqlColumnBuilderWithAutoIncrement, _a277 = entityKind, _b200) {
      constructor(name2, config) {
        super(name2, "number", "MySqlSmallInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table4) {
        return new MySqlSmallInt(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlSmallIntBuilder, _a277, "MySqlSmallIntBuilder");
    MySqlSmallInt = class extends (_b201 = MySqlColumnWithAutoIncrement, _a278 = entityKind, _b201) {
      getSQLType() {
        return `smallint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlSmallInt, _a278, "MySqlSmallInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/text.js
function text3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTextBuilder(name2, "text", config);
}
var _a279, _b202, MySqlTextBuilder, _a280, _b203, MySqlText;
var init_text3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTextBuilder = class extends (_b202 = MySqlColumnBuilder, _a279 = entityKind, _b202) {
      constructor(name2, textType, config) {
        super(name2, "string", "MySqlText");
        this.config.textType = textType;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table4) {
        return new MySqlText(table4, this.config);
      }
    };
    __publicField(MySqlTextBuilder, _a279, "MySqlTextBuilder");
    MySqlText = class extends (_b203 = MySqlColumn, _a280 = entityKind, _b203) {
      constructor() {
        super(...arguments);
        __publicField(this, "textType", this.config.textType);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.textType;
      }
    };
    __publicField(MySqlText, _a280, "MySqlText");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/time.js
function time2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTimeBuilder(name2, config);
}
var _a281, _b204, MySqlTimeBuilder, _a282, _b205, MySqlTime;
var init_time2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/time.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTimeBuilder = class extends (_b204 = MySqlColumnBuilder, _a281 = entityKind, _b204) {
      constructor(name2, config) {
        super(name2, "string", "MySqlTime");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table4) {
        return new MySqlTime(table4, this.config);
      }
    };
    __publicField(MySqlTimeBuilder, _a281, "MySqlTimeBuilder");
    MySqlTime = class extends (_b205 = MySqlColumn, _a282 = entityKind, _b205) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `time${precision}`;
      }
    };
    __publicField(MySqlTime, _a282, "MySqlTime");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/date.common.js
var _a283, _b206, MySqlDateColumnBaseBuilder, _a284, _b207, MySqlDateBaseColumn;
var init_date_common2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/date.common.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common4();
    MySqlDateColumnBaseBuilder = class extends (_b206 = MySqlColumnBuilder, _a283 = entityKind, _b206) {
      defaultNow() {
        return this.default(sql`(now())`);
      }
      // "on update now" also adds an implicit default value to the column - https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html
      onUpdateNow() {
        this.config.hasOnUpdateNow = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(MySqlDateColumnBaseBuilder, _a283, "MySqlDateColumnBuilder");
    MySqlDateBaseColumn = class extends (_b207 = MySqlColumn, _a284 = entityKind, _b207) {
      constructor() {
        super(...arguments);
        __publicField(this, "hasOnUpdateNow", this.config.hasOnUpdateNow);
      }
    };
    __publicField(MySqlDateBaseColumn, _a284, "MySqlDateColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/timestamp.js
function timestamp2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlTimestampStringBuilder(name2, config);
  }
  return new MySqlTimestampBuilder(name2, config);
}
var _a285, _b208, MySqlTimestampBuilder, _a286, _b209, MySqlTimestamp, _a287, _b210, MySqlTimestampStringBuilder, _a288, _b211, MySqlTimestampString;
var init_timestamp2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/timestamp.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_date_common2();
    MySqlTimestampBuilder = class extends (_b208 = MySqlDateColumnBaseBuilder, _a285 = entityKind, _b208) {
      constructor(name2, config) {
        super(name2, "date", "MySqlTimestamp");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table4) {
        return new MySqlTimestamp(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlTimestampBuilder, _a285, "MySqlTimestampBuilder");
    MySqlTimestamp = class extends (_b209 = MySqlDateBaseColumn, _a286 = entityKind, _b209) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `timestamp${precision}`;
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value + "+0000");
      }
      mapToDriverValue(value) {
        return value.toISOString().slice(0, -1).replace("T", " ");
      }
    };
    __publicField(MySqlTimestamp, _a286, "MySqlTimestamp");
    MySqlTimestampStringBuilder = class extends (_b210 = MySqlDateColumnBaseBuilder, _a287 = entityKind, _b210) {
      constructor(name2, config) {
        super(name2, "string", "MySqlTimestampString");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table4) {
        return new MySqlTimestampString(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlTimestampStringBuilder, _a287, "MySqlTimestampStringBuilder");
    MySqlTimestampString = class extends (_b211 = MySqlDateBaseColumn, _a288 = entityKind, _b211) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `timestamp${precision}`;
      }
    };
    __publicField(MySqlTimestampString, _a288, "MySqlTimestampString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/tinyint.js
function tinyint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTinyIntBuilder(name2, config);
}
var _a289, _b212, MySqlTinyIntBuilder, _a290, _b213, MySqlTinyInt;
var init_tinyint = __esm({
  "../drizzle-orm/dist/mysql-core/columns/tinyint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTinyIntBuilder = class extends (_b212 = MySqlColumnBuilderWithAutoIncrement, _a289 = entityKind, _b212) {
      constructor(name2, config) {
        super(name2, "number", "MySqlTinyInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table4) {
        return new MySqlTinyInt(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlTinyIntBuilder, _a289, "MySqlTinyIntBuilder");
    MySqlTinyInt = class extends (_b213 = MySqlColumnWithAutoIncrement, _a290 = entityKind, _b213) {
      getSQLType() {
        return `tinyint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlTinyInt, _a290, "MySqlTinyInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/varbinary.js
function varbinary(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlVarBinaryBuilder(name2, config);
}
var _a291, _b214, MySqlVarBinaryBuilder, _a292, _b215, MySqlVarBinary;
var init_varbinary = __esm({
  "../drizzle-orm/dist/mysql-core/columns/varbinary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlVarBinaryBuilder = class extends (_b214 = MySqlColumnBuilder, _a291 = entityKind, _b214) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "MySqlVarBinary");
        this.config.length = config?.length;
      }
      /** @internal */
      build(table4) {
        return new MySqlVarBinary(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlVarBinaryBuilder, _a291, "MySqlVarBinaryBuilder");
    MySqlVarBinary = class extends (_b215 = MySqlColumn, _a292 = entityKind, _b215) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      getSQLType() {
        return this.length === void 0 ? `varbinary` : `varbinary(${this.length})`;
      }
    };
    __publicField(MySqlVarBinary, _a292, "MySqlVarBinary");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/varchar.js
function varchar2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlVarCharBuilder(name2, config);
}
var _a293, _b216, MySqlVarCharBuilder, _a294, _b217, MySqlVarChar;
var init_varchar2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/varchar.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlVarCharBuilder = class extends (_b216 = MySqlColumnBuilder, _a293 = entityKind, _b216) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "MySqlVarChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table4) {
        return new MySqlVarChar(
          table4,
          this.config
        );
      }
    };
    __publicField(MySqlVarCharBuilder, _a293, "MySqlVarCharBuilder");
    MySqlVarChar = class extends (_b217 = MySqlColumn, _a294 = entityKind, _b217) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
    __publicField(MySqlVarChar, _a294, "MySqlVarChar");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/year.js
function year(name2) {
  return new MySqlYearBuilder(name2 ?? "");
}
var _a295, _b218, MySqlYearBuilder, _a296, _b219, MySqlYear;
var init_year = __esm({
  "../drizzle-orm/dist/mysql-core/columns/year.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlYearBuilder = class extends (_b218 = MySqlColumnBuilder, _a295 = entityKind, _b218) {
      constructor(name2) {
        super(name2, "number", "MySqlYear");
      }
      /** @internal */
      build(table4) {
        return new MySqlYear(table4, this.config);
      }
    };
    __publicField(MySqlYearBuilder, _a295, "MySqlYearBuilder");
    MySqlYear = class extends (_b219 = MySqlColumn, _a296 = entityKind, _b219) {
      getSQLType() {
        return `year`;
      }
    };
    __publicField(MySqlYear, _a296, "MySqlYear");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/index.js
var init_columns3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/index.js"() {
    "use strict";
    init_bigint2();
    init_binary();
    init_boolean2();
    init_char2();
    init_common4();
    init_custom3();
    init_date2();
    init_datetime();
    init_decimal();
    init_double();
    init_enum2();
    init_float();
    init_int();
    init_json2();
    init_mediumint();
    init_real3();
    init_serial2();
    init_smallint2();
    init_text3();
    init_time2();
    init_timestamp2();
    init_tinyint();
    init_varbinary();
    init_varchar2();
    init_year();
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/count.js
var _a297, _b220, _c8, _MySqlCountBuilder, MySqlCountBuilder;
var init_count3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _MySqlCountBuilder = class _MySqlCountBuilder extends (_c8 = SQL, _b220 = entityKind, _a297 = Symbol.toStringTag, _c8) {
      constructor(params) {
        super(_MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a297, "MySqlCountBuilder");
        __publicField(this, "session");
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _MySqlCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters}`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_MySqlCountBuilder, _b220, "MySqlCountBuilder");
    MySqlCountBuilder = _MySqlCountBuilder;
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/delete.js
var _a298, _b221, MySqlDeleteBase;
var init_delete3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    MySqlDeleteBase = class extends (_b221 = QueryPromise, _a298 = entityKind, _b221) {
      constructor(table4, session, dialect4, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlDeleteBase, _a298, "MySqlDelete");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/insert.js
var _a299, MySqlInsertBuilder, _a300, _b222, MySqlInsertBase;
var init_insert3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table();
    init_utils2();
    _a299 = entityKind;
    MySqlInsertBuilder = class {
      constructor(table4, session, dialect4) {
        __publicField(this, "shouldIgnore", false);
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
      }
      ignore() {
        this.shouldIgnore = true;
        return this;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
      }
    };
    __publicField(MySqlInsertBuilder, _a299, "MySqlInsertBuilder");
    MySqlInsertBase = class extends (_b222 = QueryPromise, _a300 = entityKind, _b222) {
      constructor(table4, values, ignore, session, dialect4) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect4;
        this.config = { table: table4, values, ignore };
      }
      /**
       * Adds an `on duplicate key update` clause to the query.
       *
       * Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
       *
       * @param config The `set` clause
       *
       * @example
       * ```ts
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW'})
       *   .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
       * ```
       *
       * While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
       *
       * ```ts
       * import { sql } from 'drizzle-orm';
       *
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onDuplicateKeyUpdate({ set: { id: sql`id` } });
       * ```
       */
      onDuplicateKeyUpdate(config) {
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        this.config.onConflict = sql`update ${setSql}`;
        return this;
      }
      $returningId() {
        const returning = [];
        for (const [key, value] of Object.entries(this.config.table[Table2.Symbol.Columns])) {
          if (value.primary) {
            returning.push({ field: value, path: [key] });
          }
        }
        this.config.returning = returning;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config).sql;
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(sql2),
          void 0,
          void 0,
          generatedIds,
          this.config.returning
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlInsertBase, _a300, "MySqlInsert");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/all.js
function getMySqlColumnBuilders() {
  return {
    bigint: bigint2,
    binary,
    boolean: boolean2,
    char: char2,
    customType: customType3,
    date: date2,
    datetime,
    decimal,
    double,
    mysqlEnum,
    float,
    int,
    json: json2,
    mediumint,
    real: real3,
    serial: serial2,
    smallint: smallint2,
    text: text3,
    time: time2,
    timestamp: timestamp2,
    tinyint,
    varbinary,
    varchar: varchar2,
    year
  };
}
var init_all3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/all.js"() {
    "use strict";
    init_bigint2();
    init_binary();
    init_boolean2();
    init_char2();
    init_custom3();
    init_date2();
    init_datetime();
    init_decimal();
    init_double();
    init_enum2();
    init_float();
    init_int();
    init_json2();
    init_mediumint();
    init_real3();
    init_serial2();
    init_smallint2();
    init_text3();
    init_time2();
    init_timestamp2();
    init_tinyint();
    init_varbinary();
    init_varchar2();
    init_year();
  }
});

// ../drizzle-orm/dist/mysql-core/table.js
function mysqlTableWithSchema(name2, columns, extraConfig, schema4, baseName = name2) {
  const rawTable = new MySqlTable(name2, schema4, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getMySqlColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column4 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys3].push(...colBuilder.buildForeignKeys(column4, rawTable));
      return [name22, column4];
    })
  );
  const table4 = Object.assign(rawTable, builtColumns);
  table4[Table2.Symbol.Columns] = builtColumns;
  table4[Table2.Symbol.ExtraConfigColumns] = builtColumns;
  if (extraConfig) {
    table4[MySqlTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return table4;
}
var InlineForeignKeys3, _a301, _b223, _c9, _d4, _e4, MySqlTable, mysqlTable;
var init_table4 = __esm({
  "../drizzle-orm/dist/mysql-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all3();
    InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
    MySqlTable = class extends (_e4 = Table2, _d4 = entityKind, _c9 = Table2.Symbol.Columns, _b223 = InlineForeignKeys3, _a301 = Table2.Symbol.ExtraConfigBuilder, _e4) {
      constructor() {
        super(...arguments);
        /** @internal */
        __publicField(this, _c9);
        /** @internal */
        __publicField(this, _b223, []);
        /** @internal */
        __publicField(this, _a301);
      }
    };
    __publicField(MySqlTable, _d4, "MySqlTable");
    /** @internal */
    __publicField(MySqlTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys: InlineForeignKeys3
    }));
    mysqlTable = (name2, columns, extraConfig) => {
      return mysqlTableWithSchema(name2, columns, extraConfig, void 0, name2);
    };
  }
});

// ../drizzle-orm/dist/mysql-core/view-base.js
var _a302, _b224, MySqlViewBase;
var init_view_base3 = __esm({
  "../drizzle-orm/dist/mysql-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    MySqlViewBase = class extends (_b224 = View3, _a302 = entityKind, _b224) {
    };
    __publicField(MySqlViewBase, _a302, "MySqlViewBase");
  }
});

// ../drizzle-orm/dist/mysql-core/dialect.js
var _a303, MySqlDialect;
var init_dialect3 = __esm({
  "../drizzle-orm/dist/mysql-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors();
    init_expressions2();
    init_relations();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_common4();
    init_table4();
    init_view_base3();
    _a303 = entityKind;
    MySqlDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      async migrate(migrations, session, config) {
        const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			create table if not exists ${sql.identifier(migrationsTable)} (
				id serial primary key,
				hash text not null,
				created_at bigint
			)
		`;
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsTable)} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name2) {
        return `\`${name2}\``;
      }
      escapeParam(_num) {
        return `?`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length)
          return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}delete from ${table4}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      buildUpdateSet(table4, set) {
        const tableColumns = table4[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table4, set);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}update ${table4} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, MySqlColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(field);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildLimit(limit) {
        return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
      }
      buildOrderBy(orderBy) {
        return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table4,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table4, Subquery) ? table4._.alias : is(table4, MySqlViewBase) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : getTableName(table4)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        const distinctSql = distinct ? sql` distinct` : void 0;
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = (() => {
          if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
            return sql`${sql.identifier(table4[Table2.Symbol.OriginalName])} ${sql.identifier(table4[Table2.Symbol.Name])}`;
          }
          return table4;
        })();
        const joinsArray = [];
        if (joins) {
          for (const [index4, joinMeta] of joins.entries()) {
            if (index4 === 0) {
              joinsArray.push(sql` `);
            }
            const table22 = joinMeta.table;
            const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
            if (is(table22, MySqlTable)) {
              const tableName = table22[MySqlTable.Symbol.Name];
              const tableSchema = table22[MySqlTable.Symbol.Schema];
              const origTableName = table22[MySqlTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
              );
            } else if (is(table22, View3)) {
              const viewName = table22[ViewBaseConfig].name;
              const viewSchema = table22[ViewBaseConfig].schema;
              const origViewName = table22[ViewBaseConfig].originalName;
              const alias = viewName === origViewName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table22} on ${joinMeta.on}`
              );
            }
            if (index4 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        const joinsSql = sql.join(joinsArray);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
        const limitSql = this.buildLimit(limit);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        let lockingClausesSql;
        if (lockingClause) {
          const { config, strength } = lockingClause;
          lockingClausesSql = sql` for ${sql.raw(strength)}`;
          if (config.noWait) {
            lockingClausesSql.append(sql` no wait`);
          } else if (config.skipLocked) {
            lockingClausesSql.append(sql` skip locked`);
          }
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const orderByUnit of orderBy) {
            if (is(orderByUnit, MySqlColumn)) {
              orderByValues.push(sql.identifier(this.casing.getColumnCasing(orderByUnit)));
            } else if (is(orderByUnit, SQL)) {
              for (let i = 0; i < orderByUnit.queryChunks.length; i++) {
                const chunk = orderByUnit.queryChunks[i];
                if (is(chunk, MySqlColumn)) {
                  orderByUnit.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
                }
              }
              orderByValues.push(sql`${orderByUnit}`);
            } else {
              orderByValues.push(sql`${orderByUnit}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table4, values, ignore, onConflict }) {
        const valuesSqlList = [];
        const columns = table4[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(
          ([_2, col]) => !col.shouldDisableInsert()
        );
        const insertOrder = colEntries.map(([, column4]) => sql.identifier(this.casing.getColumnCasing(column4)));
        const generatedIdsResponse = [];
        for (const [valueIndex, value] of values.entries()) {
          const generatedIds = {};
          const valueList = [];
          for (const [fieldName, col] of colEntries) {
            const colValue = value[fieldName];
            if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
              if (col.defaultFn !== void 0) {
                const defaultFnResult = col.defaultFn();
                generatedIds[fieldName] = defaultFnResult;
                const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                valueList.push(defaultValue);
              } else if (!col.default && col.onUpdateFn !== void 0) {
                const onUpdateFnResult = col.onUpdateFn();
                const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                valueList.push(newValue);
              } else {
                valueList.push(sql`default`);
              }
            } else {
              if (col.defaultFn && is(colValue, Param)) {
                generatedIds[fieldName] = colValue.value;
              }
              valueList.push(colValue);
            }
          }
          generatedIdsResponse.push(generatedIds);
          valuesSqlList.push(valueList);
          if (valueIndex < values.length - 1) {
            valuesSqlList.push(sql`, `);
          }
        }
        const valuesSql = sql.join(valuesSqlList);
        const ignoreSql = ignore ? sql` ignore` : void 0;
        const onConflictSql = onConflict ? sql` on duplicate key ${onConflict}` : void 0;
        return {
          sql: sql`insert${ignoreSql} into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}`,
          generatedIds: generatedIdsResponse
        };
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          invokeSource
        });
      }
      buildRelationalQuery({
        fullSchema,
        schema: schema4,
        tableNamesMap,
        table: table4,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy, where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column4 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column4 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema4, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQuery({
              fullSchema,
              schema: schema4,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema4[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_arrayagg(${field}), json_array())`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || (orderBy?.length ?? 0) > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table4, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                },
                ...(orderBy?.length ?? 0) > 0 ? [{
                  path: [],
                  field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
                }] : []
              ],
              where,
              limit,
              offset,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table4, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, MySqlTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table4, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
      buildRelationalQueryWithoutLateralSubqueries({
        fullSchema,
        schema: schema4,
        tableNamesMap,
        table: table4,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column4 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column4 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema4, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQueryWithoutLateralSubqueries({
              fullSchema,
              schema: schema4,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema4[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            let fieldSql = sql`(${builtRelation.sql})`;
            if (is(relation, Many)) {
              fieldSql = sql`coalesce(${fieldSql}, json_array())`;
            }
            const field = fieldSql.as(selectedRelationTsKey);
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({
            message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
          });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2 }) => is(field2, MySqlColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`json_arrayagg(${field})`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field,
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table4, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                },
                ...orderBy.length > 0 ? [{
                  path: [],
                  field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
                }] : []
              ],
              where,
              limit,
              offset,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table4, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, MySqlTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table4, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(MySqlDialect, _a303, "MySqlDialect");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/select.js
function createSetOperator3(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a304, MySqlSelectBuilder, _a305, _b225, MySqlSelectQueryBuilderBase, _a306, _b226, MySqlSelectBase, getMySqlSetOperators, union3, unionAll3, intersect3, intersectAll2, except3, exceptAll2;
var init_select4 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_utils2();
    init_view_common();
    init_view_base3();
    _a304 = entityKind;
    MySqlSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList", []);
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        if (config.withList) {
          this.withList = config.withList;
        }
        this.distinct = config.distinct;
      }
      from(source) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, MySqlViewBase)) {
          fields = source[ViewBaseConfig].selectedFields;
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        return new MySqlSelectBase(
          {
            table: source,
            fields,
            isPartialSelect,
            session: this.session,
            dialect: this.dialect,
            withList: this.withList,
            distinct: this.distinct
          }
        );
      }
    };
    __publicField(MySqlSelectBuilder, _a304, "MySqlSelectBuilder");
    MySqlSelectQueryBuilderBase = class extends (_b225 = TypedQueryBuilder, _a305 = entityKind, _b225) {
      constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
        super();
        __publicField(this, "_");
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        /** @internal */
        __publicField(this, "session");
        __publicField(this, "dialect");
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left"));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right"));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner"));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full"));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/mysql-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/mysql-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/mysql-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `intersect all` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets including all duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
         *
         * @example
         *
         * ```ts
         * // Select all products and quantities that are ordered by both regular and VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered
         * })
         * .from(regularCustomerOrders)
         * .intersectAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { intersectAll } from 'drizzle-orm/mysql-core'
         *
         * await intersectAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "intersectAll", this.createSetOperator("intersect", true));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/mysql-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        /**
         * Adds `except all` set operator to the query.
         *
         * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
         *
         * @example
         *
         * ```ts
         * // Select all products that are ordered by regular customers but not by VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered,
         * })
         * .from(regularCustomerOrders)
         * .exceptAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered,
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { exceptAll } from 'drizzle-orm/mysql-core'
         *
         * await exceptAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "exceptAll", this.createSetOperator("except", true));
        this.config = {
          withList,
          table: table4,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect4;
        this._ = {
          selectedFields: fields
        };
        this.tableName = getTableLikeName(table4);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
      }
      createJoin(joinType) {
        return (table4, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table4);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table4, SQL)) {
              const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table4, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getMySqlSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * See docs: {@link https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config = {}) {
        this.config.lockingClause = { strength, config };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlSelectQueryBuilderBase, _a305, "MySqlSelectQueryBuilder");
    MySqlSelectBase = class extends (_b226 = MySqlSelectQueryBuilderBase, _a306 = entityKind, _b226) {
      constructor() {
        super(...arguments);
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
      }
      prepare() {
        if (!this.session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const fieldsList = orderSelectedFields(this.config.fields);
        const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList);
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
    };
    __publicField(MySqlSelectBase, _a306, "MySqlSelect");
    applyMixins(MySqlSelectBase, [QueryPromise]);
    getMySqlSetOperators = () => ({
      union: union3,
      unionAll: unionAll3,
      intersect: intersect3,
      intersectAll: intersectAll2,
      except: except3,
      exceptAll: exceptAll2
    });
    union3 = createSetOperator3("union", false);
    unionAll3 = createSetOperator3("union", true);
    intersect3 = createSetOperator3("intersect", false);
    intersectAll2 = createSetOperator3("intersect", true);
    except3 = createSetOperator3("except", false);
    exceptAll2 = createSetOperator3("except", true);
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/query-builder.js
var _a307, QueryBuilder3;
var init_query_builder4 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_dialect3();
    init_selection_proxy();
    init_subquery();
    init_select4();
    _a307 = entityKind;
    QueryBuilder3 = class {
      constructor(dialect4) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        this.dialect = is(dialect4, MySqlDialect) ? dialect4 : void 0;
        this.dialectConfig = is(dialect4, MySqlDialect) ? void 0 : dialect4;
      }
      $with(alias) {
        const queryBuilder = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries,
            distinct: true
          });
        }
        return { select, selectDistinct };
      }
      select(fields) {
        return new MySqlSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
      }
      selectDistinct(fields) {
        return new MySqlSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new MySqlDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder3, _a307, "MySqlQueryBuilder");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/select.types.js
var init_select_types3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/update.js
var _a308, MySqlUpdateBuilder, _a309, _b227, MySqlUpdateBase;
var init_update3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_utils2();
    _a308 = entityKind;
    MySqlUpdateBuilder = class {
      constructor(table4, session, dialect4, withList) {
        this.table = table4;
        this.session = session;
        this.dialect = dialect4;
        this.withList = withList;
      }
      set(values) {
        return new MySqlUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
      }
    };
    __publicField(MySqlUpdateBuilder, _a308, "MySqlUpdateBuilder");
    MySqlUpdateBase = class extends (_b227 = QueryPromise, _a309 = entityKind, _b227) {
      constructor(table4, set, session, dialect4, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect4;
        this.config = { set, table: table4, withList };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlUpdateBase, _a309, "MySqlUpdate");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/index.js
var init_query_builders3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/index.js"() {
    "use strict";
    init_delete3();
    init_insert3();
    init_query_builder4();
    init_select4();
    init_select_types3();
    init_update3();
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/query.js
var _a310, RelationalQueryBuilder3, _a311, _b228, MySqlRelationalQuery;
var init_query3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    _a310 = entityKind;
    RelationalQueryBuilder3 = class {
      constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session, mode) {
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
        this.mode = mode;
      }
      findMany(config) {
        return new MySqlRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many",
          this.mode
        );
      }
      findFirst(config) {
        return new MySqlRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first",
          this.mode
        );
      }
    };
    __publicField(RelationalQueryBuilder3, _a310, "MySqlRelationalQueryBuilder");
    MySqlRelationalQuery = class extends (_b228 = QueryPromise, _a311 = entityKind, _b228) {
      constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session, config, queryMode, mode) {
        super();
        this.fullSchema = fullSchema;
        this.schema = schema4;
        this.tableNamesMap = tableNamesMap;
        this.table = table4;
        this.tableConfig = tableConfig;
        this.dialect = dialect4;
        this.session = session;
        this.config = config;
        this.queryMode = queryMode;
        this.mode = mode;
      }
      prepare() {
        const { query, builtQuery } = this._toSQL();
        return this.session.prepareQuery(
          builtQuery,
          void 0,
          (rawRows) => {
            const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection));
            if (this.queryMode === "first") {
              return rows[0];
            }
            return rows;
          }
        );
      }
      _getQuery() {
        const query = this.mode === "planetscale" ? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        }) : this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
        return query;
      }
      _toSQL() {
        const query = this._getQuery();
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { builtQuery, query };
      }
      /** @internal */
      getSQL() {
        return this._getQuery().sql;
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      execute() {
        return this.prepare().execute();
      }
    };
    __publicField(MySqlRelationalQuery, _a311, "MySqlRelationalQuery");
  }
});

// ../drizzle-orm/dist/mysql-core/db.js
var _a312, MySqlDatabase;
var init_db3 = __esm({
  "../drizzle-orm/dist/mysql-core/db.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count3();
    init_query_builders3();
    init_query3();
    _a312 = entityKind;
    MySqlDatabase = class {
      constructor(dialect4, session, schema4, mode) {
        __publicField(this, "query");
        this.dialect = dialect4;
        this.session = session;
        this.mode = mode;
        this._ = schema4 ? {
          schema: schema4.schema,
          fullSchema: schema4.fullSchema,
          tableNamesMap: schema4.tableNamesMap
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {}
        };
        this.query = {};
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            this.query[tableName] = new RelationalQueryBuilder3(
              schema4.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema4.fullSchema[tableName],
              columns,
              dialect4,
              session,
              this.mode
            );
          }
        }
      }
      /**
       * Creates a subquery that defines a temporary named result set as a CTE.
       *
       * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param alias The alias for the subquery.
       *
       * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
       *
       * @example
       *
       * ```ts
       * // Create a subquery with alias 'sq' and use it in the select query
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * const result = await db.with(sq).select().from(sq);
       * ```
       *
       * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
       *
       * ```ts
       * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
       * const sq = db.$with('sq').as(db.select({
       *   name: sql<string>`upper(${users.name})`.as('name'),
       * })
       * .from(users));
       *
       * const result = await db.with(sq).select({ name: sq.name }).from(sq);
       * ```
       */
      $with(alias) {
        const self2 = this;
        return {
          as(qb) {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder3(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          }
        };
      }
      $count(source, filters) {
        return new MySqlCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function update(table4) {
          return new MySqlUpdateBuilder(table4, self2.session, self2.dialect, queries);
        }
        function delete_(table4) {
          return new MySqlDeleteBase(table4, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, update, delete: delete_ };
      }
      select(fields) {
        return new MySqlSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
      }
      selectDistinct(fields) {
        return new MySqlSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       * ```
       */
      update(table4) {
        return new MySqlUpdateBuilder(table4, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       * ```
       */
      insert(table4) {
        return new MySqlInsertBuilder(table4, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * ```
       */
      delete(table4) {
        return new MySqlDeleteBase(table4, this.session, this.dialect);
      }
      execute(query) {
        return this.session.execute(typeof query === "string" ? sql.raw(query) : query.getSQL());
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(MySqlDatabase, _a312, "MySqlDatabase");
  }
});

// ../drizzle-orm/dist/mysql-core/indexes.js
var _a313, IndexBuilderOn3, _a314, IndexBuilder3, _a315, Index5;
var init_indexes3 = __esm({
  "../drizzle-orm/dist/mysql-core/indexes.js"() {
    "use strict";
    init_entity();
    _a313 = entityKind;
    IndexBuilderOn3 = class {
      constructor(name2, unique) {
        this.name = name2;
        this.unique = unique;
      }
      on(...columns) {
        return new IndexBuilder3(this.name, columns, this.unique);
      }
    };
    __publicField(IndexBuilderOn3, _a313, "MySqlIndexBuilderOn");
    _a314 = entityKind;
    IndexBuilder3 = class {
      constructor(name2, columns, unique) {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique
        };
      }
      using(using) {
        this.config.using = using;
        return this;
      }
      algorythm(algorythm) {
        this.config.algorythm = algorythm;
        return this;
      }
      lock(lock) {
        this.config.lock = lock;
        return this;
      }
      /** @internal */
      build(table4) {
        return new Index5(this.config, table4);
      }
    };
    __publicField(IndexBuilder3, _a314, "MySqlIndexBuilder");
    _a315 = entityKind;
    Index5 = class {
      constructor(config, table4) {
        __publicField(this, "config");
        this.config = { ...config, table: table4 };
      }
    };
    __publicField(Index5, _a315, "MySqlIndex");
  }
});

// ../drizzle-orm/dist/mysql-core/primary-keys.js
var _a316, PrimaryKeyBuilder3, _a317, PrimaryKey3;
var init_primary_keys3 = __esm({
  "../drizzle-orm/dist/mysql-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table4();
    _a316 = entityKind;
    PrimaryKeyBuilder3 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table4) {
        return new PrimaryKey3(table4, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder3, _a316, "MySqlPrimaryKeyBuilder");
    _a317 = entityKind;
    PrimaryKey3 = class {
      constructor(table4, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table4;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[MySqlTable.Symbol.Name]}_${this.columns.map((column4) => column4.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey3, _a317, "MySqlPrimaryKey");
  }
});

// ../drizzle-orm/dist/mysql-core/view-common.js
var MySqlViewConfig;
var init_view_common3 = __esm({
  "../drizzle-orm/dist/mysql-core/view-common.js"() {
    "use strict";
    MySqlViewConfig = Symbol.for("drizzle:MySqlViewConfig");
  }
});

// ../drizzle-orm/dist/mysql-core/view.js
function mysqlViewWithSchema(name2, selection, schema4) {
  if (selection) {
    return new ManualViewBuilder3(name2, selection, schema4);
  }
  return new ViewBuilder3(name2, schema4);
}
var _a318, ViewBuilderCore2, _a319, _b229, ViewBuilder3, _a320, _b230, ManualViewBuilder3, _a321, _b231, _c10, MySqlView2;
var init_view3 = __esm({
  "../drizzle-orm/dist/mysql-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder4();
    init_table4();
    init_view_base3();
    init_view_common3();
    _a318 = entityKind;
    ViewBuilderCore2 = class {
      constructor(name2, schema4) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema4;
      }
      algorithm(algorithm) {
        this.config.algorithm = algorithm;
        return this;
      }
      sqlSecurity(sqlSecurity) {
        this.config.sqlSecurity = sqlSecurity;
        return this;
      }
      withCheckOption(withCheckOption) {
        this.config.withCheckOption = withCheckOption ?? "cascaded";
        return this;
      }
    };
    __publicField(ViewBuilderCore2, _a318, "MySqlViewBuilder");
    ViewBuilder3 = class extends (_b229 = ViewBuilderCore2, _a319 = entityKind, _b229) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder3());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new MySqlView2({
            mysqlConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder3, _a319, "MySqlViewBuilder");
    ManualViewBuilder3 = class extends (_b230 = ViewBuilderCore2, _a320 = entityKind, _b230) {
      constructor(name2, columns, schema4) {
        super(name2, schema4);
        __publicField(this, "columns");
        this.columns = getTableColumns(mysqlTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new MySqlView2({
            mysqlConfig: void 0,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new MySqlView2({
            mysqlConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder3, _a320, "MySqlManualViewBuilder");
    MySqlView2 = class extends (_c10 = MySqlViewBase, _b231 = entityKind, _a321 = MySqlViewConfig, _c10) {
      constructor({ mysqlConfig, config }) {
        super(config);
        __publicField(this, _a321);
        this[MySqlViewConfig] = mysqlConfig;
      }
    };
    __publicField(MySqlView2, _b231, "MySqlView");
  }
});

// ../drizzle-orm/dist/mysql-core/schema.js
var _a322, MySqlSchema5;
var init_schema2 = __esm({
  "../drizzle-orm/dist/mysql-core/schema.js"() {
    "use strict";
    init_entity();
    init_table4();
    init_view3();
    _a322 = entityKind;
    MySqlSchema5 = class {
      constructor(schemaName) {
        __publicField(this, "table", (name2, columns, extraConfig) => {
          return mysqlTableWithSchema(name2, columns, extraConfig, this.schemaName);
        });
        __publicField(this, "view", (name2, columns) => {
          return mysqlViewWithSchema(name2, columns, this.schemaName);
        });
        this.schemaName = schemaName;
      }
    };
    __publicField(MySqlSchema5, _a322, "MySqlSchema");
  }
});

// ../drizzle-orm/dist/mysql-core/session.js
var _a323, MySqlPreparedQuery, _a324, MySqlSession, _a325, _b232, MySqlTransaction;
var init_session3 = __esm({
  "../drizzle-orm/dist/mysql-core/session.js"() {
    "use strict";
    init_entity();
    init_errors();
    init_sql();
    init_db3();
    _a323 = entityKind;
    MySqlPreparedQuery = class {
      constructor() {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
      }
    };
    __publicField(MySqlPreparedQuery, _a323, "MySqlPreparedQuery");
    _a324 = entityKind;
    MySqlSession = class {
      constructor(dialect4) {
        this.dialect = dialect4;
      }
      execute(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0
        ).execute();
      }
      async count(sql2) {
        const res = await this.execute(sql2);
        return Number(
          res[0][0]["count"]
        );
      }
      getSetTransactionSQL(config) {
        const parts = [];
        if (config.isolationLevel) {
          parts.push(`isolation level ${config.isolationLevel}`);
        }
        return parts.length ? sql`set transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
      getStartTransactionSQL(config) {
        const parts = [];
        if (config.withConsistentSnapshot) {
          parts.push("with consistent snapshot");
        }
        if (config.accessMode) {
          parts.push(config.accessMode);
        }
        return parts.length ? sql`start transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
    };
    __publicField(MySqlSession, _a324, "MySqlSession");
    MySqlTransaction = class extends (_b232 = MySqlDatabase, _a325 = entityKind, _b232) {
      constructor(dialect4, session, schema4, nestedIndex, mode) {
        super(dialect4, session, schema4, mode);
        this.schema = schema4;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
    };
    __publicField(MySqlTransaction, _a325, "MySqlTransaction");
  }
});

// ../drizzle-orm/dist/mysql-core/subquery.js
var init_subquery4 = __esm({
  "../drizzle-orm/dist/mysql-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/utils.js
function getTableConfig3(table4) {
  const columns = Object.values(table4[MySqlTable.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const uniqueConstraints = [];
  const foreignKeys = Object.values(table4[MySqlTable.Symbol.InlineForeignKeys]);
  const name2 = table4[Table2.Symbol.Name];
  const schema4 = table4[Table2.Symbol.Schema];
  const baseName = table4[Table2.Symbol.BaseName];
  const extraConfigBuilder = table4[MySqlTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table4[MySqlTable.Symbol.Columns]);
    for (const builder of Object.values(extraConfig)) {
      if (is(builder, IndexBuilder3)) {
        indexes.push(builder.build(table4));
      } else if (is(builder, CheckBuilder3)) {
        checks.push(builder.build(table4));
      } else if (is(builder, UniqueConstraintBuilder3)) {
        uniqueConstraints.push(builder.build(table4));
      } else if (is(builder, PrimaryKeyBuilder3)) {
        primaryKeys.push(builder.build(table4));
      } else if (is(builder, ForeignKeyBuilder3)) {
        foreignKeys.push(builder.build(table4));
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2,
    schema: schema4,
    baseName
  };
}
function getViewConfig3(view4) {
  return {
    ...view4[ViewBaseConfig],
    ...view4[MySqlViewConfig]
  };
}
var init_utils8 = __esm({
  "../drizzle-orm/dist/mysql-core/utils.js"() {
    "use strict";
    init_entity();
    init_table();
    init_view_common();
    init_checks3();
    init_foreign_keys3();
    init_indexes3();
    init_primary_keys3();
    init_table4();
    init_unique_constraint3();
    init_view_common3();
  }
});

// ../drizzle-orm/dist/mysql-core/index.js
var init_mysql_core = __esm({
  "../drizzle-orm/dist/mysql-core/index.js"() {
    "use strict";
    init_alias4();
    init_checks3();
    init_columns3();
    init_db3();
    init_dialect3();
    init_foreign_keys3();
    init_indexes3();
    init_primary_keys3();
    init_query_builders3();
    init_schema2();
    init_session3();
    init_subquery4();
    init_table4();
    init_unique_constraint3();
    init_utils8();
    init_view_common3();
    init_view3();
  }
});

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

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

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

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

// src/cli/validations/libsql.ts
var libSQLCredentials;
var init_libsql = __esm({
  "src/cli/validations/libsql.ts"() {
    "use strict";
    init_lib();
    init_views();
    init_common();
    libSQLCredentials = objectType({
      url: stringType().min(1),
      authToken: stringType().min(1).optional()
    });
  }
});

// src/cli/validations/mysql.ts
var mysqlCredentials;
var init_mysql = __esm({
  "src/cli/validations/mysql.ts"() {
    "use strict";
    init_lib();
    init_views();
    init_common();
    init_outputs();
    mysqlCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/postgres.ts
var postgresCredentials;
var init_postgres = __esm({
  "src/cli/validations/postgres.ts"() {
    "use strict";
    init_lib();
    init_views();
    init_common();
    postgresCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          literalType("require"),
          literalType("allow"),
          literalType("prefer"),
          literalType("verify-full"),
          booleanType(),
          objectType({}).passthrough()
        ]).optional()
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: literalType("aws-data-api"),
        database: stringType().min(1),
        secretArn: stringType().min(1),
        resourceArn: stringType().min(1)
      }),
      objectType({
        driver: literalType("pglite"),
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/sqlite.ts
var sqliteCredentials;
var init_sqlite = __esm({
  "src/cli/validations/sqlite.ts"() {
    "use strict";
    init_global();
    init_lib();
    init_views();
    init_common();
    sqliteCredentials = unionType([
      objectType({
        driver: literalType("turso"),
        url: stringType().min(1),
        authToken: stringType().min(1).optional()
      }),
      objectType({
        driver: literalType("d1-http"),
        accountId: stringType().min(1),
        databaseId: stringType().min(1),
        token: stringType().min(1)
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o) => {
        delete o.driver;
        return o;
      })
    ]);
  }
});

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

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

// src/cli/commands/utils.ts
var import_hanji7, assertES5, safeRegister, migrateConfig;
var init_utils9 = __esm({
  "src/cli/commands/utils.ts"() {
    "use strict";
    import_hanji7 = __toESM(require_hanji());
    init_lib();
    init_getTablesFilterByExtensions();
    init_global();
    init_schemaValidator();
    init_serializer();
    init_cli();
    init_common();
    init_libsql();
    init_libsql();
    init_mysql();
    init_outputs();
    init_postgres();
    init_sqlite();
    init_studio();
    init_views();
    assertES5 = async (unregister) => {
      try {
        init_es5();
      } catch (e) {
        if ("errors" in e && Array.isArray(e.errors) && e.errors.length > 0) {
          const es5Error = e.errors.filter((it) => it.text?.includes(`("es5") is not supported yet`)).length > 0;
          if (es5Error) {
            console.log(
              error(
                `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
              )
            );
            process.exit(1);
          }
        }
        console.error(e);
        process.exit(1);
      }
    };
    safeRegister = async () => {
      const { register } = require("esbuild-register/dist/node");
      let res;
      try {
        res = register({
          format: "cjs",
          loader: "ts"
        });
      } catch {
        res = {
          unregister: () => {
          }
        };
      }
      await assertES5(res.unregister);
      return res;
    };
    migrateConfig = objectType({
      dialect: dialect3,
      out: stringType().optional().default("drizzle"),
      migrations: configMigrations
    });
  }
});

// src/serializer/pgImports.ts
var prepareFromExports;
var init_pgImports = __esm({
  "src/serializer/pgImports.ts"() {
    "use strict";
    init_dist();
    init_pg_core();
    init_utils9();
    prepareFromExports = (exports2) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const roles = [];
      const policies = [];
      const views = [];
      const matViews = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t) => {
        if (isPgEnum(t)) {
          enums.push(t);
          return;
        }
        if (is(t, PgTable)) {
          tables.push(t);
        }
        if (is(t, PgSchema5)) {
          schemas.push(t);
        }
        if (isPgView(t)) {
          views.push(t);
        }
        if (isPgMaterializedView(t)) {
          matViews.push(t);
        }
        if (isPgSequence(t)) {
          sequences.push(t);
        }
        if (is(t, PgRole)) {
          roles.push(t);
        }
        if (is(t, PgPolicy)) {
          policies.push(t);
        }
      });
      return { tables, enums, schemas, sequences, views, matViews, roles, policies };
    };
  }
});

// src/serializer/sqliteImports.ts
var sqliteImports_exports = {};
__export(sqliteImports_exports, {
  prepareFromExports: () => prepareFromExports2,
  prepareFromSqliteImports: () => prepareFromSqliteImports
});
var prepareFromExports2, prepareFromSqliteImports;
var init_sqliteImports = __esm({
  "src/serializer/sqliteImports.ts"() {
    "use strict";
    init_dist();
    init_sqlite_core();
    init_utils9();
    prepareFromExports2 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t) => {
        if (is(t, SQLiteTable)) {
          tables.push(t);
        }
        if (is(t, SQLiteView2)) {
          views.push(t);
        }
      });
      return { tables, views };
    };
    prepareFromSqliteImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i = 0; i < imports.length; i++) {
        const it = imports[i];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports2(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/mysqlImports.ts
var mysqlImports_exports = {};
__export(mysqlImports_exports, {
  prepareFromExports: () => prepareFromExports3,
  prepareFromMySqlImports: () => prepareFromMySqlImports
});
var prepareFromExports3, prepareFromMySqlImports;
var init_mysqlImports = __esm({
  "src/serializer/mysqlImports.ts"() {
    "use strict";
    init_dist();
    init_mysql_core();
    init_utils9();
    prepareFromExports3 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t) => {
        if (is(t, MySqlTable)) {
          tables.push(t);
        }
        if (is(t, MySqlView2)) {
          views.push(t);
        }
      });
      return { tables, views };
    };
    prepareFromMySqlImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i = 0; i < imports.length; i++) {
        const it = imports[i];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports3(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

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

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

// src/api.ts
var api_exports = {};
__export(api_exports, {
  generateDrizzleJson: () => generateDrizzleJson,
  generateMigration: () => generateMigration,
  generateMySQLDrizzleJson: () => generateMySQLDrizzleJson,
  generateMySQLMigration: () => generateMySQLMigration,
  generateSQLiteDrizzleJson: () => generateSQLiteDrizzleJson,
  generateSQLiteMigration: () => generateSQLiteMigration,
  pushMySQLSchema: () => pushMySQLSchema,
  pushSQLiteSchema: () => pushSQLiteSchema,
  pushSchema: () => pushSchema,
  upPgSnapshot: () => upPgSnapshot
});
module.exports = __toCommonJS(api_exports);
var import_crypto = require("crypto");
init_migrate();

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

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

// src/cli/commands/pgUp.ts
init_pgSchema();
init_utils();
var updateUpToV6 = (json3) => {
  const schema4 = pgSchemaV5.parse(json3);
  const tables = Object.fromEntries(
    Object.entries(schema4.tables).map((it) => {
      const table4 = it[1];
      const schema5 = table4.schema || "public";
      return [`${schema5}.${table4.name}`, table4];
    })
  );
  const enums = Object.fromEntries(
    Object.entries(schema4.enums).map((it) => {
      const en = it[1];
      return [
        `public.${en.name}`,
        {
          name: en.name,
          schema: "public",
          values: Object.values(en.values)
        }
      ];
    })
  );
  return {
    ...schema4,
    version: "6",
    dialect: "postgresql",
    tables,
    enums
  };
};
var updateUpToV7 = (json3) => {
  const schema4 = pgSchemaV6.parse(json3);
  const tables = Object.fromEntries(
    Object.entries(schema4.tables).map((it) => {
      const table4 = it[1];
      const mappedIndexes = Object.fromEntries(
        Object.entries(table4.indexes).map((idx) => {
          const { columns, ...rest } = idx[1];
          const mappedColumns = columns.map((it2) => {
            return {
              expression: it2,
              isExpression: false,
              asc: true,
              nulls: "last",
              opClass: void 0
            };
          });
          return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
        })
      );
      return [it[0], { ...table4, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
    })
  );
  return {
    ...schema4,
    version: "7",
    dialect: "postgresql",
    sequences: {},
    tables,
    policies: {},
    views: {},
    roles: {}
  };
};

// src/cli/commands/sqliteIntrospect.ts
var import_hanji6 = __toESM(require_hanji());
init_mjs();
init_global();

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

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

// src/introspect-sqlite.ts
init_global();

// src/cli/commands/sqliteIntrospect.ts
init_sqliteSerializer();
init_views();
var sqlitePushIntrospect = async (db, filters) => {
  const matchers = filters.map((it) => {
    return new Minimatch(it);
  });
  const filter2 = (tableName) => {
    if (matchers.length === 0) return true;
    let flags = [];
    for (let matcher of matchers) {
      if (matcher.negate) {
        if (!matcher.match(tableName)) {
          flags.push(false);
        }
      }
      if (matcher.match(tableName)) {
        flags.push(true);
      }
    }
    if (flags.length > 0) {
      return flags.every(Boolean);
    }
    return false;
  };
  const progress = new ProgressView(
    "Pulling schema from database...",
    "Pulling schema from database..."
  );
  const res = await (0, import_hanji6.renderWithTask)(progress, fromDatabase2(db, filter2));
  const schema4 = { id: originUUID, prevId: "", ...res };
  return { schema: schema4 };
};

// src/api.ts
init_sqlitePushUtils();
init_getTablesFilterByExtensions();
init_global();
init_migrationPreparator();
init_mysqlSchema();
init_mysqlSerializer();
init_pgImports();
init_pgSchema();
init_pgSerializer();
init_sqliteSchema();
init_sqliteSerializer();
var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
  const prepared = prepareFromExports(imports);
  const id = (0, import_crypto.randomUUID)();
  const snapshot = generatePgSnapshot(
    prepared.tables,
    prepared.enums,
    prepared.schemas,
    prepared.sequences,
    prepared.roles,
    prepared.policies,
    prepared.views,
    prepared.matViews,
    casing2,
    schemaFilters
  );
  return fillPgSnapshot({
    serialized: snapshot,
    id,
    idPrev: prevId ?? originUUID
  });
};
var generateMigration = async (prev, cur) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev);
  const squashedCur = squashPgScheme(validatedCur);
  const { sqlStatements, _meta } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSchema = async (imports, drizzleInstance, schemaFilters, tablesFilter, extensionsFilters) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const filters = (tablesFilter ?? []).concat(
    getTablesFilterByExtensions({ extensionsFilters, dialect: "postgresql" })
  );
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql2.raw(query));
      return res.rows;
    }
  };
  const cur = generateDrizzleJson(imports);
  const { schema: prev } = await pgPushIntrospect(
    db,
    filters,
    schemaFilters ?? ["public"],
    void 0
  );
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev, "push");
  const squashedCur = squashPgScheme(validatedCur, "push");
  const { statements } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await pgSuggestions(db, statements);
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
  const prepared = prepareFromExports4(imports);
  const id = (0, import_crypto.randomUUID)();
  const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateSQLiteMigration = async (prev, cur) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev);
  const squashedCur = squashSqliteScheme(validatedCur);
  const { sqlStatements } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSQLiteSchema = async (imports, drizzleInstance) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const db = {
    query: async (query, params) => {
      const res = drizzleInstance.all(sql2.raw(query));
      return res;
    },
    run: async (query) => {
      return Promise.resolve(drizzleInstance.run(sql2.raw(query))).then(
        () => {
        }
      );
    }
  };
  const cur = await generateSQLiteDrizzleJson(imports);
  const { schema: prev } = await sqlitePushIntrospect(db, []);
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  const squashedCur = squashSqliteScheme(validatedCur, "push");
  const { statements, _meta } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn(
    db,
    statements,
    squashedPrev,
    squashedCur,
    _meta
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
  const prepared = prepareFromExports4(imports);
  const id = (0, import_crypto.randomUUID)();
  const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateMySQLMigration = async (prev, cur) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { sqlStatements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { logSuggestionsAndReturn: logSuggestionsAndReturn3 } = await Promise.resolve().then(() => (init_mysqlPushUtils(), mysqlPushUtils_exports));
  const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql2.raw(query));
      return res[0];
    }
  };
  const cur = await generateMySQLDrizzleJson(imports);
  const { schema: prev } = await mysqlPushIntrospect2(db, databaseName, []);
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { statements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn3(
    db,
    statements,
    validatedCur
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var upPgSnapshot = (snapshot) => {
  if (snapshot.version === "5") {
    return updateUpToV7(updateUpToV6(snapshot));
  }
  if (snapshot.version === "6") {
    return updateUpToV7(snapshot);
  }
  return snapshot;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  generateDrizzleJson,
  generateMigration,
  generateMySQLDrizzleJson,
  generateMySQLMigration,
  generateSQLiteDrizzleJson,
  generateSQLiteMigration,
  pushMySQLSchema,
  pushSQLiteSchema,
  pushSchema,
  upPgSnapshot
});
