/
ai_sampletext
/
DiplomWork
Обзор
Документация
Войти
/
ai_sampletext
/
DiplomWork
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
node_modules/drizzle-kit/api.js
75 680 строк
3 MB
boolyshareyo
Initial commit
08 июн 2026, 16:00
08 июн 2026, 16:00
6216a29
Код
Авторство
О чём код?
"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 __typeError = (msg) => { throw TypeError(msg); }; 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 name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var __privateWrapper = (obj, member, setter, getter) => ({ set _(value) { __privateSet(obj, member, value, setter); }, get _() { return __privateGet(obj, member, getter); } }); // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js function assembleStyles() { const codes = /* @__PURE__ */ new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\x1B[${style[0]}m`, close: `\x1B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, "codes", { value: codes, enumerable: false }); styles.color.close = "\x1B[39m"; styles.bgColor.close = "\x1B[49m"; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles, { rgbToAnsi256: { value(red, green, blue) { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ integer >> 16 & 255, integer >> 8 & 255, integer & 255 /* eslint-enable no-bitwise */ ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = ((code - 232) * 10 + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = remainder % 6 / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false }, hexToAnsi: { value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false } }); return styles; } var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default; var init_ansi_styles = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() { "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.4.1/node_modules/chalk/source/vendor/supports-color/index.js function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) { const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; const position = argv.indexOf(prefix2 + flag); const terminatorPosition = argv.indexOf("--"); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } function envForceColor() { if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { return 1; } if (env.FORCE_COLOR === "false") { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== void 0) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { return 3; } if (hasFlag("color=256")) { return 2; } } if ("TF_BUILD" in env && "AGENT_NAME" in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if (import_node_process.default.platform === "win32") { const osRelease = import_node_os.default.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env) { if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) { return 3; } if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if (env.TERM === "xterm-kitty") { return 3; } if ("TERM_PROGRAM" in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": { return version >= 3 ? 3 : 2; } case "Apple_Terminal": { return 2; } } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } return min; } function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } var import_node_process, import_node_os, import_node_tty, env, flagForceColor, supportsColor, supports_color_default; var init_supports_color = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js"() { "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.4.1/node_modules/chalk/source/utilities.js function stringReplaceAll(string, substring2, replacer) { let index6 = string.indexOf(substring2); if (index6 === -1) { return string; } const substringLength = substring2.length; let endIndex = 0; let returnValue = ""; do { returnValue += string.slice(endIndex, index6) + substring2 + replacer; endIndex = index6 + substringLength; index6 = string.indexOf(substring2, endIndex); } while (index6 !== -1); returnValue += string.slice(endIndex); return returnValue; } function stringEncaseCRLFWithFirstIndex(string, prefix2, postfix, index6) { let endIndex = 0; let returnValue = ""; do { const gotCR = string[index6 - 1] === "\r"; returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix; endIndex = index6 + 1; index6 = string.indexOf("\n", endIndex); } while (index6 !== -1); returnValue += string.slice(endIndex); return returnValue; } var init_utilities = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() { "use strict"; } }); // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js function createChalk(options) { return chalkFactory(options); } var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default; var init_source = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() { "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 fs5 = require("fs"); var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { var callback; if (DEBUG) { var backtrace = new Error(); callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err2) { if (err2) { backtrace.message = err2.message; err2 = backtrace; missingCallback(err2); } } function missingCallback(err2) { if (err2) { if (process.throwDeprecation) throw err2; else if (!process.noDeprecation) { var msg = "fs: missing callback " + (err2.stack || err2.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === "function" ? cb : rethrow(); } var normalize = pathModule.normalize; if (isWindows) { nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { nextPartRe = /(.*?)(?:[\/]+|$)/g; } var nextPartRe; if (isWindows) { splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { splitRootRe = /^[\/]*/; } var splitRootRe; exports2.realpathSync = function realpathSync(p5, cache5) { p5 = pathModule.resolve(p5); if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) { return cache5[p5]; } var original = p5, seenLinks = {}, knownHard = {}; var pos; var current; var base; var previous; start(); function start() { var m6 = splitRootRe.exec(p5); pos = m6[0].length; current = m6[0]; base = m6[0]; previous = ""; if (isWindows && !knownHard[base]) { fs5.lstatSync(base); knownHard[base] = true; } } while (pos < p5.length) { nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p5); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; if (knownHard[base] || cache5 && cache5[base] === base) { continue; } var resolvedLink; if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) { resolvedLink = cache5[base]; } else { var stat2 = fs5.lstatSync(base); if (!stat2.isSymbolicLink()) { knownHard[base] = true; if (cache5) cache5[base] = base; continue; } var linkTarget = null; if (!isWindows) { var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs5.statSync(base); linkTarget = fs5.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); if (cache5) cache5[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } p5 = pathModule.resolve(resolvedLink, p5.slice(pos)); start(); } if (cache5) cache5[original] = p5; return p5; }; exports2.realpath = function realpath(p5, cache5, cb) { if (typeof cb !== "function") { cb = maybeCallback(cache5); cache5 = null; } p5 = pathModule.resolve(p5); if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) { return process.nextTick(cb.bind(null, null, cache5[p5])); } var original = p5, seenLinks = {}, knownHard = {}; var pos; var current; var base; var previous; start(); function start() { var m6 = splitRootRe.exec(p5); pos = m6[0].length; current = m6[0]; base = m6[0]; previous = ""; if (isWindows && !knownHard[base]) { fs5.lstat(base, function(err2) { if (err2) return cb(err2); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } function LOOP() { if (pos >= p5.length) { if (cache5) cache5[original] = p5; return cb(null, p5); } nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p5); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; if (knownHard[base] || cache5 && cache5[base] === base) { return process.nextTick(LOOP); } if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) { return gotResolvedLink(cache5[base]); } return fs5.lstat(base, gotStat); } function gotStat(err2, stat2) { if (err2) return cb(err2); if (!stat2.isSymbolicLink()) { knownHard[base] = true; if (cache5) cache5[base] = base; return process.nextTick(LOOP); } if (!isWindows) { var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs5.stat(base, function(err3) { if (err3) return cb(err3); fs5.readlink(base, function(err4, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err4, target); }); }); } function gotTarget(err2, target, base2) { if (err2) return cb(err2); var resolvedLink = pathModule.resolve(previous, target); if (cache5) cache5[base2] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { p5 = pathModule.resolve(resolvedLink, p5.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 fs5 = require("fs"); var origRealpath = fs5.realpath; var origRealpathSync = fs5.realpathSync; var version = process.version; var ok = /^v[0-5]\./.test(version); var old = require_old(); function newError(er) { return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG"); } function realpath(p5, cache5, cb) { if (ok) { return origRealpath(p5, cache5, cb); } if (typeof cache5 === "function") { cb = cache5; cache5 = null; } origRealpath(p5, cache5, function(er, result) { if (newError(er)) { old.realpath(p5, cache5, cb); } else { cb(er, result); } }); } function realpathSync(p5, cache5) { if (ok) { return origRealpathSync(p5, cache5); } try { return origRealpathSync(p5, cache5); } catch (er) { if (newError(er)) { return old.realpathSync(p5, cache5); } else { throw er; } } } function monkeypatch() { fs5.realpath = realpath; fs5.realpathSync = realpathSync; } function unmonkeypatch() { fs5.realpath = origRealpath; fs5.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(a5, b5, str) { if (a5 instanceof RegExp) a5 = maybeMatch(a5, str); if (b5 instanceof RegExp) b5 = maybeMatch(b5, str); var r6 = range(a5, b5, str); return r6 && { start: r6[0], end: r6[1], pre: str.slice(0, r6[0]), body: str.slice(r6[0] + a5.length, r6[1]), post: str.slice(r6[1] + b5.length) }; } function maybeMatch(reg, str) { var m6 = str.match(reg); return m6 ? m6[0] : null; } balanced.range = range; function range(a5, b5, str) { var begs, beg, left, right, result; var ai = str.indexOf(a5); var bi = str.indexOf(b5, ai + 1); var i6 = ai; if (ai >= 0 && bi > 0) { if (a5 === b5) { return [ai, bi]; } begs = []; left = str.length; while (i6 >= 0 && !result) { if (i6 == ai) { begs.push(i6); ai = str.indexOf(a5, i6 + 1); } else if (begs.length == 1) { result = [begs.pop(), bi]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b5, i6 + 1); } i6 = 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 numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); } function parseCommaParts(str) { if (!str) return [""]; var parts = []; var m6 = balanced("{", "}", str); if (!m6) return str.split(","); var pre = m6.pre; var body = m6.body; var post = m6.post; var p5 = pre.split(","); p5[p5.length - 1] += "{" + body + "}"; var postParts = parseCommaParts(post); if (post.length) { p5[p5.length - 1] += postParts.shift(); p5.push.apply(p5, postParts); } parts.push.apply(parts, p5); return parts; } function expandTop(str) { if (!str) return []; if (str.substr(0, 2) === "{}") { str = "\\{\\}" + str.substr(2); } return expand2(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return "{" + str + "}"; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i6, y2) { return i6 <= y2; } function gte(i6, y2) { return i6 >= y2; } function expand2(str, isTop) { var expansions = []; var m6 = balanced("{", "}", str); if (!m6) return [str]; var pre = m6.pre; var post = m6.post.length ? expand2(m6.post, false) : [""]; if (/\$$/.test(m6.pre)) { for (var k5 = 0; k5 < post.length; k5++) { var expansion = pre + "{" + m6.body + "}" + post[k5]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m6.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m6.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m6.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { if (m6.post.match(/,.*\}/)) { str = m6.pre + "{" + m6.body + escClose + m6.post; return expand2(str); } return [str]; } var n5; if (isSequence) { n5 = m6.body.split(/\.\./); } else { n5 = parseCommaParts(m6.body); if (n5.length === 1) { n5 = expand2(n5[0], false).map(embrace); if (n5.length === 1) { return post.map(function(p5) { return m6.pre + n5[0] + p5; }); } } } var N; if (isSequence) { var x5 = numeric(n5[0]); var y2 = numeric(n5[1]); var width = Math.max(n5[0].length, n5[1].length); var incr = n5.length == 3 ? Math.abs(numeric(n5[2])) : 1; var test = lte; var reverse = y2 < x5; if (reverse) { incr *= -1; test = gte; } var pad = n5.some(isPadded); N = []; for (var i6 = x5; test(i6, y2); i6 += incr) { var c5; if (isAlphaSequence) { c5 = String.fromCharCode(i6); if (c5 === "\\") c5 = ""; } else { c5 = String(i6); if (pad) { var need = width - c5.length; if (need > 0) { var z2 = new Array(need + 1).join("0"); if (i6 < 0) c5 = "-" + z2 + c5.slice(1); else c5 = z2 + c5; } } } N.push(c5); } } else { N = []; for (var j5 = 0; j5 < n5.length; j5++) { N.push.apply(N, expand2(n5[j5], false)); } } for (var j5 = 0; j5 < N.length; j5++) { for (var k5 = 0; k5 < post.length; k5++) { var expansion = pre + N[j5] + post[k5]; 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 = (p5, pattern, options = {}) => { assertValidPattern2(pattern); if (!options.nocomment && pattern.charAt(0) === "#") { return false; } return new Minimatch2(pattern, options).match(p5); }; module2.exports = minimatch2; var path3 = require_path(); minimatch2.sep = path3.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 = (s6) => s6.split("").reduce((set, c5) => { set[c5] = true; return set; }, {}); var reSpecials2 = charSet2("().*{}+?[]^$\\!"); var addPatternStartSet2 = charSet2("[.("); var slashSplit = /\/+/; minimatch2.filter = (pattern, options = {}) => (p5, i6, list) => minimatch2(p5, pattern, options); var ext2 = (a5, b5 = {}) => { const t6 = {}; Object.keys(a5).forEach((k5) => t6[k5] = a5[k5]); Object.keys(b5).forEach((k5) => t6[k5] = b5[k5]); return t6; }; minimatch2.defaults = (def) => { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch2; } const orig = minimatch2; const m6 = (p5, pattern, options) => orig(p5, pattern, ext2(def, options)); m6.Minimatch = class Minimatch extends orig.Minimatch { constructor(pattern, options) { super(pattern, ext2(def, options)); } }; m6.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch; m6.filter = (pattern, options) => orig.filter(pattern, ext2(def, options)); m6.defaults = (options) => orig.defaults(ext2(def, options)); m6.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options)); m6.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options)); m6.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options)); return m6; }; 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((f7) => mm.match(f7)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; var globUnescape2 = (s6) => s6.replace(/\\(.)/g, "$1"); var charUnescape = (s6) => s6.replace(/\\([^-\]])/g, "$1"); var regExpEscape2 = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); var braExpEscape = (s6) => s6.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((s6) => s6.split(slashSplit)); this.debug(this.pattern, set); set = set.map((s6, si, set2) => s6.map(this.parse, this)); this.debug(this.pattern, set); set = set.filter((s6) => s6.indexOf(false) === -1); this.debug(this.pattern, set); this.set = set; } parseNegate() { if (this.options.nonegate) return; const pattern = this.pattern; let negate2 = false; let negateOffset = 0; for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) { negate2 = !negate2; negateOffset++; } if (negateOffset) this.pattern = pattern.slice(negateOffset); this.negate = negate2; } // 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 p5 = pattern[pi]; var f7 = file[fi]; this.debug(pattern, p5, f7); if (p5 === false) return false; if (p5 === GLOBSTAR2) { this.debug("GLOBSTAR", [pattern, p5, f7]); 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 p5 === "string") { hit = f7 === p5; this.debug("string match", p5, f7, hit); } else { hit = f7.match(p5); this.debug("pattern match", p5, f7, 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 = (p5) => p5.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 i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) { this.debug("%s %s %s %j", pattern, i6, re, c5); if (escaping) { if (c5 === "/") { return false; } if (reSpecials2[c5]) { re += "\\"; } re += c5; escaping = false; continue; } switch (c5) { /* istanbul ignore next */ case "/": { return false; } case "\\": if (inClass && pattern.charAt(i6 + 1) === "-") { re += c5; continue; } clearStateChar(); escaping = true; continue; // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": this.debug("%s %s %s %j <-- stateChar", pattern, i6, re, c5); if (inClass) { this.debug(" in class"); if (c5 === "!" && i6 === classStart + 1) c5 = "^"; re += c5; continue; } this.debug("call clearStateChar %j", stateChar); clearStateChar(); stateChar = c5; if (options.noext) clearStateChar(); continue; case "(": { if (inClass) { re += "("; continue; } if (!stateChar) { re += "\\("; continue; } const plEntry = { type: stateChar, start: i6 - 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(i6 + 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(i6 + 1)); } continue; } // these are mostly the same in regexp and glob case "[": clearStateChar(); if (inClass) { re += "\\" + c5; continue; } inClass = true; classStart = i6; reClassStart = re.length; re += c5; continue; case "]": if (i6 === classStart + 1 || !inClass) { re += "\\" + c5; continue; } cs = pattern.substring(classStart + 1, i6); try { RegExp("[" + braExpEscape(charUnescape(cs)) + "]"); re += c5; } catch (er) { re = re.substring(0, reClassStart) + "(?:$.)"; } hasMagic = true; inClass = false; continue; default: clearStateChar(); if (reSpecials2[c5] && !(c5 === "^" && inClass)) { re += "\\"; } re += c5; break; } } if (inClass) { cs = pattern.slice(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substring(0, reClassStart) + "\\[" + sp[0]; hasMagic = hasMagic || sp[1]; } for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug("setting tail", re, pl); tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => { if (!$2) { $2 = "\\"; } return $1 + $1 + $2 + "|"; }); this.debug("tail=%j\n %s", tail, tail, pl, re); const t6 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t6 + "\\(" + tail; } clearStateChar(); if (escaping) { re += "\\\\"; } const addPatternStart = addPatternStartSet2[re.charAt(0)]; for (let n5 = negativeLists.length - 1; n5 > -1; n5--) { const nl = negativeLists[n5]; 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 i6 = 0; i6 < openParensBefore; i6++) { 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( (p5) => typeof p5 === "string" ? regExpEscape2(p5) : p5 === GLOBSTAR2 ? GLOBSTAR2 : p5._src ).reduce((set2, p5) => { if (!(set2[set2.length - 1] === GLOBSTAR2 && p5 === GLOBSTAR2)) { set2.push(p5); } return set2; }, []); pattern.forEach((p5, i6) => { if (p5 !== GLOBSTAR2 || pattern[i6 - 1] === GLOBSTAR2) { return; } if (i6 === 0) { if (pattern.length > 1) { pattern[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i6 + 1]; } else { pattern[i6] = twoStar; } } else if (i6 === pattern.length - 1) { pattern[i6 - 1] += "(?:\\/|" + twoStar + ")?"; } else { pattern[i6 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i6 + 1]; pattern[i6 + 1] = GLOBSTAR2; } }); return pattern.filter((p5) => p5 !== 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(f7, partial = this.partial) { this.debug("match", f7, this.pattern); if (this.comment) return false; if (this.empty) return f7 === ""; if (f7 === "/" && partial) return true; const options = this.options; if (path3.sep !== "/") { f7 = f7.split(path3.sep).join("/"); } f7 = f7.split(slashSplit); this.debug(this.pattern, "split", f7); const set = this.set; this.debug(this.pattern, "set", set); let filename; for (let i6 = f7.length - 1; i6 >= 0; i6--) { filename = f7[i6]; if (filename) break; } for (let i6 = 0; i6 < set.length; i6++) { const pattern = set[i6]; let file = f7; 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 (e6) { 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 fs5 = require("fs"); var path3 = require("path"); var minimatch2 = require_minimatch(); var isAbsolute = require("path").isAbsolute; var Minimatch2 = minimatch2.Minimatch; function alphasort(a5, b5) { return a5.localeCompare(b5, "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 || fs5; 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 = path3.resolve(cwd); else { self2.cwd = path3.resolve(options.cwd); self2.changedCwd = self2.cwd !== cwd; } self2.root = options.root || path3.resolve(self2.cwd, "/"); self2.root = path3.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 i6 = 0, l5 = self2.matches.length; i6 < l5; i6++) { var matches = self2.matches[i6]; if (!matches || Object.keys(matches).length === 0) { if (self2.nonull) { var literal = self2.minimatch.globSet[i6]; if (nou) all.push(literal); else all[literal] = true; } } else { var m6 = Object.keys(matches); if (nou) all.push.apply(all, m6); else m6.forEach(function(m7) { all[m7] = true; }); } } if (!nou) all = Object.keys(all); if (!self2.nosort) all = all.sort(alphasort); if (self2.mark) { for (var i6 = 0; i6 < all.length; i6++) { all[i6] = self2._mark(all[i6]); } if (self2.nodir) { all = all.filter(function(e6) { var notDir = !/\/$/.test(e6); var c5 = self2.cache[e6] || self2.cache[makeAbs(self2, e6)]; if (notDir && c5) notDir = c5 !== "DIR" && !Array.isArray(c5); return notDir; }); } } if (self2.ignore.length) all = all.filter(function(m7) { return !isIgnored(self2, m7); }); self2.found = all; } function mark(self2, p5) { var abs = makeAbs(self2, p5); var c5 = self2.cache[abs]; var m6 = p5; if (c5) { var isDir = c5 === "DIR" || Array.isArray(c5); var slash = p5.slice(-1) === "/"; if (isDir && !slash) m6 += "/"; else if (!isDir && slash) m6 = m6.slice(0, -1); if (m6 !== p5) { var mabs = makeAbs(self2, m6); self2.statCache[mabs] = self2.statCache[abs]; self2.cache[mabs] = self2.cache[abs]; } } return m6; } function makeAbs(self2, f7) { var abs = f7; if (f7.charAt(0) === "/") { abs = path3.join(self2.root, f7); } else if (isAbsolute(f7) || f7 === "") { abs = f7; } else if (self2.changedCwd) { abs = path3.resolve(self2.cwd, f7); } else { abs = path3.resolve(f7); } if (process.platform === "win32") abs = abs.replace(/\\/g, "/"); return abs; } function isIgnored(self2, path4) { if (!self2.ignore.length) return false; return self2.ignore.some(function(item) { return item.matcher.match(path4) || !!(item.gmatcher && item.gmatcher.match(path4)); }); } function childrenIgnored(self2, path4) { if (!self2.ignore.length) return false; return self2.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path4)); }); } } }); // ../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 path3 = 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 n5 = this.minimatch.set.length; this.matches = new Array(n5); for (var i6 = 0; i6 < n5; i6++) { this._process(this.minimatch.set[i6], i6, false); } this._finish(); } GlobSync.prototype._finish = function() { assert.ok(this instanceof GlobSync); if (this.realpath) { var self2 = this; this.matches.forEach(function(matchset, index6) { var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null); for (var p5 in matchset) { try { p5 = self2._makeAbs(p5); var real = rp.realpathSync(p5, self2.realpathCache); set[real] = true; } catch (er) { if (er.syscall === "stat") set[self2._makeAbs(p5)] = true; else throw er; } } }); } common.finish(this); }; GlobSync.prototype._process = function(pattern, index6, inGlobStar) { assert.ok(this instanceof GlobSync); var n5 = 0; while (typeof pattern[n5] === "string") { n5++; } var prefix2; switch (n5) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join("/"), index6); return; case 0: prefix2 = null; break; default: prefix2 = pattern.slice(0, n5).join("/"); break; } var remain = pattern.slice(n5); var read; if (prefix2 === null) read = "."; else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) { return typeof p5 === "string" ? p5 : "[*]"; }).join("/"))) { if (!prefix2 || !isAbsolute(prefix2)) prefix2 = "/" + prefix2; read = prefix2; } else read = prefix2; var abs = this._makeAbs(read); if (childrenIgnored(this, read)) return; var isGlobStar = remain[0] === minimatch2.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar); else this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar); }; GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) { var entries = this._readdir(abs, inGlobStar); if (!entries) return; var pn = remain[0]; var negate2 = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === "."; var matchedEntries = []; for (var i6 = 0; i6 < entries.length; i6++) { var e6 = entries[i6]; if (e6.charAt(0) !== "." || dotOk) { var m6; if (negate2 && !prefix2) { m6 = !e6.match(pn); } else { m6 = e6.match(pn); } if (m6) matchedEntries.push(e6); } } var len = matchedEntries.length; if (len === 0) return; if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); for (var i6 = 0; i6 < len; i6++) { var e6 = matchedEntries[i6]; if (prefix2) { if (prefix2.slice(-1) !== "/") e6 = prefix2 + "/" + e6; else e6 = prefix2 + e6; } if (e6.charAt(0) === "/" && !this.nomount) { e6 = path3.join(this.root, e6); } this._emitMatch(index6, e6); } return; } remain.shift(); for (var i6 = 0; i6 < len; i6++) { var e6 = matchedEntries[i6]; var newPattern; if (prefix2) newPattern = [prefix2, e6]; else newPattern = [e6]; this._process(newPattern.concat(remain), index6, inGlobStar); } }; GlobSync.prototype._emitMatch = function(index6, e6) { if (isIgnored(this, e6)) return; var abs = this._makeAbs(e6); if (this.mark) e6 = this._mark(e6); if (this.absolute) { e6 = abs; } if (this.matches[index6][e6]) return; if (this.nodir) { var c5 = this.cache[abs]; if (c5 === "DIR" || Array.isArray(c5)) return; } this.matches[index6][e6] = true; if (this.stat) this._stat(e6); }; GlobSync.prototype._readdirInGlobStar = function(abs) { if (this.follow) return this._readdir(abs, false); var entries; var lstat; var stat2; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er.code === "ENOENT") { return null; } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = "FILE"; else entries = this._readdir(abs, false); return entries; }; GlobSync.prototype._readdir = function(abs, inGlobStar) { var entries; if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs); if (ownProp(this.cache, abs)) { var c5 = this.cache[abs]; if (!c5 || c5 === "FILE") return null; if (Array.isArray(c5)) return c5; } 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 i6 = 0; i6 < entries.length; i6++) { var e6 = entries[i6]; if (abs === "/") e6 = abs + e6; else e6 = abs + "/" + e6; this.cache[e6] = true; } } this.cache[abs] = entries; return entries; }; GlobSync.prototype._readdirError = function(f7, er) { switch (er.code) { case "ENOTSUP": // https://github.com/isaacs/node-glob/issues/205 case "ENOTDIR": var abs = this._makeAbs(f7); this.cache[abs] = "FILE"; if (abs === this.cwdAbs) { var error2 = new Error(er.code + " invalid cwd " + this.cwd); error2.path = this.cwd; error2.code = er.code; throw error2; } break; case "ENOENT": // not terribly unusual case "ELOOP": case "ENAMETOOLONG": case "UNKNOWN": this.cache[this._makeAbs(f7)] = false; break; default: this.cache[this._makeAbs(f7)] = false; if (this.strict) throw er; if (!this.silent) console.error("glob error", er); break; } }; GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) { var entries = this._readdir(abs, inGlobStar); if (!entries) return; var remainWithoutGlobStar = remain.slice(1); var gspref = prefix2 ? [prefix2] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); this._process(noGlobStar, index6, false); var len = entries.length; var isSym = this.symlinks[abs]; if (isSym && inGlobStar) return; for (var i6 = 0; i6 < len; i6++) { var e6 = entries[i6]; if (e6.charAt(0) === "." && !this.dot) continue; var instead = gspref.concat(entries[i6], remainWithoutGlobStar); this._process(instead, index6, true); var below = gspref.concat(entries[i6], remain); this._process(below, index6, true); } }; GlobSync.prototype._processSimple = function(prefix2, index6) { var exists = this._stat(prefix2); if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); if (!exists) return; if (prefix2 && isAbsolute(prefix2) && !this.nomount) { var trail = /[\/\\]$/.test(prefix2); if (prefix2.charAt(0) === "/") { prefix2 = path3.join(this.root, prefix2); } else { prefix2 = path3.resolve(this.root, prefix2); if (trail) prefix2 += "/"; } } if (process.platform === "win32") prefix2 = prefix2.replace(/\\/g, "/"); this._emitMatch(index6, prefix2); }; GlobSync.prototype._stat = function(f7) { var abs = this._makeAbs(f7); var needDir = f7.slice(-1) === "/"; if (f7.length > this.maxLength) return false; if (!this.stat && ownProp(this.cache, abs)) { var c5 = this.cache[abs]; if (Array.isArray(c5)) c5 = "DIR"; if (!needDir || c5 === "DIR") return c5; if (needDir && c5 === "FILE") return false; } var exists; var stat2 = this.statCache[abs]; if (!stat2) { var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) { this.statCache[abs] = false; return false; } } if (lstat && lstat.isSymbolicLink()) { try { stat2 = this.fs.statSync(abs); } catch (er) { stat2 = lstat; } } else { stat2 = lstat; } } this.statCache[abs] = stat2; var c5 = true; if (stat2) c5 = stat2.isDirectory() ? "DIR" : "FILE"; this.cache[abs] = this.cache[abs] || c5; if (needDir && c5 === "FILE") return false; return c5; }; GlobSync.prototype._mark = function(p5) { return common.mark(this, p5); }; GlobSync.prototype._makeAbs = function(f7) { return common.makeAbs(this, f7); }; } }); // ../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(k5) { wrapper[k5] = fn[k5]; }); return wrapper; function wrapper() { var args = new Array(arguments.length); for (var i6 = 0; i6 < args.length; i6++) { args[i6] = arguments[i6]; } var ret = fn.apply(this, args); var cb2 = args[args.length - 1]; if (typeof ret === "function" && ret !== cb2) { Object.keys(cb2).forEach(function(k5) { ret[k5] = cb2[k5]; }); } 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 f7 = function() { if (f7.called) return f7.value; f7.called = true; return f7.value = fn.apply(this, arguments); }; f7.called = false; return f7; } function onceStrict(fn) { var f7 = function() { if (f7.called) throw new Error(f7.onceError); f7.called = true; return f7.value = fn.apply(this, arguments); }; var name = fn.name || "Function wrapped with `once`"; f7.onceError = name + " shouldn't be called more than once"; f7.called = false; return f7; } } }); // ../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 i6 = 0; i6 < len; i6++) { cbs[i6].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 i6 = 0; i6 < length; i6++) array2[i6] = args[i6]; 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 path3 = 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 i6 = keys.length; while (i6--) { origin[keys[i6]] = add[keys[i6]]; } return origin; } glob2.hasMagic = function(pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g5 = new Glob(pattern, options); var set = g5.minimatch.set; if (!pattern) return false; if (set.length > 1) return true; for (var j5 = 0; j5 < set[0].length; j5++) { if (typeof set[0][j5] !== "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 n5 = this.minimatch.set.length; this.matches = new Array(n5); 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 (n5 === 0) return done(); var sync2 = true; for (var i6 = 0; i6 < n5; i6++) { this._process(this.minimatch.set[i6], i6, 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 n5 = this.matches.length; if (n5 === 0) return this._finish(); var self2 = this; for (var i6 = 0; i6 < this.matches.length; i6++) this._realpathSet(i6, next); function next() { if (--n5 === 0) self2._finish(); } }; Glob.prototype._realpathSet = function(index6, cb) { var matchset = this.matches[index6]; if (!matchset) return cb(); var found = Object.keys(matchset); var self2 = this; var n5 = found.length; if (n5 === 0) return cb(); var set = this.matches[index6] = /* @__PURE__ */ Object.create(null); found.forEach(function(p5, i6) { p5 = self2._makeAbs(p5); rp.realpath(p5, self2.realpathCache, function(er, real) { if (!er) set[real] = true; else if (er.syscall === "stat") set[p5] = true; else self2.emit("error", er); if (--n5 === 0) { self2.matches[index6] = set; cb(); } }); }); }; Glob.prototype._mark = function(p5) { return common.mark(this, p5); }; Glob.prototype._makeAbs = function(f7) { return common.makeAbs(this, f7); }; Glob.prototype.abort = function() { this.aborted = true; this.emit("abort"); }; Glob.prototype.pause = function() { if (!this.paused) { this.paused = true; this.emit("pause"); } }; Glob.prototype.resume = function() { if (this.paused) { this.emit("resume"); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i6 = 0; i6 < eq.length; i6++) { var e6 = eq[i6]; this._emitMatch(e6[0], e6[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i6 = 0; i6 < pq.length; i6++) { var p5 = pq[i6]; this._processing--; this._process(p5[0], p5[1], p5[2], p5[3]); } } } }; Glob.prototype._process = function(pattern, index6, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === "function"); if (this.aborted) return; this._processing++; if (this.paused) { this._processQueue.push([pattern, index6, inGlobStar, cb]); return; } var n5 = 0; while (typeof pattern[n5] === "string") { n5++; } var prefix2; switch (n5) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join("/"), index6, cb); return; case 0: prefix2 = null; break; default: prefix2 = pattern.slice(0, n5).join("/"); break; } var remain = pattern.slice(n5); var read; if (prefix2 === null) read = "."; else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) { return typeof p5 === "string" ? p5 : "[*]"; }).join("/"))) { if (!prefix2 || !isAbsolute(prefix2)) prefix2 = "/" + prefix2; read = prefix2; } else read = prefix2; var abs = this._makeAbs(read); if (childrenIgnored(this, read)) return cb(); var isGlobStar = remain[0] === minimatch2.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb); else this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb); }; Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) { var self2 = this; this._readdir(abs, inGlobStar, function(er, entries) { return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb); }); }; Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) { if (!entries) return cb(); var pn = remain[0]; var negate2 = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === "."; var matchedEntries = []; for (var i6 = 0; i6 < entries.length; i6++) { var e6 = entries[i6]; if (e6.charAt(0) !== "." || dotOk) { var m6; if (negate2 && !prefix2) { m6 = !e6.match(pn); } else { m6 = e6.match(pn); } if (m6) matchedEntries.push(e6); } } var len = matchedEntries.length; if (len === 0) return cb(); if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); for (var i6 = 0; i6 < len; i6++) { var e6 = matchedEntries[i6]; if (prefix2) { if (prefix2 !== "/") e6 = prefix2 + "/" + e6; else e6 = prefix2 + e6; } if (e6.charAt(0) === "/" && !this.nomount) { e6 = path3.join(this.root, e6); } this._emitMatch(index6, e6); } return cb(); } remain.shift(); for (var i6 = 0; i6 < len; i6++) { var e6 = matchedEntries[i6]; var newPattern; if (prefix2) { if (prefix2 !== "/") e6 = prefix2 + "/" + e6; else e6 = prefix2 + e6; } this._process([e6].concat(remain), index6, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function(index6, e6) { if (this.aborted) return; if (isIgnored(this, e6)) return; if (this.paused) { this._emitQueue.push([index6, e6]); return; } var abs = isAbsolute(e6) ? e6 : this._makeAbs(e6); if (this.mark) e6 = this._mark(e6); if (this.absolute) e6 = abs; if (this.matches[index6][e6]) return; if (this.nodir) { var c5 = this.cache[abs]; if (c5 === "DIR" || Array.isArray(c5)) return; } this.matches[index6][e6] = true; var st = this.statCache[abs]; if (st) this.emit("stat", e6, st); this.emit("match", e6); }; 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 c5 = this.cache[abs]; if (!c5 || c5 === "FILE") return cb(); if (Array.isArray(c5)) return cb(null, c5); } 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 i6 = 0; i6 < entries.length; i6++) { var e6 = entries[i6]; if (abs === "/") e6 = abs + e6; else e6 = abs + "/" + e6; this.cache[e6] = true; } } this.cache[abs] = entries; return cb(null, entries); }; Glob.prototype._readdirError = function(f7, er, cb) { if (this.aborted) return; switch (er.code) { case "ENOTSUP": // https://github.com/isaacs/node-glob/issues/205 case "ENOTDIR": var abs = this._makeAbs(f7); this.cache[abs] = "FILE"; if (abs === this.cwdAbs) { var error2 = new Error(er.code + " invalid cwd " + this.cwd); error2.path = this.cwd; error2.code = er.code; this.emit("error", error2); this.abort(); } break; case "ENOENT": // not terribly unusual case "ELOOP": case "ENAMETOOLONG": case "UNKNOWN": this.cache[this._makeAbs(f7)] = false; break; default: this.cache[this._makeAbs(f7)] = false; if (this.strict) { this.emit("error", er); this.abort(); } if (!this.silent) console.error("glob error", er); break; } return cb(); }; Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) { var self2 = this; this._readdir(abs, inGlobStar, function(er, entries) { self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) { if (!entries) return cb(); var remainWithoutGlobStar = remain.slice(1); var gspref = prefix2 ? [prefix2] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); this._process(noGlobStar, index6, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; if (isSym && inGlobStar) return cb(); for (var i6 = 0; i6 < len; i6++) { var e6 = entries[i6]; if (e6.charAt(0) === "." && !this.dot) continue; var instead = gspref.concat(entries[i6], remainWithoutGlobStar); this._process(instead, index6, true, cb); var below = gspref.concat(entries[i6], remain); this._process(below, index6, true, cb); } cb(); }; Glob.prototype._processSimple = function(prefix2, index6, cb) { var self2 = this; this._stat(prefix2, function(er, exists) { self2._processSimple2(prefix2, index6, er, exists, cb); }); }; Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); if (!exists) return cb(); if (prefix2 && isAbsolute(prefix2) && !this.nomount) { var trail = /[\/\\]$/.test(prefix2); if (prefix2.charAt(0) === "/") { prefix2 = path3.join(this.root, prefix2); } else { prefix2 = path3.resolve(this.root, prefix2); if (trail) prefix2 += "/"; } } if (process.platform === "win32") prefix2 = prefix2.replace(/\\/g, "/"); this._emitMatch(index6, prefix2); cb(); }; Glob.prototype._stat = function(f7, cb) { var abs = this._makeAbs(f7); var needDir = f7.slice(-1) === "/"; if (f7.length > this.maxLength) return cb(); if (!this.stat && ownProp(this.cache, abs)) { var c5 = this.cache[abs]; if (Array.isArray(c5)) c5 = "DIR"; if (!needDir || c5 === "DIR") return cb(null, c5); if (needDir && c5 === "FILE") return cb(); } var exists; var stat2 = this.statCache[abs]; if (stat2 !== void 0) { if (stat2 === false) return cb(null, stat2); else { var type = stat2.isDirectory() ? "DIR" : "FILE"; if (needDir && type === "FILE") return cb(); else return cb(null, type, stat2); } } var self2 = this; var statcb = inflight("stat\0" + abs, lstatcb_); if (statcb) self2.fs.lstat(abs, statcb); function lstatcb_(er, lstat) { if (lstat && lstat.isSymbolicLink()) { return self2.fs.stat(abs, function(er2, stat3) { if (er2) self2._stat2(f7, abs, null, lstat, cb); else self2._stat2(f7, abs, er2, stat3, cb); }); } else { self2._stat2(f7, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function(f7, abs, er, stat2, cb) { if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) { this.statCache[abs] = false; return cb(); } var needDir = f7.slice(-1) === "/"; this.statCache[abs] = stat2; if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory()) return cb(null, false, stat2); var c5 = true; if (stat2) c5 = stat2.isDirectory() ? "DIR" : "FILE"; this.cache[abs] = this.cache[abs] || c5; if (needDir && c5 === "FILE") return cb(); return cb(null, c5, stat2); }; } }); // ../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(x5, y2) { if (!y2) return `${CSI}${x5 + 1}G`; return `${CSI}${y2 + 1};${x5 + 1}H`; }, move(x5, y2) { let ret = ""; if (x5 < 0) ret += `${CSI}${-x5}D`; else if (x5 > 0) ret += `${CSI}${x5}C`; if (y2 < 0) ret += `${CSI}${-y2}A`; else if (y2 > 0) ret += `${CSI}${y2}B`; return ret; }, up: (count = 1) => `${CSI}${count}A`, down: (count = 1) => `${CSI}${count}B`, forward: (count = 1) => `${CSI}${count}C`, backward: (count = 1) => `${CSI}${count}D`, nextLine: (count = 1) => `${CSI}E`.repeat(count), prevLine: (count = 1) => `${CSI}F`.repeat(count), left: `${CSI}G`, hide: `${CSI}?25l`, show: `${CSI}?25h`, save: `${ESC}7`, restore: `${ESC}8` }; var scroll = { up: (count = 1) => `${CSI}S`.repeat(count), down: (count = 1) => `${CSI}T`.repeat(count) }; var erase = { screen: `${CSI}2J`, up: (count = 1) => `${CSI}1J`.repeat(count), down: (count = 1) => `${CSI}J`.repeat(count), line: `${CSI}2K`, lineEnd: `${CSI}K`, lineStart: `${CSI}1K`, lines(count) { let clear = ""; for (let i6 = 0; i6 < count; i6++) clear += this.line + (i6 < count - 1 ? cursor.up() : ""); if (count) clear += cursor.left; return clear; } }; module2.exports = { cursor, scroll, erase, beep }; } }); // ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js var require_utils = __commonJS({ "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.clear = void 0; var sisteransi_1 = require_src(); var strip = (str) => { const pattern = [ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))" ].join("|"); const RGX = new RegExp(pattern, "g"); return typeof str === "string" ? str.replace(RGX, "") : str; }; var stringWidth = (str) => [...strip(str)].length; var clear = function(prompt, perLine) { if (!perLine) return sisteransi_1.erase.line + sisteransi_1.cursor.to(0); let rows = 0; const lines = prompt.split(/\r?\n/); for (let line of lines) { rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine); } return sisteransi_1.erase.lines(rows); }; exports2.clear = clear; } }); // ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js var require_lodash = __commonJS({ "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) { "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(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { lastInvokeTime = time; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall; return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush2() { return timerId === void 0 ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush2; 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 (e6) { reject(e6); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e6) { reject(e6); } } 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(view5, stdin, stdout, closable) { this.view = view5; this.stdin = stdin; this.stdout = stdout; this.closable = closable; this.text = ""; this.status = "idle"; if (this.stdin.isTTY) this.stdin.setRawMode(true); const keypress = (str, key) => { if (key.name === "c" && key.ctrl === true) { this.requestLayout(); this.view.detach(this); this.tearDown(keypress); if (terminateHandler) { terminateHandler(this.stdin, this.stdout); return; } this.stdout.write(` ^C `); process.exit(1); } if (key.name === "escape") { this.status = "aborted"; this.requestLayout(); this.view.detach(this); this.tearDown(keypress); this.resolve({ status: "aborted", data: void 0 }); return; } if (key.name === "return") { this.status = "submitted"; this.requestLayout(); this.view.detach(this); this.tearDown(keypress); this.resolve({ status: "submitted", data: this.view.result() }); return; } view5.input(str, key); }; this.stdin.on("keypress", keypress); this.view.attach(this); const { resolve, 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(state2) { if (state2 === "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(view5, stdout) { this.view = view5; 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 render7(view5) { const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)(); if (view5 instanceof Prompt3) { const terminal = new Terminal(view5, stdin, stdout, closable); terminal.requestLayout(); return terminal.result(); } stdout.write(`${view5} `); closable.close(); return; } exports2.render = render7; function renderWithTask5(view5, task) { return __awaiter(this, void 0, void 0, function* () { const terminal = new TaskTerminal(view5, process.stdout); terminal.requestLayout(); const result = yield task; terminal.clear(); return result; }); } exports2.renderWithTask = renderWithTask5; var terminateHandler; function onTerminate(callback) { terminateHandler = callback; } exports2.onTerminate = onTerminate; } }); // src/global.ts function assertUnreachable(x5) { throw new Error("Didn't expect to get here"); } var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries; var init_global = __esm({ "src/global.ts"() { "use strict"; originUUID = "00000000-0000-0000-0000-000000000000"; snapshotVersion = "7"; mapValues = (obj, map2) => { const result = Object.keys(obj).reduce(function(result2, key) { result2[key] = map2(obj[key]); return result2; }, {}); return result; }; mapKeys = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const newKey = map2(key, val2); return [newKey, val2]; }) ); return result; }; mapEntries = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const [newKey, newVal] = map2(key, val2); return [newKey, newVal]; }) ); return result; }; customMapEntries = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const [newKey, newVal] = map2(key, val2); return [newKey, newVal]; }) ); return result; }; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js var util, objectUtil, ZodParsedType, getParsedType; var init_util = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() { "use strict"; (function(util2) { util2.assertEqual = (_3) => { }; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k5) => typeof obj[obj[k5]] !== "number"); const filtered = {}; for (const k5 of validKeys) { filtered[k5] = obj[k5]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e6) { return obj[e6]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; function joinValues(array2, separator = " | ") { return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_3, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); getParsedType = (data) => { const t6 = typeof data; switch (t6) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js var ZodIssueCode, quotelessJson, ZodError; var init_ZodError = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() { "use strict"; init_util(); ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; ZodError = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error2) => { for (const issue of error2.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i6 = 0; while (i6 < issue.path.length) { const el = issue.path[i6]; const terminal = i6 === 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]; i6++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error2 = new ZodError(issues); return error2; }; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js var errorMap, en_default; var init_en = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js"() { "use strict"; init_ZodError(); init_util(); errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; en_default = errorMap; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js function setErrorMap(map2) { overrideErrorMap = map2; } function getErrorMap() { return overrideErrorMap; } var overrideErrorMap; var init_errors = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() { "use strict"; init_en(); overrideErrorMap = en_default; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default ? void 0 : en_default // then global default map ].filter((x5) => !!x5) }); ctx.common.issues.push(issue); } var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync; var init_parseUtil = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() { "use strict"; init_errors(); init_en(); makeIssue = (params) => { const { data, path: path3, errorMaps, issueData } = params; const fullPath = [...path3, ...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((m6) => !!m6).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; EMPTY_PATH = []; ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s6 of results) { if (s6.status === "aborted") return INVALID; if (s6.status === "dirty") status.dirty(); arrayValue.push(s6.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 = (x5) => x5.status === "aborted"; isDirty = (x5) => x5.status === "dirty"; isValid = (x5) => x5.status === "valid"; isAsync = (x5) => typeof Promise !== "undefined" && x5 instanceof Promise; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js var init_typeAliases = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() { "use strict"; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js var errorUtil; var init_errorUtil = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() { "use strict"; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt, alg) { if (!jwtRegex.test(jwt)) return false; try { const [header] = jwt.split("."); const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version) { if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { return true; } return false; } function floatSafeRemainder(val2, step) { const valDecCount = (val2.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } function deepPartialify(schema6) { if (schema6 instanceof ZodObject) { const newShape = {}; for (const key in schema6.shape) { const fieldSchema = schema6.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema6._def, shape: () => newShape }); } else if (schema6 instanceof ZodArray) { return new ZodArray({ ...schema6._def, type: deepPartialify(schema6.element) }); } else if (schema6 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema6.unwrap())); } else if (schema6 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema6.unwrap())); } else if (schema6 instanceof ZodTuple) { return ZodTuple.create(schema6.items.map((item) => deepPartialify(item))); } else { return schema6; } } function mergeValues(a5, b5) { const aType = getParsedType(a5); const bType = getParsedType(b5); if (a5 === b5) { return { valid: true, data: a5 }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b5); const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a5, ...b5 }; for (const key of sharedKeys) { const sharedValue = mergeValues(a5[key], b5[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 (a5.length !== b5.length) { return { valid: false }; } const newArray = []; for (let index6 = 0; index6 < a5.length; index6++) { const itemA = a5[index6]; const itemB = b5[index6]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b5) { return { valid: true, data: a5 }; } else { return { valid: false }; } } function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } function cleanParams(params, data) { const p5 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const p22 = typeof p5 === "string" ? { message: p5 } : p5; return p22; } function custom(check, _params2 = {}, fatal) { if (check) return ZodAny.create().superRefine((data, ctx) => { const r6 = check(data); if (r6 instanceof Promise) { return r6.then((r7) => { if (!r7) { const params = cleanParams(_params2, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } }); } if (!r6) { const params = cleanParams(_params2, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } return; }); return ZodAny.create(); } var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER; var init_types = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() { "use strict"; init_ZodError(); init_errors(); init_errorUtil(); init_parseUtil(); init_util(); ParseInputLazyPath = class { constructor(parent, value, path3, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path3; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error2 = new ZodError(ctx.common.issues); this._error = error2; return this._error; } }; } }; ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: params?.async ?? false, contextualErrorMap: params?.errorMap }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err2) { if (err2?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params?.errorMap, async: true }, path: 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 = (val2) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val2); } else { return message; } }; return this._refinement((val2, ctx) => { const result = check(val2); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val2) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val2, ctx) => { if (!check(val2)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; cuidRegex = /^c[^\s-]{8,}$/i; cuid2Regex = /^[0-9a-z]+$/; ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; nanoidRegex = /^[a-z0-9_-]{21}$/i; jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; dateRegex = new RegExp(`^${dateRegexSource}$`); ZodString = class _ZodString extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const 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 { 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 === "jwt") { if (!isValidJWT(input.data, check.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cidr") { if (!isValidCidr(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", 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 if (check.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", 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) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof options?.precision === "undefined" ? null : options?.precision, offset: options?.offset ?? false, local: options?.local ?? false, ...errorUtil.errToObj(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?.precision === "undefined" ? null : options?.precision, ...errorUtil.errToObj(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?.position, ...errorUtil.errToObj(options?.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString.create = (params) => { return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; ZodNumber = class _ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const 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 min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null; let min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params) }); }; ZodBigInt = class _ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { try { input.data = BigInt(input.data); } catch { return this._getInvalidInput(input); } } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const 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 }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(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 min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt.create = (params) => { return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; ZodDate = class _ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const 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 min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: params?.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, i6) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i6)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i6) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i6)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema6, params) => { return new ZodArray({ type: schema6, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // <Def extends ZodObjectDef>(def: Def) => // <Augmentation extends ZodRawShape>( // augmentation: Augmentation // ): ZodObject< // extendShape<ReturnType<Def["shape"]>, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema6) { return this.augment({ [key]: schema6 }); } // merge<Incoming extends AnyZodObject>( // merging: Incoming // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { // ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index6) { return new _ZodObject({ ...this._def, catchall: index6 }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types3, params) => { return new ZodUnion({ options: types3, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [void 0]; } else if (type instanceof ZodNull) { return [null]; } else if (type instanceof ZodOptional) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; ZodTuple = class _ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema6 = this._def.items[itemIndex] || this._def.rest; if (!schema6) return null; return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x5) => !!x5); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; ZodRecord = class _ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index6) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; ZodSet = class _ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i6) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i6))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; ZodFunction = class _ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error2) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error2 } }); } function makeReturnsIssue(returns, error2) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), 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((e6) => { error2.addIssue(makeArgsIssue(args, e6)); throw error2; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e6) => { error2.addIssue(makeReturnsIssue(result, e6)); throw error2; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new _ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new _ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; ZodEnum = class _ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } get Values() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } get Enum() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum.create = createZodEnum; ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise.create = (schema6, params) => { return new ZodPromise({ type: schema6, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema6, effect, params) => { return new ZodEffects({ schema: schema6, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema6, params) => { return new ZodEffects({ schema: schema6, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; ZodNullable = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; ZodNaN = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; BRAND = Symbol("zod_brand"); ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; ZodPipeline = class _ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a5, b5) { return new _ZodPipeline({ in: a5, out: b5, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } }; ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; late = { object: ZodObject.lazycreate }; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); stringType = ZodString.create; numberType = ZodNumber.create; nanType = ZodNaN.create; bigIntType = ZodBigInt.create; booleanType = ZodBoolean.create; dateType = ZodDate.create; symbolType = ZodSymbol.create; undefinedType = ZodUndefined.create; nullType = ZodNull.create; anyType = ZodAny.create; unknownType = ZodUnknown.create; neverType = ZodNever.create; voidType = ZodVoid.create; arrayType = ZodArray.create; objectType = ZodObject.create; strictObjectType = ZodObject.strictCreate; unionType = ZodUnion.create; discriminatedUnionType = ZodDiscriminatedUnion.create; intersectionType = ZodIntersection.create; tupleType = ZodTuple.create; recordType = ZodRecord.create; mapType = ZodMap.create; setType = ZodSet.create; functionType = ZodFunction.create; lazyType = ZodLazy.create; literalType = ZodLiteral.create; enumType = ZodEnum.create; nativeEnumType = ZodNativeEnum.create; promiseType = ZodPromise.create; effectsType = ZodEffects.create; optionalType = ZodOptional.create; nullableType = ZodNullable.create; preprocessType = ZodEffects.createWithPreprocess; pipelineType = ZodPipeline.create; ostring = () => stringType().optional(); onumber = () => numberType().optional(); oboolean = () => booleanType().optional(); coerce = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; NEVER = INVALID; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js var external_exports = {}; __export(external_exports, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBigInt: () => ZodBigInt, ZodBoolean: () => ZodBoolean, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSchema: () => ZodType, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodSymbol: () => ZodSymbol, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce, custom: () => custom, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap, getParsedType: () => getParsedType, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); var init_external = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() { "use strict"; init_errors(); init_parseUtil(); init_typeAliases(); init_util(); init_types(); init_ZodError(); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js var init_v3 = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() { "use strict"; init_external(); init_external(); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js var init_esm = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() { "use strict"; init_v3(); init_v3(); } }); // src/serializer/gelSchema.ts var enumSchema, enumSchemaV1, indexColumn, index, fk, sequenceSchema, roleSchema, sequenceSquashed, column, checkConstraint, columnSquashed, compositePK, uniqueConstraint, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view, table, schemaHash, kitInternals, gelSchemaExternal, gelSchemaInternal, tableSquashed, gelSchemaSquashed, gelSchema, dryGel; var init_gelSchema = __esm({ "src/serializer/gelSchema.ts"() { "use strict"; init_global(); init_esm(); enumSchema = objectType({ name: stringType(), schema: stringType(), values: stringType().array() }).strict(); enumSchemaV1 = objectType({ name: stringType(), values: recordType(stringType(), stringType()) }).strict(); indexColumn = objectType({ expression: stringType(), isExpression: booleanType(), asc: booleanType(), nulls: stringType().optional(), opclass: stringType().optional() }); index = 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(); fk = 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(); column = 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(); checkConstraint = 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(); compositePK = objectType({ name: stringType(), columns: stringType().array() }).strict(); uniqueConstraint = 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(); view = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column), definition: stringType().optional(), materialized: booleanType(), with: mergedViewWithOption.optional(), isExisting: booleanType(), withNoData: booleanType().optional(), using: stringType().optional(), tablespace: stringType().optional() }).strict(); table = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column), indexes: recordType(stringType(), index), foreignKeys: recordType(stringType(), fk), compositePrimaryKeys: recordType(stringType(), compositePK), uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}), policies: recordType(stringType(), policy).default({}), checkConstraints: recordType(stringType(), checkConstraint).default({}), isRLSEnabled: booleanType().default(false) }).strict(); schemaHash = objectType({ id: stringType(), prevId: stringType() }); kitInternals = objectType({ tables: recordType( stringType(), objectType({ columns: recordType( stringType(), objectType({ isArray: booleanType().optional(), dimensions: numberType().optional(), rawType: stringType().optional(), isDefaultAnExpression: booleanType().optional() }).optional() ) }).optional() ) }).optional(); gelSchemaExternal = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: arrayType(table), enums: arrayType(enumSchemaV1), schemas: arrayType(objectType({ name: stringType() })), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }) }).strict(); gelSchemaInternal = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: recordType(stringType(), table), enums: recordType(stringType(), enumSchema), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view).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: kitInternals }).strict(); tableSquashed = 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(); gelSchemaSquashed = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: recordType(stringType(), tableSquashed), enums: recordType(stringType(), enumSchema), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view), sequences: recordType(stringType(), sequenceSquashed), roles: recordType(stringType(), roleSchema).default({}), policies: recordType(stringType(), policySquashed).default({}) }).strict(); gelSchema = gelSchemaInternal.merge(schemaHash); dryGel = gelSchema.parse({ version: "1", dialect: "gel", id: originUUID, prevId: "", tables: {}, enums: {}, schemas: {}, policies: {}, roles: {}, sequences: {}, _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // src/serializer/mysqlSchema.ts var index2, fk2, column2, tableV3, compositePK2, uniqueConstraint2, checkConstraint2, tableV4, table2, viewMeta, view2, kitInternals2, dialect, schemaHash2, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed2, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql; var init_mysqlSchema = __esm({ "src/serializer/mysqlSchema.ts"() { "use strict"; init_esm(); init_global(); index2 = 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(); fk2 = objectType({ name: stringType(), tableFrom: stringType(), columnsFrom: stringType().array(), tableTo: stringType(), columnsTo: stringType().array(), onUpdate: stringType().optional(), onDelete: stringType().optional() }).strict(); column2 = 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(), 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() }).strict(); checkConstraint2 = objectType({ name: stringType(), value: stringType() }).strict(); tableV4 = objectType({ name: stringType(), schema: stringType().optional(), columns: recordType(stringType(), column2), indexes: recordType(stringType(), index2), foreignKeys: recordType(stringType(), fk2) }).strict(); table2 = objectType({ name: stringType(), columns: recordType(stringType(), column2), indexes: recordType(stringType(), index2), foreignKeys: recordType(stringType(), fk2), compositePrimaryKeys: recordType(stringType(), compositePK2), uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}), checkConstraint: recordType(stringType(), checkConstraint2).default({}) }).strict(); viewMeta = objectType({ algorithm: enumType(["undefined", "merge", "temptable"]), sqlSecurity: enumType(["definer", "invoker"]), withCheckOption: enumType(["local", "cascaded"]).optional() }).strict(); view2 = objectType({ name: stringType(), columns: recordType(stringType(), column2), definition: stringType().optional(), isExisting: booleanType() }).strict().merge(viewMeta); kitInternals2 = 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"); schemaHash2 = 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(), table2), schemas: recordType(stringType(), stringType()), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals2 }).strict(); schemaInternal = objectType({ version: literalType("5"), dialect, tables: recordType(stringType(), table2), views: recordType(stringType(), view2).default({}), _meta: objectType({ tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals2 }).strict(); schemaV3 = schemaInternalV3.merge(schemaHash2); schemaV4 = schemaInternalV4.merge(schemaHash2); schemaV5 = schemaInternalV5.merge(schemaHash2); schema = schemaInternal.merge(schemaHash2); tableSquashedV4 = objectType({ name: stringType(), schema: stringType().optional(), columns: recordType(stringType(), column2), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()) }).strict(); tableSquashed2 = objectType({ name: stringType(), columns: recordType(stringType(), column2), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()), uniqueConstraints: recordType(stringType(), stringType()).default({}), checkConstraints: recordType(stringType(), stringType()).default({}) }).strict(); viewSquashed = view2.omit({ algorithm: true, sqlSecurity: true, withCheckOption: true }).extend({ meta: stringType() }); schemaSquashed = objectType({ version: literalType("5"), dialect, tables: recordType(stringType(), tableSquashed2), views: recordType(stringType(), viewSquashed) }).strict(); schemaSquashedV4 = objectType({ version: literalType("4"), dialect, tables: recordType(stringType(), tableSquashedV4), schemas: recordType(stringType(), stringType()) }).strict(); MySqlSquasher = { squashIdx: (idx) => { index2.parse(idx); return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`; }, unsquashIdx: (input) => { const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";"); const destructed = { name, columns: columnsString.split(","), isUnique: isUnique === "true", using: using ? using : void 0, algorithm: algorithm ? algorithm : void 0, lock: lock ? lock : void 0 }; return index2.parse(destructed); }, squashPK: (pk) => { return `${pk.name};${pk.columns.join(",")}`; }, unsquashPK: (pk) => { const splitted = pk.split(";"); return { name: splitted[0], columns: splitted[1].split(",") }; }, squashUnique: (unq) => { return `${unq.name};${unq.columns.join(",")}`; }, unsquashUnique: (unq) => { const [name, columns] = unq.split(";"); return { name, columns: columns.split(",") }; }, squashFK: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = fk2.parse({ name, tableFrom, columnsFrom: columnsFromStr.split(","), tableTo, columnsTo: columnsToStr.split(","), onUpdate, onDelete }); return result; }, squashCheck: (input) => { return `${input.name};${input.value}`; }, unsquashCheck: (input) => { const [name, value] = input.split(";"); return { name, value }; }, squashView: (view5) => { return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`; }, unsquashView: (meta) => { const [algorithm, sqlSecurity, withCheckOption] = meta.split(";"); const toReturn = { algorithm, sqlSecurity, withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0 }; return viewMeta.parse(toReturn); } }; squashMysqlScheme = (json) => { const mappedTables = Object.fromEntries( Object.entries(json.tables).map((it) => { const squashedIndexes = mapValues(it[1].indexes, (index6) => { return MySqlSquasher.squashIdx(index6); }); const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => { return MySqlSquasher.squashFK(fk5); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return MySqlSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return MySqlSquasher.squashUnique(unq); } ); const squashedCheckConstraints = mapValues(it[1].checkConstraint, (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(json.views).map(([key, value]) => { const meta = MySqlSquasher.squashView(value); return [key, { name: value.name, isExisting: value.isExisting, columns: value.columns, definition: value.definition, meta }]; }) ); return { version: "5", dialect: json.dialect, tables: mappedTables, views: mappedViews }; }; mysqlSchema = schema; mysqlSchemaV5 = schemaV5; mysqlSchemaSquashed = schemaSquashed; backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]); dryMySql = mysqlSchema.parse({ version: "5", dialect: "mysql", id: originUUID, prevId: "", tables: {}, schemas: {}, views: {}, _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // src/serializer/pgSchema.ts var indexV2, columnV2, tableV2, enumSchemaV12, enumSchema2, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn2, index3, indexV4, indexV5, indexV6, fk3, sequenceSchema2, roleSchema2, sequenceSquashed2, columnV7, column3, checkConstraint3, columnSquashed2, tableV32, compositePK3, uniqueConstraint3, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view3, tableV42, tableV5, tableV6, tableV7, table3, schemaHash3, kitInternals3, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed3, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg; var init_pgSchema = __esm({ "src/serializer/pgSchema.ts"() { "use strict"; init_global(); init_esm(); indexV2 = objectType({ name: stringType(), columns: recordType( stringType(), objectType({ name: stringType() }) ), isUnique: booleanType() }).strict(); columnV2 = objectType({ name: stringType(), type: stringType(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), references: stringType().optional() }).strict(); tableV2 = objectType({ name: stringType(), columns: recordType(stringType(), columnV2), indexes: recordType(stringType(), indexV2) }).strict(); enumSchemaV12 = objectType({ name: stringType(), values: recordType(stringType(), stringType()) }).strict(); enumSchema2 = objectType({ name: stringType(), schema: stringType(), values: stringType().array() }).strict(); pgSchemaV2 = objectType({ version: literalType("2"), tables: recordType(stringType(), tableV2), enums: recordType(stringType(), enumSchemaV12) }).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(), enumSchemaV12) }).strict(); indexColumn2 = objectType({ expression: stringType(), isExpression: booleanType(), asc: booleanType(), nulls: stringType().optional(), opclass: stringType().optional() }); index3 = objectType({ name: stringType(), columns: indexColumn2.array(), isUnique: booleanType(), with: recordType(stringType(), anyType()).optional(), method: stringType().default("btree"), where: stringType().optional(), concurrently: booleanType().default(false) }).strict(); 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(); fk3 = objectType({ name: stringType(), tableFrom: stringType(), columnsFrom: stringType().array(), tableTo: stringType(), schemaTo: stringType().optional(), columnsTo: stringType().array(), onUpdate: stringType().optional(), onDelete: stringType().optional() }).strict(); sequenceSchema2 = objectType({ name: stringType(), increment: stringType().optional(), minValue: stringType().optional(), maxValue: stringType().optional(), startWith: stringType().optional(), cache: stringType().optional(), cycle: booleanType().optional(), schema: stringType() }).strict(); roleSchema2 = objectType({ name: stringType(), createDb: booleanType().optional(), createRole: booleanType().optional(), inherit: booleanType().optional() }).strict(); sequenceSquashed2 = objectType({ name: stringType(), schema: stringType(), values: stringType() }).strict(); 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(); column3 = objectType({ name: stringType(), type: stringType(), typeSchema: stringType().optional(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), isUnique: anyType().optional(), uniqueName: stringType().optional(), nullsNotDistinct: booleanType().optional(), generated: objectType({ type: literalType("stored"), as: stringType() }).optional(), identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional() }).strict(); checkConstraint3 = objectType({ name: stringType(), value: stringType() }).strict(); columnSquashed2 = objectType({ name: stringType(), type: stringType(), typeSchema: stringType().optional(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), isUnique: anyType().optional(), uniqueName: stringType().optional(), nullsNotDistinct: booleanType().optional(), generated: objectType({ type: literalType("stored"), as: stringType() }).optional(), identity: stringType().optional() }).strict(); tableV32 = objectType({ name: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), index3), foreignKeys: recordType(stringType(), fk3) }).strict(); compositePK3 = objectType({ name: stringType(), columns: stringType().array() }).strict(); uniqueConstraint3 = objectType({ name: stringType(), columns: stringType().array(), nullsNotDistinct: booleanType() }).strict(); policy2 = objectType({ name: stringType(), as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(), for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(), to: stringType().array().optional(), using: stringType().optional(), withCheck: stringType().optional(), on: stringType().optional(), schema: stringType().optional() }).strict(); policySquashed2 = objectType({ name: stringType(), values: stringType() }).strict(); viewWithOption2 = objectType({ checkOption: enumType(["local", "cascaded"]).optional(), securityBarrier: booleanType().optional(), securityInvoker: booleanType().optional() }).strict(); matViewWithOption2 = objectType({ fillfactor: numberType().optional(), toastTupleTarget: numberType().optional(), parallelWorkers: numberType().optional(), autovacuumEnabled: booleanType().optional(), vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(), vacuumTruncate: booleanType().optional(), autovacuumVacuumThreshold: numberType().optional(), autovacuumVacuumScaleFactor: numberType().optional(), autovacuumVacuumCostDelay: numberType().optional(), autovacuumVacuumCostLimit: numberType().optional(), autovacuumFreezeMinAge: numberType().optional(), autovacuumFreezeMaxAge: numberType().optional(), autovacuumFreezeTableAge: numberType().optional(), autovacuumMultixactFreezeMinAge: numberType().optional(), autovacuumMultixactFreezeMaxAge: numberType().optional(), autovacuumMultixactFreezeTableAge: numberType().optional(), logAutovacuumMinDuration: numberType().optional(), userCatalogTable: booleanType().optional() }).strict(); mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict(); view3 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), definition: stringType().optional(), materialized: booleanType(), with: mergedViewWithOption2.optional(), isExisting: booleanType(), withNoData: booleanType().optional(), using: stringType().optional(), tablespace: stringType().optional() }).strict(); tableV42 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), indexV4), foreignKeys: recordType(stringType(), fk3) }).strict(); tableV5 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), indexV5), foreignKeys: recordType(stringType(), fk3), compositePrimaryKeys: recordType(stringType(), compositePK3), uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}) }).strict(); tableV6 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), indexV6), foreignKeys: recordType(stringType(), fk3), compositePrimaryKeys: recordType(stringType(), compositePK3), uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}) }).strict(); tableV7 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), columnV7), indexes: recordType(stringType(), index3), foreignKeys: recordType(stringType(), fk3), compositePrimaryKeys: recordType(stringType(), compositePK3), uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}) }).strict(); table3 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), index3), foreignKeys: recordType(stringType(), fk3), compositePrimaryKeys: recordType(stringType(), compositePK3), uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}), policies: recordType(stringType(), policy2).default({}), checkConstraints: recordType(stringType(), checkConstraint3).default({}), isRLSEnabled: booleanType().default(false) }).strict(); schemaHash3 = objectType({ id: stringType(), prevId: stringType() }); kitInternals3 = 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(), enumSchemaV12) }).strict(); pgSchemaInternalV4 = objectType({ version: literalType("4"), dialect: literalType("pg"), tables: recordType(stringType(), tableV42), enums: recordType(stringType(), enumSchemaV12), schemas: recordType(stringType(), stringType()) }).strict(); pgSchemaInternalV5 = objectType({ version: literalType("5"), dialect: literalType("pg"), tables: recordType(stringType(), tableV5), enums: recordType(stringType(), enumSchemaV12), schemas: recordType(stringType(), stringType()), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals3 }).strict(); pgSchemaInternalV6 = objectType({ version: literalType("6"), dialect: literalType("postgresql"), tables: recordType(stringType(), tableV6), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals3 }).strict(); pgSchemaExternal = objectType({ version: literalType("5"), dialect: literalType("pg"), tables: arrayType(table3), enums: arrayType(enumSchemaV12), 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(), enumSchema2), schemas: recordType(stringType(), stringType()), sequences: recordType(stringType(), sequenceSchema2), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals3 }).strict(); pgSchemaInternal = objectType({ version: literalType("7"), dialect: literalType("postgresql"), tables: recordType(stringType(), table3), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view3).default({}), sequences: recordType(stringType(), sequenceSchema2).default({}), roles: recordType(stringType(), roleSchema2).default({}), policies: recordType(stringType(), policy2).default({}), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals3 }).strict(); tableSquashed3 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), columnSquashed2), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()), uniqueConstraints: recordType(stringType(), stringType()), policies: recordType(stringType(), stringType()), checkConstraints: recordType(stringType(), stringType()), isRLSEnabled: booleanType().default(false) }).strict(); tableSquashedV42 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column3), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()) }).strict(); pgSchemaSquashedV4 = objectType({ version: literalType("4"), dialect: literalType("pg"), tables: recordType(stringType(), tableSquashedV42), enums: recordType(stringType(), enumSchemaV12), schemas: recordType(stringType(), stringType()) }).strict(); pgSchemaSquashedV6 = objectType({ version: literalType("6"), dialect: literalType("postgresql"), tables: recordType(stringType(), tableSquashed3), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()) }).strict(); pgSchemaSquashed = objectType({ version: literalType("7"), dialect: literalType("postgresql"), tables: recordType(stringType(), tableSquashed3), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view3), sequences: recordType(stringType(), sequenceSquashed2), roles: recordType(stringType(), roleSchema2).default({}), policies: recordType(stringType(), policySquashed2).default({}) }).strict(); pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3); pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3); pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3); pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3); pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3); pgSchema = pgSchemaInternal.merge(schemaHash3); backwardCompatiblePgSchema = unionType([ pgSchemaV5, pgSchemaV6, pgSchema ]); PgSquasher = { squashIdx: (idx) => { index3.parse(idx); return `${idx.name};${idx.columns.map( (c5) => `${c5.expression}--${c5.isExpression}--${c5.asc}--${c5.nulls}--${c5.opclass ? c5.opclass : ""}` ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`; }, unsquashIdx: (input) => { const [ name, columnsString, isUnique, concurrently, method, where, idxWith ] = input.split(";"); const columnString = columnsString.split(",,"); const columns = []; for (const column6 of columnString) { const [expression, isExpression, asc, nulls, opclass] = column6.split("--"); columns.push({ nulls, isExpression: isExpression === "true", asc: asc === "true", expression, opclass: opclass === "undefined" ? void 0 : opclass }); } const result = index3.parse({ name, columns, isUnique: isUnique === "true", concurrently: concurrently === "true", method, where: where === "undefined" ? void 0 : where, with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith) }); return result; }, squashIdxPush: (idx) => { index3.parse(idx); return `${idx.name};${idx.columns.map((c5) => `${c5.isExpression ? "" : c5.expression}--${c5.asc}--${c5.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`; }, unsquashIdxPush: (input) => { const [name, columnsString, isUnique, method, idxWith] = input.split(";"); const columnString = columnsString.split("--"); const columns = []; for (const column6 of columnString) { const [expression, asc, nulls, opclass] = column6.split(","); columns.push({ nulls, isExpression: expression === "", asc: asc === "true", expression }); } const result = index3.parse({ name, columns, isUnique: isUnique === "true", concurrently: false, method, with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith) }); return result; }, squashFK: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`; }, squashPolicy: (policy5) => { return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`; }, unsquashPolicy: (policy5) => { const splitted = policy5.split("--"); return { name: splitted[0], as: splitted[1], for: splitted[2], to: splitted[3].split(","), using: splitted[4] !== "undefined" ? splitted[4] : void 0, withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0, on: splitted[6] !== "undefined" ? splitted[6] : void 0 }; }, squashPolicyPush: (policy5) => { return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.on}`; }, unsquashPolicyPush: (policy5) => { const splitted = policy5.split("--"); return { name: splitted[0], as: splitted[1], for: splitted[2], to: splitted[3].split(","), on: splitted[4] !== "undefined" ? splitted[4] : void 0 }; }, squashPK: (pk) => { return `${pk.columns.join(",")};${pk.name}`; }, unsquashPK: (pk) => { const splitted = pk.split(";"); return { name: splitted[1], columns: splitted[0].split(",") }; }, squashUnique: (unq) => { return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`; }, unsquashUnique: (unq) => { const [name, columns, nullsNotDistinct] = unq.split(";"); return { name, columns: columns.split(","), nullsNotDistinct: nullsNotDistinct === "true" }; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete, schemaTo ] = input.split(";"); const result = fk3.parse({ name, tableFrom, columnsFrom: columnsFromStr.split(","), schemaTo, tableTo, columnsTo: columnsToStr.split(","), onUpdate, onDelete }); return result; }, squashSequence: (seq) => { return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`; }, unsquashSequence: (seq) => { const splitted = seq.split(";"); return { minValue: splitted[0] !== "undefined" ? splitted[0] : void 0, maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0, increment: splitted[2] !== "undefined" ? splitted[2] : void 0, startWith: splitted[3] !== "undefined" ? splitted[3] : void 0, cache: splitted[4] !== "undefined" ? splitted[4] : void 0, cycle: splitted[5] === "true" }; }, squashIdentity: (seq) => { return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`; }, unsquashIdentity: (seq) => { const splitted = seq.split(";"); return { name: splitted[0], type: splitted[1], minValue: splitted[2] !== "undefined" ? splitted[2] : void 0, maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0, increment: splitted[4] !== "undefined" ? splitted[4] : void 0, startWith: splitted[5] !== "undefined" ? splitted[5] : void 0, cache: splitted[6] !== "undefined" ? splitted[6] : void 0, cycle: splitted[7] === "true" }; }, squashCheck: (check) => { return `${check.name};${check.value}`; }, unsquashCheck: (input) => { const [ name, value ] = input.split(";"); return { name, value }; } }; squashPgScheme = (json, action) => { const mappedTables = Object.fromEntries( Object.entries(json.tables).map((it) => { const squashedIndexes = mapValues(it[1].indexes, (index6) => { return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6); }); const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => { return PgSquasher.squashFK(fk5); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return PgSquasher.squashPK(pk); }); const mappedColumns = Object.fromEntries( Object.entries(it[1].columns).map((it2) => { const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0; return [ it2[0], { ...it2[1], identity: mappedIdentity } ]; }) ); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return PgSquasher.squashUnique(unq); } ); const squashedPolicies = mapValues(it[1].policies, (policy5) => { return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5); }); const squashedChecksContraints = mapValues( it[1].checkConstraints, (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(json.sequences).map((it) => { return [ it[0], { name: it[1].name, schema: it[1].schema, values: PgSquasher.squashSequence(it[1]) } ]; }) ); const mappedPolicies = Object.fromEntries( Object.entries(json.policies).map((it) => { return [ it[0], { name: it[1].name, values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1]) } ]; }) ); return { version: "7", dialect: json.dialect, tables: mappedTables, enums: json.enums, schemas: json.schemas, views: json.views, policies: mappedPolicies, sequences: mappedSequences, roles: json.roles }; }; dryPg = pgSchema.parse({ version: snapshotVersion, dialect: "postgresql", id: originUUID, prevId: "", tables: {}, enums: {}, schemas: {}, policies: {}, roles: {}, sequences: {}, _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // src/serializer/singlestoreSchema.ts var index4, column4, compositePK4, uniqueConstraint4, table4, viewMeta2, kitInternals4, dialect2, schemaHash4, schemaInternal2, schema2, tableSquashed4, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore; var init_singlestoreSchema = __esm({ "src/serializer/singlestoreSchema.ts"() { "use strict"; init_esm(); init_global(); index4 = 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(); column4 = 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(); compositePK4 = objectType({ name: stringType(), columns: stringType().array() }).strict(); uniqueConstraint4 = objectType({ name: stringType(), columns: stringType().array() }).strict(); table4 = objectType({ name: stringType(), columns: recordType(stringType(), column4), indexes: recordType(stringType(), index4), compositePrimaryKeys: recordType(stringType(), compositePK4), uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({}) }).strict(); viewMeta2 = objectType({ algorithm: enumType(["undefined", "merge", "temptable"]), sqlSecurity: enumType(["definer", "invoker"]), withCheckOption: enumType(["local", "cascaded"]).optional() }).strict(); kitInternals4 = objectType({ tables: recordType( stringType(), objectType({ columns: recordType( stringType(), objectType({ isDefaultAnExpression: booleanType().optional() }).optional() ) }).optional() ).optional(), indexes: recordType( stringType(), objectType({ columns: recordType( stringType(), objectType({ isExpression: booleanType().optional() }).optional() ) }).optional() ).optional() }).optional(); dialect2 = literalType("singlestore"); schemaHash4 = objectType({ id: stringType(), prevId: stringType() }); schemaInternal2 = objectType({ version: literalType("1"), dialect: dialect2, tables: recordType(stringType(), table4), /* views: record(string(), view).default({}), */ _meta: objectType({ tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals4 }).strict(); schema2 = schemaInternal2.merge(schemaHash4); tableSquashed4 = objectType({ name: stringType(), columns: recordType(stringType(), column4), indexes: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()), uniqueConstraints: recordType(stringType(), stringType()).default({}) }).strict(); schemaSquashed2 = objectType({ version: literalType("1"), dialect: dialect2, tables: recordType(stringType(), tableSquashed4) /* views: record(string(), viewSquashed), */ }).strict(); SingleStoreSquasher = { squashIdx: (idx) => { index4.parse(idx); return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`; }, unsquashIdx: (input) => { const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";"); const destructed = { name, columns: columnsString.split(","), isUnique: isUnique === "true", using: using ? using : void 0, algorithm: algorithm ? algorithm : void 0, lock: lock ? lock : void 0 }; return index4.parse(destructed); }, squashPK: (pk) => { return `${pk.name};${pk.columns.join(",")}`; }, unsquashPK: (pk) => { const splitted = pk.split(";"); return { name: splitted[0], columns: splitted[1].split(",") }; }, squashUnique: (unq) => { return `${unq.name};${unq.columns.join(",")}`; }, unsquashUnique: (unq) => { const [name, columns] = unq.split(";"); return { name, columns: columns.split(",") }; } /* squashView: (view: View): string => { return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`; }, unsquashView: (meta: string): SquasherViewMeta => { const [algorithm, sqlSecurity, withCheckOption] = meta.split(';'); const toReturn = { algorithm: algorithm, sqlSecurity: sqlSecurity, withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined, }; return viewMeta.parse(toReturn); }, */ }; squashSingleStoreScheme = (json) => { const mappedTables = Object.fromEntries( Object.entries(json.tables).map((it) => { const squashedIndexes = mapValues(it[1].indexes, (index6) => { return SingleStoreSquasher.squashIdx(index6); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return SingleStoreSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return SingleStoreSquasher.squashUnique(unq); } ); return [ it[0], { name: it[1].name, columns: it[1].columns, indexes: squashedIndexes, compositePrimaryKeys: squashedPKs, uniqueConstraints: squashedUniqueConstraints } ]; }) ); return { version: "1", dialect: json.dialect, tables: mappedTables /* views: mappedViews, */ }; }; singlestoreSchema = schema2; singlestoreSchemaSquashed = schemaSquashed2; backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]); drySingleStore = singlestoreSchema.parse({ version: "1", dialect: "singlestore", id: originUUID, prevId: "", tables: {}, schemas: {}, /* views: {}, */ _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // src/serializer/sqliteSchema.ts var index5, fk4, compositePK5, column5, tableV33, uniqueConstraint5, checkConstraint4, table5, view4, dialect3, schemaHash5, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals5, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed5, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema; var init_sqliteSchema = __esm({ "src/serializer/sqliteSchema.ts"() { "use strict"; init_esm(); init_global(); index5 = objectType({ name: stringType(), columns: stringType().array(), where: stringType().optional(), isUnique: booleanType() }).strict(); fk4 = objectType({ name: stringType(), tableFrom: stringType(), columnsFrom: stringType().array(), tableTo: stringType(), columnsTo: stringType().array(), onUpdate: stringType().optional(), onDelete: stringType().optional() }).strict(); compositePK5 = objectType({ columns: stringType().array(), name: stringType().optional() }).strict(); column5 = 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(), column5), indexes: recordType(stringType(), index5), foreignKeys: recordType(stringType(), fk4) }).strict(); uniqueConstraint5 = objectType({ name: stringType(), columns: stringType().array() }).strict(); checkConstraint4 = objectType({ name: stringType(), value: stringType() }).strict(); table5 = objectType({ name: stringType(), columns: recordType(stringType(), column5), indexes: recordType(stringType(), index5), foreignKeys: recordType(stringType(), fk4), compositePrimaryKeys: recordType(stringType(), compositePK5), uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}), checkConstraints: recordType(stringType(), checkConstraint4).default({}) }).strict(); view4 = objectType({ name: stringType(), columns: recordType(stringType(), column5), definition: stringType().optional(), isExisting: booleanType() }).strict(); dialect3 = enumType(["sqlite"]); schemaHash5 = objectType({ id: stringType(), prevId: stringType() }).strict(); schemaInternalV32 = objectType({ version: literalType("3"), dialect: dialect3, tables: recordType(stringType(), tableV33), enums: objectType({}) }).strict(); schemaInternalV42 = objectType({ version: literalType("4"), dialect: dialect3, tables: recordType(stringType(), table5), views: recordType(stringType(), view4).default({}), enums: objectType({}) }).strict(); schemaInternalV52 = objectType({ version: literalType("5"), dialect: dialect3, tables: recordType(stringType(), table5), enums: objectType({}), _meta: objectType({ tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }) }).strict(); kitInternals5 = objectType({ indexes: recordType( stringType(), objectType({ columns: recordType( stringType(), objectType({ isExpression: booleanType().optional() }).optional() ) }).optional() ).optional() }).optional(); latestVersion = literalType("6"); schemaInternal3 = objectType({ version: latestVersion, dialect: dialect3, tables: recordType(stringType(), table5), views: recordType(stringType(), view4).default({}), enums: objectType({}), _meta: objectType({ tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals5 }).strict(); schemaV32 = schemaInternalV32.merge(schemaHash5).strict(); schemaV42 = schemaInternalV42.merge(schemaHash5).strict(); schemaV52 = schemaInternalV52.merge(schemaHash5).strict(); schema3 = schemaInternal3.merge(schemaHash5).strict(); tableSquashed5 = objectType({ name: stringType(), columns: recordType(stringType(), column5), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()), uniqueConstraints: recordType(stringType(), stringType()).default({}), checkConstraints: recordType(stringType(), stringType()).default({}) }).strict(); schemaSquashed3 = objectType({ version: latestVersion, dialect: dialect3, tables: recordType(stringType(), tableSquashed5), views: recordType(stringType(), view4), enums: anyType() }).strict(); SQLiteSquasher = { squashIdx: (idx) => { index5.parse(idx); return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`; }, unsquashIdx: (input) => { const [name, columnsString, isUnique, where] = input.split(";"); const result = index5.parse({ name, columns: columnsString.split(","), isUnique: isUnique === "true", where: where ?? void 0 }); return result; }, squashUnique: (unq) => { return `${unq.name};${unq.columns.join(",")}`; }, unsquashUnique: (unq) => { const [name, columns] = unq.split(";"); return { name, columns: columns.split(",") }; }, squashFK: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = fk4.parse({ name, tableFrom, columnsFrom: columnsFromStr.split(","), tableTo, columnsTo: columnsToStr.split(","), onUpdate, onDelete }); return result; }, squashPushFK: (fk5) => { return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashPushFK: (input) => { const [ tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = fk4.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 [ name, value ] = input.split(";"); return { name, value }; } }; squashSqliteScheme = (json, action) => { const mappedTables = Object.fromEntries( Object.entries(json.tables).map((it) => { const squashedIndexes = mapValues(it[1].indexes, (index6) => { return SQLiteSquasher.squashIdx(index6); }); const squashedFKs = customMapEntries( it[1].foreignKeys, (key, value) => { return action === "push" ? [ SQLiteSquasher.squashPushFK(value), SQLiteSquasher.squashPushFK(value) ] : [key, SQLiteSquasher.squashFK(value)]; } ); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return SQLiteSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return SQLiteSquasher.squashUnique(unq); } ); const squashedCheckConstraints = mapValues( it[1].checkConstraints, (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: json.dialect, tables: mappedTables, views: json.views, enums: json.enums }; }; drySQLite = schema3.parse({ version: "6", dialect: "sqlite", id: originUUID, prevId: "", tables: {}, views: {}, enums: {}, _meta: { tables: {}, columns: {} } }); sqliteSchemaV5 = schemaV52; sqliteSchema = schema3; SQLiteSchemaSquashed = schemaSquashed3; backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]); } }); // src/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 import_url, copy, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl; var init_utils = __esm({ "src/utils.ts"() { "use strict"; import_url = require("url"); init_views(); init_global(); init_gelSchema(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); copy = (it) => { return JSON.parse(JSON.stringify(it)); }; prepareMigrationMeta = (schemas, tables, columns) => { const _meta = { schemas: {}, tables: {}, columns: {} }; schemas.forEach((it) => { const from = schemaRenameKey(it.from); const to = schemaRenameKey(it.to); _meta.schemas[from] = to; }); tables.forEach((it) => { const from = tableRenameKey(it.from); const to = tableRenameKey(it.to); _meta.tables[from] = to; }); columns.forEach((it) => { const from = columnRenameKey(it.from.table, it.from.schema, it.from.column); const to = columnRenameKey(it.to.table, it.to.schema, it.to.column); _meta.columns[from] = to; }); return _meta; }; schemaRenameKey = (it) => { return it; }; tableRenameKey = (it) => { const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`; return out; }; columnRenameKey = (table6, schema6, column6) => { const out = schema6 ? `"${schema6}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`; return out; }; normaliseSQLiteUrl = (it, type) => { if (type === "libsql") { if (it.startsWith("file:")) { return it; } try { const url = (0, import_url.parse)(it); if (url.protocol === null) { return `file:${it}`; } return it; } catch (e6) { return `file:${it}`; } } if (type === "better-sqlite") { if (it.startsWith("file:")) { return it.substring(5); } return it; } assertUnreachable(type); }; normalisePGliteUrl = (it) => { if (it.startsWith("file:")) { return it.substring(5); } return it; }; } }); // src/cli/views.ts var import_hanji, warning, err, 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}`); }; err = (msg) => { (0, import_hanji.render)(`${source_default.bold.red("Error")} ${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 text = ` Is ${source_default.bold.blue( this.base.name )} column in ${source_default.bold.blue( this.tableName )} table created or renamed from another column? `; const isSelectedRenamed = isRenamePromptItem( this.data.items[this.data.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => { return this.base.name.length + 3 + it["from"].name.length; }).reduce((a5, b5) => { if (a5 > b5) { return a5; } return b5; }, 0); this.data.items.forEach((it, idx) => { const isSelected = idx === this.data.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.data.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.data.items[this.data.selectedIdx]; } }; tableKey = (it) => { return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`; }; ResolveSelectNamed = class extends import_hanji.Prompt { constructor(base, data, entityType) { super(); this.base = base; this.entityType = entityType; this.on("attach", (terminal) => terminal.toggleCursor("hide")); this.state = new import_hanji.SelectState(data); this.state.bind(this); this.base = base; } render(status) { if (status === "submitted" || status === "aborted") { return ""; } const key = this.base.name; let text = ` Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}? `; const isSelectedRenamed = isRenamePromptItem( this.state.items[this.state.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => { const it = _3; const keyFrom = it.from.name; return key.length + 3 + keyFrom.length; }).reduce((a5, b5) => { if (a5 > b5) { return a5; } return b5; }, 0); const entityType = this.entityType; this.state.items.forEach((it, idx) => { const isSelected = idx === this.state.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.state.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.state.items[this.state.selectedIdx]; } }; ResolveSelect = class extends import_hanji.Prompt { constructor(base, data, entityType) { super(); this.base = base; this.entityType = entityType; this.on("attach", (terminal) => terminal.toggleCursor("hide")); this.state = new import_hanji.SelectState(data); this.state.bind(this); this.base = base; } render(status) { if (status === "submitted" || status === "aborted") { return ""; } const key = tableKey(this.base); let text = ` Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}? `; const isSelectedRenamed = isRenamePromptItem( this.state.items[this.state.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => { const it = _3; const keyFrom = tableKey(it.from); return key.length + 3 + keyFrom.length; }).reduce((a5, b5) => { if (a5 > b5) { return a5; } return b5; }, 0); const entityType = this.entityType; this.state.items.forEach((it, idx) => { const isSelected = idx === this.state.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.state.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.state.items[this.state.selectedIdx]; } }; ResolveSchemasSelect = class extends import_hanji.Prompt { constructor(base, data) { super(); this.base = base; this.on("attach", (terminal) => terminal.toggleCursor("hide")); this.state = new import_hanji.SelectState(data); this.state.bind(this); this.base = base; } render(status) { if (status === "submitted" || status === "aborted") { return ""; } let text = ` Is ${source_default.bold.blue( this.base.name )} schema created or renamed from another schema? `; const isSelectedRenamed = isRenamePromptItem( this.state.items[this.state.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => { return this.base.name.length + 3 + it["from"].name.length; }).reduce((a5, b5) => { if (a5 > b5) { return a5; } return b5; }, 0); this.state.items.forEach((it, idx) => { const isSelected = idx === this.state.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.state.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.state.items[this.state.selectedIdx]; } }; Spinner = class { constructor(frames) { this.frames = frames; this.offset = 0; this.tick = () => { this.iterator(); }; this.value = () => { return this.frames[this.offset]; }; this.iterator = () => { this.offset += 1; this.offset %= frames.length - 1; }; } }; 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 import_fs, glob, import_path, prepareFilenames; var init_serializer = __esm({ "src/serializer/index.ts"() { "use strict"; import_fs = __toESM(require("fs")); glob = __toESM(require_glob()); import_path = __toESM(require("path")); init_views(); prepareFilenames = (path3) => { if (typeof path3 === "string") { path3 = [path3]; } const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || ""; const result = path3.reduce((result2, cur) => { const globbed = glob.sync(`${prefix2}${cur}`); globbed.forEach((it) => { const fileName = import_fs.default.lstatSync(it).isDirectory() ? null : import_path.default.resolve(it); const filenames = fileName ? [fileName] : import_fs.default.readdirSync(it).map((file) => import_path.default.join(import_path.default.resolve(it), file)); filenames.filter((file) => !import_fs.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file)); }); return result2; }, /* @__PURE__ */ new Set()); const res = [...result]; const errors = res.filter((it) => { return !(it.endsWith(".ts") || it.endsWith(".js") || it.endsWith(".cjs") || it.endsWith(".mjs") || it.endsWith(".mts") || it.endsWith(".cts")); }); if (res.length === 0) { console.log( error( `No schema files found for path config [${path3.map((it) => `'${it}'`).join(", ")}]` ) ); console.log( error( `If path represents a file - please make sure to use .ts or other extension in the path` ) ); process.exit(1); } return res; }; } }); // src/migrationPreparator.ts var init_migrationPreparator = __esm({ "src/migrationPreparator.ts"() { "use strict"; init_serializer(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); } }); // ../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, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; floor = Math.floor, min = Math.min; defaultCmp = function(x5, y2) { if (x5 < y2) { return -1; } if (x5 > y2) { return 1; } return 0; }; insort = function(a5, x5, 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 = a5.length; } while (lo < hi) { mid = floor((lo + hi) / 2); if (cmp(x5, a5[mid]) < 0) { hi = mid; } else { lo = mid + 1; } } return [].splice.apply(a5, [lo, lo - lo].concat(x5)), x5; }; 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 i6, _i, _j, _len, _ref, _ref1, _results, _results1; if (cmp == null) { cmp = defaultCmp; } _ref1 = function() { _results1 = []; for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) { _results1.push(_j2); } return _results1; }.apply(this).reverse(); _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { i6 = _ref1[_i]; _results.push(_siftup(array2, i6, 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, n5, cmp) { var elem, result, _i, _len, _ref; if (cmp == null) { cmp = defaultCmp; } result = array2.slice(0, n5); if (!result.length) { return result; } heapify(result, cmp); _ref = array2.slice(n5); for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; heappushpop(result, elem, cmp); } return result.sort(cmp).reverse(); }; nsmallest = function(array2, n5, cmp) { var elem, i6, los, result, _i, _j, _len, _ref, _ref1, _results; if (cmp == null) { cmp = defaultCmp; } if (n5 * 10 <= array2.length) { result = array2.slice(0, n5).sort(cmp); if (!result.length) { return result; } los = result[result.length - 1]; _ref = array2.slice(n5); for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; if (cmp(elem, los) < 0) { insort(result, elem, 0, null, cmp); result.pop(); los = result[result.length - 1]; } } return result; } heapify(array2, cmp); _results = []; for (i6 = _j = 0, _ref1 = min(n5, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i6 = 0 <= _ref1 ? ++_j : --_j) { _results.push(heappop(array2, cmp)); } return _results; }; _siftdown = function(array2, startpos, pos, cmp) { var newitem, parent, parentpos; if (cmp == null) { cmp = defaultCmp; } newitem = array2[pos]; while (pos > startpos) { parentpos = pos - 1 >> 1; parent = array2[parentpos]; if (cmp(newitem, parent) < 0) { array2[pos] = parent; pos = parentpos; continue; } break; } return array2[pos] = newitem; }; _siftup = function(array2, pos, cmp) { var childpos, endpos, newitem, rightpos, startpos; if (cmp == null) { cmp = defaultCmp; } endpos = array2.length; startpos = pos; newitem = array2[pos]; childpos = 2 * pos + 1; while (childpos < endpos) { rightpos = childpos + 1; if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) { childpos = rightpos; } array2[pos] = array2[childpos]; pos = childpos; childpos = 2 * pos + 1; } array2[pos] = newitem; return _siftdown(array2, startpos, pos, cmp); }; Heap = function() { Heap2.push = heappush; Heap2.pop = heappop; Heap2.replace = heapreplace; Heap2.pushpop = heappushpop; Heap2.heapify = heapify; Heap2.updateItem = updateItem; Heap2.nlargest = nlargest; Heap2.nsmallest = nsmallest; function Heap2(cmp) { this.cmp = cmp != null ? cmp : defaultCmp; this.nodes = []; } Heap2.prototype.push = function(x5) { return heappush(this.nodes, x5, this.cmp); }; Heap2.prototype.pop = function() { return heappop(this.nodes, this.cmp); }; Heap2.prototype.peek = function() { return this.nodes[0]; }; Heap2.prototype.contains = function(x5) { return this.nodes.indexOf(x5) !== -1; }; Heap2.prototype.replace = function(x5) { return heapreplace(this.nodes, x5, this.cmp); }; Heap2.prototype.pushpop = function(x5) { return heappushpop(this.nodes, x5, this.cmp); }; Heap2.prototype.heapify = function() { return heapify(this.nodes, this.cmp); }; Heap2.prototype.updateItem = function(x5) { return updateItem(this.nodes, x5, 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, max, min, ndiff, restore, unifiedDiff, indexOf = [].indexOf; ({ floor, max, min } = Math); Heap = require_heap2(); assert = require("assert"); _calculateRatio = function(matches, length) { if (length) { return 2 * matches / length; } else { return 1; } }; _arrayCmp = function(a5, b5) { var i6, l5, la, lb, ref; [la, lb] = [a5.length, b5.length]; for (i6 = l5 = 0, ref = min(la, lb); 0 <= ref ? l5 < ref : l5 > ref; i6 = 0 <= ref ? ++l5 : --l5) { if (a5[i6] < b5[i6]) { return -1; } if (a5[i6] > b5[i6]) { return 1; } } return la - lb; }; _has = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; _any = function(items) { var item, l5, len; for (l5 = 0, len = items.length; l5 < len; l5++) { item = items[l5]; 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, a5 = "", b5 = "", autojunk = true) { this.isjunk = isjunk1; this.autojunk = autojunk; this.a = this.b = null; this.setSeqs(a5, b5); } setSeqs(a5, b5) { this.setSeq1(a5); return this.setSeq2(b5); } setSeq1(a5) { if (a5 === this.a) { return; } this.a = a5; return this.matchingBlocks = this.opcodes = null; } setSeq2(b5) { if (b5 === this.b) { return; } this.b = b5; 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 b5, b2j, elt, i6, indices, isjunk, junk, l5, len, n5, ntest, popular; b5 = this.b; this.b2j = b2j = /* @__PURE__ */ new Map(); for (i6 = l5 = 0, len = b5.length; l5 < len; i6 = ++l5) { elt = b5[i6]; if (!b2j.has(elt)) { b2j.set(elt, []); } indices = b2j.get(elt); indices.push(i6); } 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(); n5 = b5.length; if (this.autojunk && n5 >= 200) { ntest = floor(n5 / 100) + 1; b2j.forEach(function(idxs, elt2) { if (idxs.length > ntest) { popular.set(elt2, true); return b2j.delete(elt2); } }); } this.isbjunk = function(b6) { return junk.has(b6); }; return this.isbpopular = function(b6) { return popular.has(b6); }; } findLongestMatch(alo, ahi, blo, bhi) { var a5, b5, b2j, besti, bestj, bestsize, i6, isbjunk, j5, j2len, jlist, k5, l5, len, m6, newj2len, ref, ref1; [a5, b5, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk]; [besti, bestj, bestsize] = [alo, blo, 0]; j2len = {}; for (i6 = l5 = ref = alo, ref1 = ahi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) { newj2len = {}; jlist = []; if (b2j.has(a5[i6])) { jlist = b2j.get(a5[i6]); } for (m6 = 0, len = jlist.length; m6 < len; m6++) { j5 = jlist[m6]; if (j5 < blo) { continue; } if (j5 >= bhi) { break; } k5 = newj2len[j5] = (j2len[j5 - 1] || 0) + 1; if (k5 > bestsize) { [besti, bestj, bestsize] = [i6 - k5 + 1, j5 - k5 + 1, k5]; } } j2len = newj2len; } while (besti > alo && bestj > blo && !isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) { [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1]; } while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) { bestsize++; } while (besti > alo && bestj > blo && isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) { [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1]; } while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) { bestsize++; } return [besti, bestj, bestsize]; } getMatchingBlocks() { var ahi, alo, bhi, blo, i6, i1, i22, j5, j1, j22, k5, k1, k22, l5, la, lb, len, matchingBlocks, nonAdjacent, queue, x5; 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(); [i6, j5, k5] = x5 = this.findLongestMatch(alo, ahi, blo, bhi); if (k5) { matchingBlocks.push(x5); if (alo < i6 && blo < j5) { queue.push([alo, i6, blo, j5]); } if (i6 + k5 < ahi && j5 + k5 < bhi) { queue.push([i6 + k5, ahi, j5 + k5, bhi]); } } } matchingBlocks.sort(_arrayCmp); i1 = j1 = k1 = 0; nonAdjacent = []; for (l5 = 0, len = matchingBlocks.length; l5 < len; l5++) { [i22, j22, k22] = matchingBlocks[l5]; if (i1 + k1 === i22 && j1 + k1 === j22) { k1 += k22; } else { if (k1) { nonAdjacent.push([i1, j1, k1]); } [i1, j1, k1] = [i22, j22, k22]; } } if (k1) { nonAdjacent.push([i1, j1, k1]); } nonAdjacent.push([la, lb, 0]); return this.matchingBlocks = nonAdjacent; } getOpcodes() { var ai, answer, bj, i6, j5, l5, len, ref, size, tag; if (this.opcodes) { return this.opcodes; } i6 = j5 = 0; this.opcodes = answer = []; ref = this.getMatchingBlocks(); for (l5 = 0, len = ref.length; l5 < len; l5++) { [ai, bj, size] = ref[l5]; tag = ""; if (i6 < ai && j5 < bj) { tag = "replace"; } else if (i6 < ai) { tag = "delete"; } else if (j5 < bj) { tag = "insert"; } if (tag) { answer.push([tag, i6, ai, j5, bj]); } [i6, j5] = [ai + size, bj + size]; if (size) { answer.push(["equal", ai, i6, bj, j5]); } } return answer; } getGroupedOpcodes(n5 = 3) { var codes, group, groups, i1, i22, j1, j22, l5, len, nn, tag; codes = this.getOpcodes(); if (!codes.length) { codes = [["equal", 0, 1, 0, 1]]; } if (codes[0][0] === "equal") { [tag, i1, i22, j1, j22] = codes[0]; codes[0] = [tag, max(i1, i22 - n5), i22, max(j1, j22 - n5), j22]; } if (codes[codes.length - 1][0] === "equal") { [tag, i1, i22, j1, j22] = codes[codes.length - 1]; codes[codes.length - 1] = [tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)]; } nn = n5 + n5; groups = []; group = []; for (l5 = 0, len = codes.length; l5 < len; l5++) { [tag, i1, i22, j1, j22] = codes[l5]; if (tag === "equal" && i22 - i1 > nn) { group.push([tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)]); groups.push(group); group = []; [i1, j1] = [max(i1, i22 - n5), max(j1, j22 - n5)]; } group.push([tag, i1, i22, j1, j22]); } if (group.length && !(group.length === 1 && group[0][0] === "equal")) { groups.push(group); } return groups; } ratio() { var l5, len, match2, matches, ref; matches = 0; ref = this.getMatchingBlocks(); for (l5 = 0, len = ref.length; l5 < len; l5++) { match2 = ref[l5]; matches += match2[2]; } return _calculateRatio(matches, this.a.length + this.b.length); } quickRatio() { var avail, elt, fullbcount, l5, len, len1, m6, matches, numb, ref, ref1; if (!this.fullbcount) { this.fullbcount = fullbcount = {}; ref = this.b; for (l5 = 0, len = ref.length; l5 < len; l5++) { elt = ref[l5]; fullbcount[elt] = (fullbcount[elt] || 0) + 1; } } fullbcount = this.fullbcount; avail = {}; matches = 0; ref1 = this.a; for (m6 = 0, len1 = ref1.length; m6 < len1; m6++) { elt = ref1[m6]; if (_has(avail, elt)) { numb = avail[elt]; } else { numb = fullbcount[elt] || 0; } avail[elt] = numb - 1; if (numb > 0) { matches++; } } return _calculateRatio(matches, this.a.length + this.b.length); } realQuickRatio() { var la, lb; [la, lb] = [this.a.length, this.b.length]; return _calculateRatio(min(la, lb), la + lb); } }; getCloseMatches = function(word, possibilities, n5 = 3, cutoff = 0.6) { var l5, len, len1, m6, result, results, s6, score, x5; if (!(n5 > 0)) { throw new Error(`n must be > 0: (${n5})`); } if (!(0 <= cutoff && cutoff <= 1)) { throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`); } result = []; s6 = new SequenceMatcher(); s6.setSeq2(word); for (l5 = 0, len = possibilities.length; l5 < len; l5++) { x5 = possibilities[l5]; s6.setSeq1(x5); if (s6.realQuickRatio() >= cutoff && s6.quickRatio() >= cutoff && s6.ratio() >= cutoff) { result.push([s6.ratio(), x5]); } } result = Heap.nlargest(result, n5, _arrayCmp); results = []; for (m6 = 0, len1 = result.length; m6 < len1; m6++) { [score, x5] = result[m6]; results.push(x5); } return results; }; _countLeading = function(line, ch) { var i6, n5; [i6, n5] = [0, line.length]; while (i6 < n5 && line[i6] === ch) { i6++; } return i6; }; 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(a5, b5) { var ahi, alo, bhi, blo, cruncher, g5, l5, len, len1, line, lines, m6, ref, tag; cruncher = new SequenceMatcher(this.linejunk, a5, b5); lines = []; ref = cruncher.getOpcodes(); for (l5 = 0, len = ref.length; l5 < len; l5++) { [tag, alo, ahi, blo, bhi] = ref[l5]; switch (tag) { case "replace": g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi); break; case "delete": g5 = this._dump("-", a5, alo, ahi); break; case "insert": g5 = this._dump("+", b5, blo, bhi); break; case "equal": g5 = this._dump(" ", a5, alo, ahi); break; default: throw new Error(`unknow tag (${tag})`); } for (m6 = 0, len1 = g5.length; m6 < len1; m6++) { line = g5[m6]; lines.push(line); } } return lines; } _dump(tag, x5, lo, hi) { var i6, l5, ref, ref1, results; results = []; for (i6 = l5 = ref = lo, ref1 = hi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) { results.push(`${tag} ${x5[i6]}`); } return results; } _plainReplace(a5, alo, ahi, b5, blo, bhi) { var first, g5, l5, len, len1, line, lines, m6, ref, second; assert(alo < ahi && blo < bhi); if (bhi - blo < ahi - alo) { first = this._dump("+", b5, blo, bhi); second = this._dump("-", a5, alo, ahi); } else { first = this._dump("-", a5, alo, ahi); second = this._dump("+", b5, blo, bhi); } lines = []; ref = [first, second]; for (l5 = 0, len = ref.length; l5 < len; l5++) { g5 = ref[l5]; for (m6 = 0, len1 = g5.length; m6 < len1; m6++) { line = g5[m6]; lines.push(line); } } return lines; } _fancyReplace(a5, alo, ahi, b5, blo, bhi) { var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i6, j5, l5, la, lb, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, r6, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t6, 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 (j5 = l5 = ref = blo, ref1 = bhi; ref <= ref1 ? l5 < ref1 : l5 > ref1; j5 = ref <= ref1 ? ++l5 : --l5) { bj = b5[j5]; cruncher.setSeq2(bj); for (i6 = m6 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m6 < ref3 : m6 > ref3; i6 = ref2 <= ref3 ? ++m6 : --m6) { ai = a5[i6]; if (ai === bj) { if (eqi === null) { [eqi, eqj] = [i6, j5]; } continue; } cruncher.setSeq1(ai); if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) { [bestRatio, besti, bestj] = [cruncher.ratio(), i6, j5]; } } } if (bestRatio < cutoff) { if (eqi === null) { ref4 = this._plainReplace(a5, alo, ahi, b5, blo, bhi); for (o5 = 0, len = ref4.length; o5 < len; o5++) { line = ref4[o5]; lines.push(line); } return lines; } [besti, bestj, bestRatio] = [eqi, eqj, 1]; } else { eqi = null; } ref5 = this._fancyHelper(a5, alo, besti, b5, blo, bestj); for (p5 = 0, len1 = ref5.length; p5 < len1; p5++) { line = ref5[p5]; lines.push(line); } [aelt, belt] = [a5[besti], b5[bestj]]; if (eqi === null) { atags = btags = ""; cruncher.setSeqs(aelt, belt); ref6 = cruncher.getOpcodes(); for (q5 = 0, len2 = ref6.length; q5 < len2; q5++) { [tag, ai1, ai2, bj1, bj2] = ref6[q5]; [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 (r6 = 0, len3 = ref7.length; r6 < len3; r6++) { line = ref7[r6]; lines.push(line); } } else { lines.push(" " + aelt); } ref8 = this._fancyHelper(a5, besti + 1, ahi, b5, bestj + 1, bhi); for (t6 = 0, len4 = ref8.length; t6 < len4; t6++) { line = ref8[t6]; lines.push(line); } return lines; } _fancyHelper(a5, alo, ahi, b5, blo, bhi) { var g5; g5 = []; if (alo < ahi) { if (blo < bhi) { g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi); } else { g5 = this._dump("-", a5, alo, ahi); } } else if (blo < bhi) { g5 = this._dump("+", b5, blo, bhi); } return g5; } _qformat(aline, bline, atags, btags) { var common, lines; lines = []; common = min(_countLeading(aline, " "), _countLeading(bline, " ")); common = min(common, _countLeading(atags.slice(0, common), " ")); common = min(common, _countLeading(btags.slice(0, common), " ")); atags = atags.slice(common).replace(/\s+$/, ""); btags = btags.slice(common).replace(/\s+$/, ""); lines.push("- " + aline); if (atags.length) { lines.push(`? ${Array(common + 1).join(" ")}${atags} `); } lines.push("+ " + bline); if (btags.length) { lines.push(`? ${Array(common + 1).join(" ")}${btags} `); } return lines; } }; IS_LINE_JUNK = function(line, pat = /^\s*#?\s*$/) { return pat.test(line); }; IS_CHARACTER_JUNK = function(ch, ws = " ") { return indexOf.call(ws, ch) >= 0; }; _formatRangeUnified = function(start, stop) { var beginning, length; beginning = start + 1; length = stop - start; if (length === 1) { return `${beginning}`; } if (!length) { beginning--; } return `${beginning},${length}`; }; unifiedDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) { var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, ref, ref1, ref2, ref3, started, tag, todate; if (fromfile == null) { fromfile = ""; } if (tofile == null) { tofile = ""; } if (fromfiledate == null) { fromfiledate = ""; } if (tofiledate == null) { tofiledate = ""; } if (n5 == null) { n5 = 3; } if (lineterm == null) { lineterm = "\n"; } lines = []; started = false; ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes(); for (l5 = 0, len = ref.length; l5 < len; l5++) { group = ref[l5]; 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 (m6 = 0, len1 = group.length; m6 < len1; m6++) { [tag, i1, i22, j1, j22] = group[m6]; if (tag === "equal") { ref1 = a5.slice(i1, i22); for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) { line = ref1[o5]; lines.push(" " + line); } continue; } if (tag === "replace" || tag === "delete") { ref2 = a5.slice(i1, i22); for (p5 = 0, len3 = ref2.length; p5 < len3; p5++) { line = ref2[p5]; lines.push("-" + line); } } if (tag === "replace" || tag === "insert") { ref3 = b5.slice(j1, j22); for (q5 = 0, len4 = ref3.length; q5 < len4; q5++) { line = ref3[q5]; lines.push("+" + line); } } } } return lines; }; _formatRangeContext = function(start, stop) { var beginning, length; beginning = start + 1; length = stop - start; if (!length) { beginning--; } if (length <= 1) { return `${beginning}`; } return `${beginning},${beginning + length - 1}`; }; contextDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) { var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, prefix2, q5, ref, ref1, ref2, started, tag, todate; if (fromfile == null) { fromfile = ""; } if (tofile == null) { tofile = ""; } if (fromfiledate == null) { fromfiledate = ""; } if (tofiledate == null) { tofiledate = ""; } if (n5 == null) { n5 = 3; } if (lineterm == null) { lineterm = "\n"; } prefix2 = { insert: "+ ", delete: "- ", replace: "! ", equal: " " }; started = false; lines = []; ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes(); for (l5 = 0, len = ref.length; l5 < len; l5++) { group = ref[l5]; 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, m7, results; results = []; for (m7 = 0, len12 = group.length; m7 < len12; m7++) { [tag, _3, _3, _3, _3] = group[m7]; results.push(tag === "replace" || tag === "delete"); } return results; }())) { for (m6 = 0, len1 = group.length; m6 < len1; m6++) { [tag, i1, i22, _3, _3] = group[m6]; if (tag !== "insert") { ref1 = a5.slice(i1, i22); for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) { line = ref1[o5]; lines.push(prefix2[tag] + line); } } } } file2Range = _formatRangeContext(first[3], last[4]); lines.push(`--- ${file2Range} ----${lineterm}`); if (_any(function() { var len32, p6, results; results = []; for (p6 = 0, len32 = group.length; p6 < len32; p6++) { [tag, _3, _3, _3, _3] = group[p6]; results.push(tag === "replace" || tag === "insert"); } return results; }())) { for (p5 = 0, len3 = group.length; p5 < len3; p5++) { [tag, _3, _3, j1, j22] = group[p5]; if (tag !== "delete") { ref2 = b5.slice(j1, j22); for (q5 = 0, len4 = ref2.length; q5 < len4; q5++) { line = ref2[q5]; lines.push(prefix2[tag] + line); } } } } } } return lines; }; ndiff = function(a5, b5, linejunk, charjunk = IS_CHARACTER_JUNK) { return new Differ(linejunk, charjunk).compare(a5, b5); }; restore = function(delta, which) { var l5, len, line, lines, prefixes2, ref, tag; tag = { 1: "- ", 2: "+ " }[which]; if (!tag) { throw new Error(`unknow delta choice (must be 1 or 2): ${which}`); } prefixes2 = [" ", tag]; lines = []; for (l5 = 0, len = delta.length; l5 < len; l5++) { line = delta[l5]; if (ref = line.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) { lines.push(line.slice(2)); } } return lines; }; exports2._arrayCmp = _arrayCmp; exports2.SequenceMatcher = SequenceMatcher; exports2.getCloseMatches = getCloseMatches; exports2._countLeading = _countLeading; exports2.Differ = Differ; exports2.IS_LINE_JUNK = IS_LINE_JUNK; exports2.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK; exports2._formatRangeUnified = _formatRangeUnified; exports2.unifiedDiff = unifiedDiff; exports2._formatRangeContext = _formatRangeContext; exports2.contextDiff = contextDiff; exports2.ndiff = ndiff; exports2.restore = restore; }).call(exports2); } }); // ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js var require_difflib2 = __commonJS({ "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports2, module2) { "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((x5) => roundObj(x5, 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 val2 = codes[key]; var style = styles3[key] = []; style.open = "\x1B[" + val2[0] + "m"; style.close = "\x1B[" + val2[1] + "m"; }); } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js var require_has_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 os3 = require("os"); var hasFlag2 = require_has_flag(); var env4 = 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 env4) { forceColor = env4.FORCE_COLOR.length === 0 || parseInt(env4.FORCE_COLOR, 10) !== 0; } function translateLevel2(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor2(stream) { if (forceColor === false) { return 0; } if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) { return 3; } if (hasFlag2("color=256")) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } var min = forceColor ? 1 : 0; if (process.platform === "win32") { var osRelease = os3.release().split("."); if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env4) { if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) { return sign in env4; }) || env4.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env4) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env4.TEAMCITY_VERSION) ? 1 : 0; } if ("TERM_PROGRAM" in env4) { var version = parseInt((env4.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env4.TERM_PROGRAM) { case "iTerm.app": return version >= 3 ? 3 : 2; case "Hyper": return 3; case "Apple_Terminal": return 2; } } if (/-256(color)?$/i.test(env4.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env4.TERM)) { return 1; } if ("COLORTERM" in env4) { return 1; } if (env4.TERM === "dumb") { return min; } return min; } function getSupportLevel(stream) { var level = supportsColor2(stream); return translateLevel2(level); } module2.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js var require_trap = __commonJS({ "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports2, module2) { "use strict"; module2["exports"] = function runTheTrap(text, options) { var result = ""; text = text || "Run the trap, drop the bass"; text = text.split(""); var trap = { a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], c: ["\xA9", "\u023B", "\u03FE"], d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], e: [ "\xCB", "\u0115", "\u018E", "\u0258", "\u03A3", "\u03BE", "\u04BC", "\u0A6C" ], f: ["\u04FA"], g: ["\u0262"], h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], i: ["\u0F0F"], j: ["\u0134"], k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], l: ["\u0139"], m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], o: [ "\xD8", "\xF5", "\xF8", "\u01FE", "\u0298", "\u047A", "\u05DD", "\u06DD", "\u0E4F" ], p: ["\u01F7", "\u048E"], q: ["\u09CD"], r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], t: ["\u0141", "\u0166", "\u0373"], u: ["\u01B1", "\u054D"], v: ["\u05D8"], w: ["\u0428", "\u0460", "\u047C", "\u0D70"], x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], y: ["\xA5", "\u04B0", "\u04CB"], z: ["\u01B5", "\u0240"] }; text.forEach(function(c5) { c5 = c5.toLowerCase(); var chars = trap[c5] || [" "]; var rand = Math.floor(Math.random() * chars.length); if (typeof trap[c5] !== "undefined") { result += trap[c5][rand]; } else { result += c5; } }); 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(text, options) { text = text || " he is here "; var soul = { "up": [ "\u030D", "\u030E", "\u0304", "\u0305", "\u033F", "\u0311", "\u0306", "\u0310", "\u0352", "\u0357", "\u0351", "\u0307", "\u0308", "\u030A", "\u0342", "\u0313", "\u0308", "\u034A", "\u034B", "\u034C", "\u0303", "\u0302", "\u030C", "\u0350", "\u0300", "\u0301", "\u030B", "\u030F", "\u0312", "\u0313", "\u0314", "\u033D", "\u0309", "\u0363", "\u0364", "\u0365", "\u0366", "\u0367", "\u0368", "\u0369", "\u036A", "\u036B", "\u036C", "\u036D", "\u036E", "\u036F", "\u033E", "\u035B", "\u0346", "\u031A" ], "down": [ "\u0316", "\u0317", "\u0318", "\u0319", "\u031C", "\u031D", "\u031E", "\u031F", "\u0320", "\u0324", "\u0325", "\u0326", "\u0329", "\u032A", "\u032B", "\u032C", "\u032D", "\u032E", "\u032F", "\u0330", "\u0331", "\u0332", "\u0333", "\u0339", "\u033A", "\u033B", "\u033C", "\u0345", "\u0347", "\u0348", "\u0349", "\u034D", "\u034E", "\u0353", "\u0354", "\u0355", "\u0356", "\u0359", "\u035A", "\u0323" ], "mid": [ "\u0315", "\u031B", "\u0300", "\u0301", "\u0358", "\u0321", "\u0322", "\u0327", "\u0328", "\u0334", "\u0335", "\u0336", "\u035C", "\u035D", "\u035E", "\u035F", "\u0360", "\u0362", "\u0338", "\u0337", "\u0361", " \u0489" ] }; var all = [].concat(soul.up, soul.down, soul.mid); function randomNumber(range) { var r6 = Math.floor(Math.random() * range); return r6; } function isChar(character) { var bool = false; all.filter(function(i6) { bool = i6 === character; }); return bool; } function heComes(text2, options2) { var result = ""; var counts; var l5; options2 = options2 || {}; options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true; options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true; options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true; options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi"; text2 = text2.split(""); for (l5 in text2) { if (isChar(l5)) { continue; } result = result + text2[l5]; 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 d5 in arr) { var index6 = arr[d5]; for (var i6 = 0; i6 <= counts[index6]; i6++) { if (options2[index6]) { result = result + soul[index6][randomNumber(soul[index6].length)]; } } } } return result; } return heComes(text, options); }; } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js var require_america = __commonJS({ "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) { "use strict"; module2["exports"] = function(colors) { return function(letter, i6, exploded) { if (letter === " ") return letter; switch (i6 % 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, i6, exploded) { return i6 % 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, i6, exploded) { if (letter === " ") { return letter; } else { return colors[rainbowColors[i6++ % 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, i6, 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 i6 = nestedStyles.length; while (i6--) { var code = ansiStyles2[nestedStyles[i6]]; 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 i6 in theme[style2]) { out = colors[theme[style2][i6]](out); } return out; } return colors[theme[style2]](str); }; })(style); } }; function init2() { var ret = {}; Object.keys(styles3).forEach(function(name) { ret[name] = { get: function() { return build([name]); } }; }); return ret; } var sequencer = function sequencer2(map3, str) { var exploded = str.split(""); exploded = exploded.map(map3); return exploded.join(""); }; colors.trap = require_trap(); colors.zalgo = require_zalgo(); colors.maps = {}; colors.maps.america = require_america()(colors); colors.maps.zebra = require_zebra()(colors); colors.maps.rainbow = require_rainbow()(colors); colors.maps.random = require_random()(colors); for (map2 in colors.maps) { (function(map3) { colors[map3] = function(str) { return sequencer(colors.maps[map3], str); }; })(map2); } var map2; defineProps(colors, init2()); } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js var require_safe = __commonJS({ "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports2, module2) { "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 = { " "(s6) { return s6; }, "+": color.green, "-": color.red }; var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) { let subvalue; const prefix2 = key ? `${key}: ` : ""; const subindent = indent + " "; const outputElisions = (n5) => { const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions; if (n5 < maxElisions) { for (let i6 = 0; i6 < n5; i6++) { output(" ", subindent + "..."); } } else { output(" ", subindent + `... (${n5} 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 m6; subvalue = diff2[subkey]; if (m6 = subkey.match(/^(.*)__deleted$/)) { subcolorizeToCallback(options, m6[1], subvalue, output, "-", subindent); } else if (m6 = subkey.match(/^(.*)__added$/)) { subcolorizeToCallback(options, m6[1], subvalue, output, "+", subindent); } else { subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent); } } return output(color2, `${indent}}`); } case "array": { output(color2, `${indent}${prefix2}[`); let looksLikeDiff = true; for (const item of diff2) { if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) { looksLikeDiff = false; } } if (looksLikeDiff) { let op; let elisionCount = 0; for ([op, subvalue] of diff2) { if (op === " " && subvalue == null) { elisionCount++; } else { if (elisionCount > 0) { outputElisions(elisionCount); } elisionCount = 0; if (![" ", "~", "+", "-"].includes(op)) { throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`); } if (op === "~") { op = " "; } subcolorizeToCallback(options, "", subvalue, output, op, subindent); } } if (elisionCount > 0) { outputElisions(elisionCount); } } else { for (subvalue of diff2) { subcolorizeToCallback(options, "", subvalue, output, color2, subindent); } } return output(color2, `${indent}]`); } default: if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) { return output(color2, indent + prefix2 + JSON.stringify(diff2)); } } }; var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", ""); var colorizeToArray = function(diff2, options = {}) { const output = []; colorizeToCallback(diff2, options, (color2, line) => output.push(`${color2}${line}`)); return output; }; var colorize = function(diff2, options = {}) { const output = []; colorizeToCallback(diff2, options, function(color2, line) { if (options.color != null ? options.color : true) { return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line}`) + "\n"); } else { return output.push(`${color2}${line} `); } }); return output.join(""); }; module2.exports = { colorize, colorizeToArray, colorizeToCallback }; } }); // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js var require_lib = __commonJS({ "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports2, module2) { "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, index6, fuzzyOriginals) { let bestMatch = null; for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) { if (key !== "__next") { const indexDistance = Math.abs(matchIndex - index6); if (extendedTypeOf(item) === extendedTypeOf(candidate)) { const { score } = this.diff(item, candidate); if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) { bestMatch = { score, key, indexDistance }; } } } } return bestMatch; } scalarize(array2, originals, fuzzyOriginals) { const fuzzyMatches = []; if (fuzzyOriginals) { const keyScores = {}; for (let index6 = 0; index6 < array2.length; index6++) { const item = array2[index6]; if (this.isScalar(item)) { continue; } const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals); if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) { keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 }; } } for (const [key, match2] of Object.entries(keyScores)) { fuzzyMatches[match2.index] = key; } } const result = []; for (let index6 = 0; index6 < array2.length; index6++) { const item = array2[index6]; if (this.isScalar(item)) { result.push(item); } else { const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++; originals[key] = { item, index: index6 }; result.push(key); } } return result; } isScalarized(item, originals) { return typeof item === "string" && item in originals; } descalarize(item, originals) { if (this.isScalarized(item, originals)) { return originals[item].item; } else { return item; } } arrayDiff(obj1, obj2) { const originals1 = { __next: 1 }; const seq1 = this.scalarize(obj1, originals1); const originals2 = { __next: originals1.__next }; const seq2 = this.scalarize(obj2, originals2, originals1); if (this.options.sort) { seq1.sort(); seq2.sort(); } const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes(); let result = []; let score = 0; let equal = true; for (const [op, i1, i22, j1, j22] of opcodes) { let i6, j5; let asc, end; let asc1, end1; let asc2, end2; if (!(op === "equal" || this.options.keysOnly && op === "replace")) { equal = false; } switch (op) { case "equal": for (i6 = i1, end = i22, asc = i1 <= end; asc ? i6 < end : i6 > end; asc ? i6++ : i6--) { const item = seq1[i6]; 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 (i6 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i6 < end1 : i6 > end1; asc1 ? i6++ : i6--) { result.push(["-", this.descalarize(seq1[i6], originals1)]); score -= 5; } break; case "insert": for (j5 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j5 < end2 : j5 > end2; asc2 ? j5++ : j5--) { result.push(["+", this.descalarize(seq2[j5], originals2)]); score -= 5; } break; case "replace": if (!this.options.keysOnly) { let asc3, end3; let asc4, end4; for (i6 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i6 < end3 : i6 > end3; asc3 ? i6++ : i6--) { result.push(["-", this.descalarize(seq1[i6], originals1)]); score -= 5; } for (j5 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j5 < end4 : j5 > end4; asc4 ? j5++ : j5--) { result.push(["+", this.descalarize(seq2[j5], originals2)]); score -= 5; } } else { let asc5, end5; for (i6 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i6 < end5 : i6 > end5; asc5 ? i6++ : i6--) { const change = this.diff( this.descalarize(seq1[i6], originals1), this.descalarize(seq2[i6 - i1 + j1], originals2) ); if (!change.equal) { result.push(["~", change.result]); equal = false; } else { result.push([" "]); } } } break; } } if (equal || opcodes.length === 0) { if (!this.options.full) { result = void 0; } else { result = obj1; } score = 100; } else { score = Math.max(0, score); } return { score, result, equal }; } diff(obj1, obj2) { const type1 = extendedTypeOf(obj1); const type2 = extendedTypeOf(obj2); if (type1 === type2) { switch (type1) { case "object": return this.objectDiff(obj1, obj2); case "array": return this.arrayDiff(obj1, obj2); } } let score = 100; let result = obj1; let equal; if (!this.options.keysOnly) { if (type1 === "date" && type2 === "date") { equal = obj1.getTime() === obj2.getTime(); } else { equal = obj1 === obj2; } if (!equal) { score = 0; if (this.options.outputNewOnly) { result = obj2; } else { result = { __old: obj1, __new: obj2 }; } } else if (!this.options.full) { result = void 0; } } else { equal = true; result = void 0; } return { score, result, equal }; } }; function diff2(obj1, obj2, options = {}) { if (options.precision !== void 0) { obj1 = roundObj(obj1, options.precision); obj2 = roundObj(obj2, options.precision); } return new JsonDiff(options).diff(obj1, obj2).result; } function diffString(obj1, obj2, options = {}) { return colorize(diff2(obj1, obj2, options), options); } module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback }; } }); // src/jsonDiffer.js function diffSchemasOrTables(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {}); const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]); const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]); return { added, deleted }; } function diffIndPolicies(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {}); const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]); const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]); return { added, deleted }; } function diffColumns(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = (0, import_json_diff.diff)(left, right) ?? {}; const alteredTables = Object.fromEntries( Object.entries(result).filter((it) => { return !(it[0].includes("__added") || it[0].includes("__deleted")); }).map((tableEntry) => { const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => { return it[0].endsWith("__deleted"); }).map((it) => { return it[1]; }); const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => { return it[0].endsWith("__added"); }).map((it) => { return it[1]; }); tableEntry[1].columns = { added: addedColumns, deleted: deletedColumns }; const table6 = left[tableEntry[0]]; return [ tableEntry[0], { name: table6.name, schema: table6.schema, ...tableEntry[1] } ]; }) ); return alteredTables; } function diffPolicies(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = (0, import_json_diff.diff)(left, right) ?? {}; const alteredTables = Object.fromEntries( Object.entries(result).filter((it) => { return !(it[0].includes("__added") || it[0].includes("__deleted")); }).map((tableEntry) => { const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => { return it[0].endsWith("__deleted"); }).map((it) => { return it[1]; }); const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => { return it[0].endsWith("__added"); }).map((it) => { return it[1]; }); tableEntry[1].policies = { added: addedPolicies, deleted: deletedPolicies }; const table6 = left[tableEntry[0]]; return [ tableEntry[0], { name: table6.name, schema: table6.schema, ...tableEntry[1] } ]; }) ); return alteredTables; } function applyJsonDiff(json1, json2) { json1 = JSON.parse(JSON.stringify(json1)); json2 = JSON.parse(JSON.stringify(json2)); const rawDiff = (0, import_json_diff.diff)(json1, json2); const difference = JSON.parse(JSON.stringify(rawDiff || {})); difference.schemas = difference.schemas || {}; difference.tables = difference.tables || {}; difference.enums = difference.enums || {}; difference.sequences = difference.sequences || {}; difference.roles = difference.roles || {}; difference.policies = difference.policies || {}; difference.views = difference.views || {}; const schemaKeys = Object.keys(difference.schemas); for (let key of schemaKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete difference.schemas[key]; continue; } } const tableKeys = Object.keys(difference.tables); for (let key of tableKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete difference.tables[key]; continue; } const table6 = json1.tables[key]; difference.tables[key] = { name: table6.name, schema: table6.schema, ...difference.tables[key] }; } for (let [tableKey2, tableValue] of Object.entries(difference.tables)) { const table6 = difference.tables[tableKey2]; const columns = tableValue.columns || {}; const columnKeys = Object.keys(columns); for (let key of columnKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete table6.columns[key]; continue; } } if (Object.keys(columns).length === 0) { delete table6["columns"]; } if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) { delete difference.tables[tableKey2]; } } const enumsEntries = Object.entries(difference.enums); const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { const enumEntry = json1.enums[it[0]]; const { name, schema: schema6, values } = enumEntry; const sequence = mapArraysDiff(values, it[1].values); const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => { return { before: it2.before, value: it2.value }; }); const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value); return { name, schema: schema6, addedValues, deletedValues }; }); const sequencesEntries = Object.entries(difference.sequences); const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => { return json2.sequences[it[0]]; }); const rolesEntries = Object.entries(difference.roles); const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { return json2.roles[it[0]]; }); const policiesEntries = Object.entries(difference.policies); const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { return json2.policies[it[0]]; }); const viewsEntries = Object.entries(difference.views); const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map( ([nameWithSchema, view5]) => { const deletedWithOption = view5.with__deleted; const addedWithOption = view5.with__added; const deletedWith = Object.fromEntries( Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => { return [key.replace("__deleted", ""), value]; }) ); const addedWith = Object.fromEntries( Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => { return [key.replace("__added", ""), value]; }) ); const alterWith = Object.fromEntries( Object.entries(view5.with || {}).filter( (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined" ).map( (it) => { return [it[0], it[1].__new]; } ) ); const alteredSchema = view5.schema; const alteredDefinition = view5.definition; const alteredExisting = view5.isExisting; const addedTablespace = view5.tablespace__added; const droppedTablespace = view5.tablespace__deleted; const alterTablespaceTo = view5.tablespace; let alteredTablespace; if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" }; if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace }; if (alterTablespaceTo) alteredTablespace = alterTablespaceTo; const addedUsing = view5.using__added; const droppedUsing = view5.using__deleted; const alterUsingTo = view5.using; let alteredUsing; if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" }; if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing }; if (alterUsingTo) alteredUsing = alterUsingTo; const alteredMeta = view5.meta; return Object.fromEntries( Object.entries({ name: json2.views[nameWithSchema].name, schema: json2.views[nameWithSchema].schema, // pg deletedWithOption, addedWithOption, deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0, addedWith: Object.keys(addedWith).length ? addedWith : void 0, alteredWith: Object.keys(alterWith).length ? alterWith : void 0, alteredSchema, alteredTablespace, alteredUsing, // mysql alteredMeta, // common alteredDefinition, alteredExisting }).filter(([_3, value]) => value !== void 0) ); } ); const alteredTablesWithColumns = Object.values(difference.tables).map( (table6) => { return findAlternationsInTable(table6); } ); return { alteredTablesWithColumns, alteredEnums, alteredSequences, alteredRoles, alteredViews, alteredPolicies }; } var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn; var init_jsonDiffer = __esm({ "src/jsonDiffer.js"() { "use strict"; "use-strict"; import_json_diff = __toESM(require_lib()); mapArraysDiff = (source, diff2) => { const sequence = []; let sourceIndex = 0; for (let i6 = 0; i6 < diff2.length; i6++) { const it = diff2[i6]; if (it.length === 1) { sequence.push({ type: "same", value: source[sourceIndex] }); sourceIndex += 1; } else { if (it[0] === "-") { sequence.push({ type: "removed", value: it[1] }); } else { sequence.push({ type: "added", value: it[1], before: "" }); } } } const result = sequence.reverse().reduce( (acc, it) => { if (it.type === "same") { acc.prev = it.value; } if (it.type === "added" && acc.prev) { it.before = acc.prev; } acc.result.push(it); return acc; }, { result: [] } ); return result.result.reverse(); }; findAlternationsInTable = (table6) => { const columns = table6.columns ?? {}; const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => { return { name: it, ...columns[it] }; }); const deletedIndexes = Object.fromEntries( Object.entries(table6.indexes__deleted || {}).concat( Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedIndexes = Object.fromEntries( Object.entries(table6.indexes__added || {}).concat( Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredIndexes = Object.fromEntries( Object.entries(table6.indexes || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const deletedPolicies = Object.fromEntries( Object.entries(table6.policies__deleted || {}).concat( Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedPolicies = Object.fromEntries( Object.entries(table6.policies__added || {}).concat( Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredPolicies = Object.fromEntries( Object.entries(table6.policies || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const deletedForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys__deleted || {}).concat( Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys__added || {}).concat( Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys || {}).filter( (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted") ).map((entry) => [entry[0], entry[1]]) ); const addedCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const addedUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const addedCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean); return { name: table6.name, schema: table6.schema || "", altered: mappedAltered, addedIndexes, deletedIndexes, alteredIndexes, addedForeignKeys, deletedForeignKeys, alteredForeignKeys, addedCompositePKs, deletedCompositePKs, alteredCompositePKs, addedUniqueConstraints, deletedUniqueConstraints, alteredUniqueConstraints, deletedPolicies, addedPolicies, alteredPolicies, addedCheckConstraints, deletedCheckConstraints, alteredCheckConstraints }; }; alternationsInColumn = (column6) => { const altered = [column6]; const result = altered.filter((it) => { if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) { return false; } return true; }).map((it) => { if (typeof it.name !== "string" && "__old" in it.name) { return { ...it, name: { type: "changed", old: it.name.__old, new: it.name.__new } }; } return it; }).map((it) => { if ("type" in it) { return { ...it, type: { type: "changed", old: it.type.__old, new: it.type.__new } }; } return it; }).map((it) => { if ("default" in it) { return { ...it, default: { type: "changed", old: it.default.__old, new: it.default.__new } }; } if ("default__added" in it) { const { default__added, ...others } = it; return { ...others, default: { type: "added", value: it.default__added } }; } if ("default__deleted" in it) { const { default__deleted, ...others } = it; return { ...others, default: { type: "deleted", value: it.default__deleted } }; } return it; }).map((it) => { if ("generated" in it) { if ("as" in it.generated && "type" in it.generated) { return { ...it, generated: { type: "changed", old: { as: it.generated.as.__old, type: it.generated.type.__old }, new: { as: it.generated.as.__new, type: it.generated.type.__new } } }; } else if ("as" in it.generated) { return { ...it, generated: { type: "changed", old: { as: it.generated.as.__old }, new: { as: it.generated.as.__new } } }; } else { return { ...it, generated: { type: "changed", old: { as: it.generated.type.__old }, new: { as: it.generated.type.__new } } }; } } if ("generated__added" in it) { const { generated__added, ...others } = it; return { ...others, generated: { type: "added", value: it.generated__added } }; } if ("generated__deleted" in it) { const { generated__deleted, ...others } = it; return { ...others, generated: { type: "deleted", value: it.generated__deleted } }; } return it; }).map((it) => { if ("identity" in it) { return { ...it, identity: { type: "changed", old: it.identity.__old, new: it.identity.__new } }; } if ("identity__added" in it) { const { identity__added, ...others } = it; return { ...others, identity: { type: "added", value: it.identity__added } }; } if ("identity__deleted" in it) { const { identity__deleted, ...others } = it; return { ...others, identity: { type: "deleted", value: it.identity__deleted } }; } return it; }).map((it) => { if ("notNull" in it) { return { ...it, notNull: { type: "changed", old: it.notNull.__old, new: it.notNull.__new } }; } if ("notNull__added" in it) { const { notNull__added, ...others } = it; return { ...others, notNull: { type: "added", value: it.notNull__added } }; } if ("notNull__deleted" in it) { const { notNull__deleted, ...others } = it; return { ...others, notNull: { type: "deleted", value: it.notNull__deleted } }; } return it; }).map((it) => { if ("primaryKey" in it) { return { ...it, primaryKey: { type: "changed", old: it.primaryKey.__old, new: it.primaryKey.__new } }; } if ("primaryKey__added" in it) { const { notNull__added, ...others } = it; return { ...others, primaryKey: { type: "added", value: it.primaryKey__added } }; } if ("primaryKey__deleted" in it) { const { notNull__deleted, ...others } = it; return { ...others, primaryKey: { type: "deleted", value: it.primaryKey__deleted } }; } return it; }).map((it) => { if ("typeSchema" in it) { return { ...it, typeSchema: { type: "changed", old: it.typeSchema.__old, new: it.typeSchema.__new } }; } if ("typeSchema__added" in it) { const { typeSchema__added, ...others } = it; return { ...others, typeSchema: { type: "added", value: it.typeSchema__added } }; } if ("typeSchema__deleted" in it) { const { typeSchema__deleted, ...others } = it; return { ...others, typeSchema: { type: "deleted", value: it.typeSchema__deleted } }; } return it; }).map((it) => { if ("onUpdate" in it) { return { ...it, onUpdate: { type: "changed", old: it.onUpdate.__old, new: it.onUpdate.__new } }; } if ("onUpdate__added" in it) { const { onUpdate__added, ...others } = it; return { ...others, onUpdate: { type: "added", value: it.onUpdate__added } }; } if ("onUpdate__deleted" in it) { const { onUpdate__deleted, ...others } = it; return { ...others, onUpdate: { type: "deleted", value: it.onUpdate__deleted } }; } return it; }).map((it) => { if ("autoincrement" in it) { return { ...it, autoincrement: { type: "changed", old: it.autoincrement.__old, new: it.autoincrement.__new } }; } if ("autoincrement__added" in it) { const { autoincrement__added, ...others } = it; return { ...others, autoincrement: { type: "added", value: it.autoincrement__added } }; } if ("autoincrement__deleted" in it) { const { autoincrement__deleted, ...others } = it; return { ...others, autoincrement: { type: "deleted", value: it.autoincrement__deleted } }; } return it; }).map((it) => { if ("" in it) { return { ...it, autoincrement: { type: "changed", old: it.autoincrement.__old, new: it.autoincrement.__new } }; } if ("autoincrement__added" in it) { const { autoincrement__added, ...others } = it; return { ...others, autoincrement: { type: "added", value: it.autoincrement__added } }; } if ("autoincrement__deleted" in it) { const { autoincrement__deleted, ...others } = it; return { ...others, autoincrement: { type: "deleted", value: it.autoincrement__deleted } }; } return it; }).filter(Boolean); return result[0]; }; } }); // src/sqlgenerator.ts function fromJson(statements, dialect6, action, json2) { const result = statements.flatMap((statement) => { const filtered = convertors.filter((it) => { return it.can(statement, dialect6); }); const convertor = filtered.length === 1 ? filtered[0] : void 0; if (!convertor) { return ""; } return convertor.convert(statement, json2, action); }).filter((it) => it !== ""); return result; } var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors; var init_sqlgenerator = __esm({ "src/sqlgenerator.ts"() { "use strict"; init_migrate(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); init_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", "halfvec", "sparsevec", "bit" ]; const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join(""); const withoutArrayDefinition = type.replace(arrayDefinitionRegex, ""); return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`; }; Convertor = class { }; PgCreateRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_role" && dialect6 === "postgresql"; } convert(statement) { return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`; } }; PgDropRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_role" && dialect6 === "postgresql"; } convert(statement) { return `DROP ROLE "${statement.name}";`; } }; PgRenameRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_role" && dialect6 === "postgresql"; } convert(statement) { return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`; } }; PgAlterRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_role" && dialect6 === "postgresql"; } convert(statement) { return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`; } }; PgCreatePolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_policy" && dialect6 === "postgresql"; } convert(statement) { const policy5 = statement.data; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; const usingPart = policy5.using ? ` USING (${policy5.using})` : ""; const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : ""; const policyToPart = policy5.to?.map( (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"` ).join(", "); return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`; } }; PgDropPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_policy" && dialect6 === "postgresql"; } convert(statement) { const policy5 = statement.data; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`; } }; PgRenamePolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_policy" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`; } }; PgAlterPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_policy" && dialect6 === "postgresql"; } convert(statement, _dialect, action) { const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : ""; const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : ""; return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`; } }; PgCreateIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_ind_policy" && dialect6 === "postgresql"; } convert(statement) { const policy5 = statement.data; const usingPart = policy5.using ? ` USING (${policy5.using})` : ""; const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : ""; const policyToPart = policy5.to?.map( (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"` ).join(", "); return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`; } }; PgDropIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_ind_policy" && dialect6 === "postgresql"; } convert(statement) { const policy5 = statement.data; return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`; } }; PgRenameIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_ind_policy" && dialect6 === "postgresql"; } convert(statement) { return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`; } }; PgAlterIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_ind_policy" && dialect6 === "postgresql"; } convert(statement) { const newPolicy = statement.newData; const oldPolicy = statement.oldData; const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : ""; const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : ""; return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`; } }; PgEnableRlsConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "enable_rls" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`; } }; PgDisableRlsConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "disable_rls" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`; } }; PgCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "postgresql"; } convert(st) { const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st; let statement = ""; const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; statement += `CREATE TABLE ${name} ( `; for (let i6 = 0; i6 < columns.length; i6++) { const column6 = columns[i6]; const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column6.notNull && !column6.identity ? " NOT NULL" : ""; const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""; const uniqueConstraint6 = column6.isUnique ? ` CONSTRAINT "${column6.uniqueName}" UNIQUE${column6.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : ""; const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : ""; const type = parseType(schemaPrefix, column6.type); const generated = column6.generated; const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : ""; const unsquashedIdentity = column6.identity ? PgSquasher.unsquashIdentity(column6.identity) : void 0; const identityWithSchema = schema6 ? `"${schema6}"."${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 += ` "${column6.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`; statement += i6 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6); statement += ` CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`; } } if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) { for (const checkConstraint5 of checkConstraints) { statement += ",\n"; const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5); statement += ` CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`; } } statement += ` );`; statement += ` `; const enableRls = new PgEnableRlsConvertor().convert({ type: "enable_rls", tableName, schema: schema6 }); return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []]; } }; MySqlCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "mysql"; } convert(st) { const { tableName, columns, schema: schema6, checkConstraints, compositePKs, uniqueConstraints, internals } = st; let statement = ""; statement += `CREATE TABLE \`${tableName}\` ( `; for (let i6 = 0; i6 < columns.length; i6++) { const column6 = columns[i6]; const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column6.notNull ? " NOT NULL" : ""; const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""; const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : ""; const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : ""; statement += ` \`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`; statement += i6 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6); const uniqueString = unsquashedUnique.columns.map((it) => { 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 checkConstraint5 of checkConstraints) { statement += ",\n"; const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5); statement += ` CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`; } } statement += ` );`; statement += ` `; return statement; } }; SingleStoreCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "singlestore"; } convert(st) { const { tableName, columns, schema: schema6, compositePKs, uniqueConstraints, internals } = st; let statement = ""; statement += `CREATE TABLE \`${tableName}\` ( `; for (let i6 = 0; i6 < columns.length; i6++) { const column6 = columns[i6]; const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column6.notNull ? " NOT NULL" : ""; const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""; const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : ""; const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : ""; statement += ` \`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`; statement += i6 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6); const uniqueString = unsquashedUnique.columns.map((it) => { return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``; }).join(","); statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`; } } statement += ` );`; statement += ` `; return statement; } }; SQLiteCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(st) { const { tableName, columns, referenceData, compositePKs, uniqueConstraints, checkConstraints } = st; let statement = ""; statement += `CREATE TABLE \`${tableName}\` ( `; for (let i6 = 0; i6 < columns.length; i6++) { const column6 = columns[i6]; const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column6.notNull ? " NOT NULL" : ""; const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""; const autoincrementStatement = column6.autoincrement ? " AUTOINCREMENT" : ""; const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS ${column6.generated.as} ${column6.generated.type.toUpperCase()}` : ""; statement += " "; statement += `\`${column6.name}\` ${column6.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`; statement += i6 === columns.length - 1 ? "" : ",\n"; } compositePKs.forEach((it) => { statement += ",\n "; statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`; }); for (let i6 = 0; i6 < referenceData.length; i6++) { const { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate } = referenceData[i6]; const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : ""; const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : ""; const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(","); const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(","); statement += ","; statement += "\n "; statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6); statement += ` CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`; } } if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) { for (const check of checkConstraints) { statement += ",\n"; const { value, name } = SQLiteSquasher.unsquashCheck(check); statement += ` CONSTRAINT "${name}" CHECK(${value})`; } } statement += ` `; statement += `);`; statement += ` `; return statement; } }; PgCreateViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_view" && dialect6 === "postgresql"; } convert(st) { const { definition, name: viewName, schema: schema6, with: withOption, materialized, withNoData, tablespace, using } = st; const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`; let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`; if (using) statement += ` USING "${using}"`; const options = []; if (withOption) { statement += ` WITH (`; Object.entries(withOption).forEach(([key, value]) => { if (typeof value === "undefined") return; options.push(`${key.snake_case()} = ${value}`); }); statement += options.join(", "); statement += `)`; } if (tablespace) statement += ` TABLESPACE ${tablespace}`; statement += ` AS (${definition})`; if (withNoData) statement += ` WITH NO DATA`; statement += `;`; return statement; } }; MySqlCreateViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "mysql_create_view" && dialect6 === "mysql"; } convert(st) { const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st; let statement = `CREATE `; statement += replace ? `OR REPLACE ` : ""; statement += algorithm ? `ALGORITHM = ${algorithm} ` : ""; statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity} ` : ""; statement += `VIEW \`${name}\` AS (${definition})`; statement += withCheckOption ? ` WITH ${withCheckOption} CHECK OPTION` : ""; statement += ";"; return statement; } }; SqliteCreateViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(st) { const { definition, name } = st; return `CREATE VIEW \`${name}\` AS ${definition};`; } }; PgDropViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_view" && dialect6 === "postgresql"; } convert(st) { const { name: viewName, schema: schema6, materialized } = st; const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`; return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`; } }; MySqlDropViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_view" && dialect6 === "mysql"; } convert(st) { const { name } = st; return `DROP VIEW \`${name}\`;`; } }; SqliteDropViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(st) { const { name } = st; return `DROP VIEW \`${name}\`;`; } }; MySqlAlterViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_mysql_view" && dialect6 === "mysql"; } convert(st) { const { name, algorithm, definition, sqlSecurity, withCheckOption } = st; let statement = `ALTER `; statement += algorithm ? `ALGORITHM = ${algorithm} ` : ""; statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity} ` : ""; statement += `VIEW \`${name}\` AS ${definition}`; statement += withCheckOption ? ` WITH ${withCheckOption} CHECK OPTION` : ""; statement += ";"; return statement; } }; PgRenameViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_view" && dialect6 === "postgresql"; } convert(st) { const { nameFrom: from, nameTo: to, schema: schema6, materialized } = st; const nameFrom = `"${schema6}"."${from}"`; return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`; } }; MySqlRenameViewConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_view" && dialect6 === "mysql"; } convert(st) { const { nameFrom: from, nameTo: to } = st; return `RENAME TABLE \`${from}\` TO \`${to}\`;`; } }; PgAlterViewSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql"; } convert(st) { const { fromSchema, toSchema, name, materialized } = st; const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`; return statement; } }; PgAlterViewAddWithOptionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql"; } convert(st) { const { schema: schema6, with: withOption, name, materialized } = st; let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" SET (`; const options = []; Object.entries(withOption).forEach(([key, value]) => { options.push(`${key.snake_case()} = ${value}`); }); statement += options.join(", "); statement += `);`; return statement; } }; PgAlterViewDropWithOptionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql"; } convert(st) { const { schema: schema6, name, materialized, with: withOptions } = st; let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" RESET (`; const options = []; Object.entries(withOptions).forEach(([key, value]) => { options.push(`${key.snake_case()}`); }); statement += options.join(", "); statement += ");"; return statement; } }; PgAlterViewAlterTablespaceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql"; } convert(st) { const { schema: schema6, name, toTablespace } = st; const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET TABLESPACE ${toTablespace};`; return statement; } }; PgAlterViewAlterUsingConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_view_alter_using" && dialect6 === "postgresql"; } convert(st) { const { schema: schema6, name, toUsing } = st; const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET ACCESS METHOD "${toUsing}";`; return statement; } }; PgAlterTableAlterColumnSetGenerated = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql"; } convert(statement) { const { identity, tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const unsquashedIdentity = PgSquasher.unsquashIdentity(identity); const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`; const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : ""; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`; } }; PgAlterTableAlterColumnDropGenerated = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`; } }; PgAlterTableAlterColumnAlterGenerated = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql"; } convert(statement) { const { identity, oldIdentity, tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const unsquashedIdentity = PgSquasher.unsquashIdentity(identity); const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity); const statementsToReturn = []; if (unsquashedOldIdentity.type !== unsquashedIdentity.type) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};` ); } if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};` ); } if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};` ); } if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};` ); } if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};` ); } if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};` ); } if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) { statementsToReturn.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};` ); } return statementsToReturn; } }; PgAlterTableAddUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_unique_constraint" && dialect6 === "postgresql"; } convert(statement) { const unsquashed = PgSquasher.unsquashUnique(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`; } }; PgAlterTableDropUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_unique_constraint" && dialect6 === "postgresql"; } convert(statement) { const unsquashed = PgSquasher.unsquashUnique(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`; } }; PgAlterTableAddCheckConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_check_constraint" && dialect6 === "postgresql"; } convert(statement) { const unsquashed = PgSquasher.unsquashCheck(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`; } }; PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_check_constraint" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`; } }; MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_unique_constraint" && dialect6 === "mysql"; } convert(statement) { const unsquashed = MySqlSquasher.unsquashUnique(statement.data); return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`; } }; MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_unique_constraint" && dialect6 === "mysql"; } convert(statement) { const unsquashed = MySqlSquasher.unsquashUnique(statement.data); return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`; } }; MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_check_constraint" && dialect6 === "mysql"; } convert(statement) { const unsquashed = MySqlSquasher.unsquashCheck(statement.data); const { tableName } = statement; return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`; } }; SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_unique_constraint" && dialect6 === "singlestore"; } convert(statement) { const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data); return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`; } }; SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_unique_constraint" && dialect6 === "singlestore"; } convert(statement) { const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data); return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`; } }; MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_check_constraint" && dialect6 === "mysql"; } convert(statement) { const { tableName } = statement; return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`; } }; CreatePgSequenceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_sequence" && dialect6 === "postgresql"; } convert(st) { const { name, values, schema: schema6 } = st; const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`; } }; DropPgSequenceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_sequence" && dialect6 === "postgresql"; } convert(st) { const { name, schema: schema6 } = st; const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `DROP SEQUENCE ${sequenceWithSchema};`; } }; RenamePgSequenceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_sequence" && dialect6 === "postgresql"; } convert(st) { const { nameFrom, nameTo, schema: schema6 } = st; const sequenceWithSchemaFrom = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`; const sequenceWithSchemaTo = schema6 ? `"${schema6}"."${nameTo}"` : `"${nameTo}"`; return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`; } }; MovePgSequenceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "move_sequence" && dialect6 === "postgresql"; } convert(st) { const { schemaFrom, schemaTo, name } = st; const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`; const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`; return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`; } }; AlterPgSequenceConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_sequence" && dialect6 === "postgresql"; } convert(st) { const { name, schema: schema6, values } = st; const { increment, minValue, maxValue, startWith, cache: cache5, cycle } = values; const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache5 ? ` CACHE ${cache5}` : ""}${cycle ? ` CYCLE` : ""};`; } }; CreateTypeEnumConvertor = class extends Convertor { can(statement) { return statement.type === "create_type_enum"; } convert(st) { const { name, values, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; let valuesStatement = "("; valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", "); valuesStatement += ")"; let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`; return statement; } }; DropTypeEnumConvertor = class extends Convertor { can(statement) { return statement.type === "drop_type_enum"; } convert(st) { const { name, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; let statement = `DROP TYPE ${enumNameWithSchema};`; return statement; } }; AlterTypeAddValueConvertor = class extends Convertor { can(statement) { return statement.type === "alter_type_add_value"; } convert(st) { const { name, schema: schema6, value, before } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`; } }; AlterTypeSetSchemaConvertor = class extends Convertor { can(statement) { return statement.type === "move_type_enum"; } convert(st) { const { name, schemaFrom, schemaTo } = st; const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`; return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`; } }; AlterRenameTypeConvertor = class extends Convertor { can(statement) { return statement.type === "rename_type_enum"; } convert(st) { const { nameTo, nameFrom, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`; return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`; } }; AlterTypeDropValueConvertor = class extends Convertor { can(statement) { return statement.type === "alter_type_drop_value"; } convert(st) { const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st; const statements = []; for (const withEnum of columnsWithEnum) { const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`; statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;` ); if (withEnum.default) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;` ); } } statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" })); statements.push(new CreateTypeEnumConvertor().convert({ name, schema: enumSchema4, values: newValues, type: "create_type_enum" })); for (const withEnum of columnsWithEnum) { const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`; const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType); if (withEnum.default) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};` ); } statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};` ); } return statements; } }; PgDropTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_table" && dialect6 === "postgresql"; } convert(statement, _d2, action) { const { tableName, schema: schema6, policies } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const dropPolicyConvertor = new PgDropPolicyConvertor(); const droppedPolicies = policies?.map((p5) => { return dropPolicyConvertor.convert({ type: "drop_policy", tableName, data: action === "push" ? PgSquasher.unsquashPolicyPush(p5) : PgSquasher.unsquashPolicy(p5), schema: schema6 }); }) ?? []; return [ ...droppedPolicies, `DROP TABLE ${tableNameWithSchema} CASCADE;` ]; } }; MySQLDropTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_table" && dialect6 === "mysql"; } convert(statement) { const { tableName } = statement; return `DROP TABLE \`${tableName}\`;`; } }; SingleStoreDropTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_table" && dialect6 === "singlestore"; } convert(statement) { const { tableName } = statement; return `DROP TABLE \`${tableName}\`;`; } }; SQLiteDropTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName } = statement; return `DROP TABLE \`${tableName}\`;`; } }; PgRenameTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_table" && dialect6 === "postgresql"; } convert(statement) { const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement; const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`; const to = `"${tableNameTo}"`; return `ALTER TABLE ${from} RENAME TO ${to};`; } }; SqliteRenameTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableNameFrom, tableNameTo } = statement; return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`; } }; MySqlRenameTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_table" && dialect6 === "mysql"; } convert(statement) { const { tableNameFrom, tableNameTo } = statement; return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`; } }; SingleStoreRenameTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_table" && dialect6 === "singlestore"; } convert(statement) { const { tableNameFrom, tableNameTo } = statement; return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`; } }; PgAlterTableRenameColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_rename_column" && dialect6 === "postgresql"; } convert(statement) { const { tableName, oldColumnName, newColumnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`; } }; MySqlAlterTableRenameColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_rename_column" && dialect6 === "mysql"; } convert(statement) { const { tableName, oldColumnName, newColumnName } = statement; return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`; } }; SingleStoreAlterTableRenameColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_rename_column" && dialect6 === "singlestore"; } convert(statement) { const { tableName, oldColumnName, newColumnName } = statement; return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`; } }; SQLiteAlterTableRenameColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, oldColumnName, newColumnName } = statement; return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`; } }; PgAlterTableDropColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_drop_column" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`; } }; MySqlAlterTableDropColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_drop_column" && dialect6 === "mysql"; } convert(statement) { const { tableName, columnName } = statement; return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`; } }; SingleStoreAlterTableDropColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_drop_column" && dialect6 === "singlestore"; } convert(statement) { const { tableName, columnName } = statement; return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`; } }; SQLiteAlterTableDropColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName } = statement; return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`; } }; PgAlterTableAddColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_add_column" && dialect6 === "postgresql"; } convert(statement) { const { tableName, column: column6, schema: schema6 } = statement; const { name, type, notNull, generated, primaryKey, identity } = column6; const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : ""; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`; const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : ""; const fixedType = parseType(schemaPrefix, column6.type); const notNullStatement = `${notNull ? " NOT NULL" : ""}`; const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0; const identityWithSchema = schema6 ? `"${schema6}"."${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 "${name}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`; } }; MySqlAlterTableAddColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_add_column" && dialect6 === "mysql"; } convert(statement) { const { tableName, column: column6 } = statement; const { name, type, notNull, primaryKey, autoincrement, onUpdate, generated } = column6; const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.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 \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`; } }; SingleStoreAlterTableAddColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_add_column" && dialect6 === "singlestore"; } convert(statement) { const { tableName, column: column6 } = statement; const { name, type, notNull, primaryKey, autoincrement, onUpdate, generated } = column6; const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.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 \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`; } }; SQLiteAlterTableAddColumnConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, column: column6, referenceData } = statement; const { name, type, notNull, primaryKey, generated } = column6; const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`; const notNullStatement = `${notNull ? " NOT NULL" : ""}`; const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`; const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0; const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`; const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : ""; return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`; } }; PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const statements = []; const type = parseType(`"${typeSchema}".`, newDataType.name); if (!oldDataType.isEnum && !newDataType.isEnum) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};` ); if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } } if (oldDataType.isEnum && !newDataType.isEnum) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};` ); if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } } if (!oldDataType.isEnum && newDataType.isEnum) { if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};` ); } statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};` ); } if (oldDataType.isEnum && newDataType.isEnum) { const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`; if (newDataType.name !== oldDataType.name && columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`, alterType, `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } else { statements.push(alterType); } } return statements; } }; PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`; } }; PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`; } }; PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`; } }; PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`, addColumnStatement ]; } }; PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`, addColumnStatement ]; } }; SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated, columnNotNull } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull: columnNotNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull: columnNotNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``; const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`, addColumnStatement ]; } }; MySqlAlterTableAddPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`; } }; MySqlAlterTableDropPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`; } }; LibSQLModifyColumn = class extends Convertor { can(statement, dialect6) { return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso"; } convert(statement, json2) { const { tableName, columnName } = statement; let columnType = ``; let columnDefault = ""; let columnNotNull = ""; const sqlStatements = []; const indexes = []; for (const table6 of Object.values(json2.tables)) { for (const index6 of Object.values(table6.indexes)) { const unsquashed = SQLiteSquasher.unsquashIdx(index6); sqlStatements.push(`DROP INDEX "${unsquashed.name}";`); indexes.push({ ...unsquashed, tableName: table6.name }); } } switch (statement.type) { case "alter_table_alter_column_set_type": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; case "alter_table_alter_column_drop_notnull": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = ""; break; case "alter_table_alter_column_set_notnull": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = ` NOT NULL`; break; case "alter_table_alter_column_set_default": columnType = ` ${statement.newDataType}`; columnDefault = ` DEFAULT ${statement.newDefaultValue}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; case "alter_table_alter_column_drop_default": columnType = ` ${statement.newDataType}`; columnDefault = ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; } columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault; sqlStatements.push( `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};` ); for (const index6 of indexes) { const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX"; const whereStatement = index6.where ? ` WHERE ${index6.where}` : ""; const uniqueString = index6.columns.map((it) => `\`${it}\``).join(","); const tableName2 = index6.tableName; sqlStatements.push( `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};` ); } return sqlStatements; } }; MySqlModifyColumn = class extends Convertor { can(statement, dialect6) { return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql"; } convert(statement) { const { tableName, columnName } = statement; let columnType = ``; let columnDefault = ""; let columnNotNull = ""; let columnOnUpdate = ""; let columnAutoincrement = ""; let primaryKey = statement.columnPk ? " PRIMARY KEY" : ""; let columnGenerated = ""; if (statement.type === "alter_table_alter_column_drop_notnull") { columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_notnull") { columnNotNull = ` NOT NULL`; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_drop_on_update") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnOnUpdate = ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_on_update") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_autoincrement") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = " AUTO_INCREMENT"; } else if (statement.type === "alter_table_alter_column_drop_autoincrement") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = ""; } else if (statement.type === "alter_table_alter_column_set_default") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = ` DEFAULT ${statement.newDefaultValue}`; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_drop_default") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_generated") { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; if (statement.columnGenerated?.type === "virtual") { return [ new MySqlAlterTableDropColumnConvertor().convert({ type: "alter_table_drop_column", tableName: statement.tableName, columnName: statement.columnName, schema: statement.schema }), new MySqlAlterTableAddColumnConvertor().convert({ tableName, column: { name: columnName, type: statement.newDataType, notNull: statement.columnNotNull, default: statement.columnDefault, onUpdate: statement.columnOnUpdate, autoincrement: statement.columnAutoIncrement, primaryKey: statement.columnPk, generated: statement.columnGenerated }, schema: statement.schema, type: "alter_table_add_column" }) ]; } else { columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : ""; } } else if (statement.type === "alter_table_alter_column_drop_generated") { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; if (statement.oldColumn?.generated?.type === "virtual") { return [ new MySqlAlterTableDropColumnConvertor().convert({ type: "alter_table_drop_column", tableName: statement.tableName, columnName: statement.columnName, schema: statement.schema }), new MySqlAlterTableAddColumnConvertor().convert({ tableName, column: { name: columnName, type: statement.newDataType, notNull: statement.columnNotNull, default: statement.columnDefault, onUpdate: statement.columnOnUpdate, autoincrement: statement.columnAutoIncrement, primaryKey: statement.columnPk, generated: statement.columnGenerated }, schema: statement.schema, type: "alter_table_add_column" }) ]; } } else { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : ""; } columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault; return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`; } }; SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``; const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`, addColumnStatement ]; } }; SingleStoreAlterTableAddPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`; } }; SingleStoreAlterTableDropPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`; } }; SingleStoreModifyColumn = class extends Convertor { can(statement, dialect6) { return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore"; } convert(statement) { const { tableName, columnName } = statement; let columnType = ``; let columnDefault = ""; let columnNotNull = ""; let columnOnUpdate = ""; let columnAutoincrement = ""; let primaryKey = statement.columnPk ? " PRIMARY KEY" : ""; let columnGenerated = ""; if (statement.type === "alter_table_alter_column_drop_notnull") { columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_notnull") { columnNotNull = ` NOT NULL`; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_drop_on_update") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnOnUpdate = ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_on_update") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_autoincrement") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = " AUTO_INCREMENT"; } else if (statement.type === "alter_table_alter_column_drop_autoincrement") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = ""; } else if (statement.type === "alter_table_alter_column_set_default") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = ` DEFAULT ${statement.newDefaultValue}`; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_drop_default") { columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnType = ` ${statement.newDataType}`; columnDefault = ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; } else if (statement.type === "alter_table_alter_column_set_generated") { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; if (statement.columnGenerated?.type === "virtual") { return [ new SingleStoreAlterTableDropColumnConvertor().convert({ type: "alter_table_drop_column", tableName: statement.tableName, columnName: statement.columnName, schema: statement.schema }), new SingleStoreAlterTableAddColumnConvertor().convert({ tableName, column: { name: columnName, type: statement.newDataType, notNull: statement.columnNotNull, default: statement.columnDefault, onUpdate: statement.columnOnUpdate, autoincrement: statement.columnAutoIncrement, primaryKey: statement.columnPk, generated: statement.columnGenerated }, schema: statement.schema, type: "alter_table_add_column" }) ]; } else { columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : ""; } } else if (statement.type === "alter_table_alter_column_drop_generated") { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; if (statement.oldColumn?.generated?.type === "virtual") { return [ new SingleStoreAlterTableDropColumnConvertor().convert({ type: "alter_table_drop_column", tableName: statement.tableName, columnName: statement.columnName, schema: statement.schema }), new SingleStoreAlterTableAddColumnConvertor().convert({ tableName, column: { name: columnName, type: statement.newDataType, notNull: statement.columnNotNull, default: statement.columnDefault, onUpdate: statement.columnOnUpdate, autoincrement: statement.columnAutoIncrement, primaryKey: statement.columnPk, generated: statement.columnGenerated }, schema: statement.schema, type: "alter_table_add_column" }) ]; } } else { columnType = ` ${statement.newDataType}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : ""; columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : ""; } columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault; return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`; } }; PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_composite_pk" && dialect6 === "postgresql"; } convert(statement) { const { name, columns } = PgSquasher.unsquashPK(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`; } }; PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_composite_pk" && dialect6 === "postgresql"; } convert(statement) { const { name, columns } = PgSquasher.unsquashPK(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`; } }; PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_composite_pk" && dialect6 === "postgresql"; } convert(statement) { const { name, columns } = PgSquasher.unsquashPK(statement.old); const { name: newName, columns: newColumns } = PgSquasher.unsquashPK( statement.new ); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}"; ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`; } }; MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_composite_pk" && dialect6 === "mysql"; } convert(statement) { const { name, columns } = MySqlSquasher.unsquashPK(statement.data); return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`; } }; MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_composite_pk" && dialect6 === "mysql"; } convert(statement) { const { name, columns } = MySqlSquasher.unsquashPK(statement.data); return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`; } }; MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_composite_pk" && dialect6 === "mysql"; } convert(statement) { const { name, columns } = MySqlSquasher.unsquashPK(statement.old); const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK( statement.new ); return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`; } }; PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName } = statement; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`; } }; PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; return `/* Unfortunately in current drizzle-kit version we can't automatically get name for primary key. We are working on making it available! Meanwhile you can: 1. Check pk name in your database, by running SELECT constraint_name FROM information_schema.table_constraints WHERE table_schema = '${typeof schema6 === "undefined" || schema6 === "" ? "public" : schema6}' AND table_name = '${tableName}' AND constraint_type = 'PRIMARY KEY'; 2. Uncomment code below and paste pk name manually Hope to release this update as soon as possible */ -- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`; } }; PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName } = statement; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`; } }; PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName } = statement; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`; } }; PgCreateForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_reference" && dialect6 === "postgresql"; } convert(statement) { const { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate, schemaTo } = PgSquasher.unsquashFK(statement.data); const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : ""; const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : ""; const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(","); const toColumnsString = columnsTo.map((it) => `"${it}"`).join(","); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`; const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`; const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`; return alterStatement; } }; LibSQLCreateForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_reference" && dialect6 === "turso"; } convert(statement, json2, action) { const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data); const { columnDefault, columnNotNull, columnType } = statement; const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : ""; const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : ""; const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : ""; const columnNotNullValue = columnNotNull ? ` NOT NULL` : ""; const columnTypeValue = columnType ? ` ${columnType}` : ""; const columnFrom = columnsFrom[0]; const columnTo = columnsTo[0]; return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`; } }; MySqlCreateForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_reference" && dialect6 === "mysql"; } convert(statement) { const { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate } = MySqlSquasher.unsquashFK(statement.data); const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : ""; const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : ""; const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(","); const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(","); return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`; } }; PgAlterForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_reference" && dialect6 === "postgresql"; } convert(statement) { const newFk = PgSquasher.unsquashFK(statement.data); const oldFk = PgSquasher.unsquashFK(statement.oldFkey); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`; let sql = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}"; `; const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : ""; const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : ""; const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(","); const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(","); const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`; const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`; const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`; sql += alterStatement; return sql; } }; PgDeleteForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_reference" && dialect6 === "postgresql"; } convert(statement) { const tableFrom = statement.tableName; const { name } = PgSquasher.unsquashFK(statement.data); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`; return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}"; `; } }; MySqlDeleteForeignKeyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "delete_reference" && dialect6 === "mysql"; } convert(statement) { const tableFrom = statement.tableName; const { name } = MySqlSquasher.unsquashFK(statement.data); return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name}\`; `; } }; CreatePgIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_index_pg" && dialect6 === "postgresql"; } convert(statement) { const { name, columns, isUnique, concurrently, with: withMap, method, where } = statement.data; const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX"; const value = columns.map( (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}` ).join(","); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; function reverseLogic(mappedWith) { let reversedString = ""; for (const key in mappedWith) { if (mappedWith.hasOwnProperty(key)) { reversedString += `${key}=${mappedWith[key]},`; } } reversedString = reversedString.slice(0, -1); return reversedString; } return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`; } }; CreateMySqlIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_index" && dialect6 === "mysql"; } convert(statement) { const { name, columns, isUnique } = MySqlSquasher.unsquashIdx( statement.data ); const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX"; const uniqueString = columns.map((it) => { return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``; }).join(","); return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`; } }; CreateSingleStoreIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_index" && dialect6 === "singlestore"; } convert(statement) { const { name, columns, isUnique } = SingleStoreSquasher.unsquashIdx( statement.data ); const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX"; const uniqueString = columns.map((it) => { return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``; }).join(","); return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`; } }; CreateSqliteIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { name, columns, isUnique, where } = SQLiteSquasher.unsquashIdx( statement.data ); const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX"; const whereStatement = where ? ` WHERE ${where}` : ""; const uniqueString = columns.map((it) => { return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``; }).join(","); return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`; } }; PgDropIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_index" && dialect6 === "postgresql"; } convert(statement) { const { schema: schema6 } = statement; const { name } = PgSquasher.unsquashIdx(statement.data); const indexNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `DROP INDEX ${indexNameWithSchema};`; } }; PgCreateSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_schema" && dialect6 === "postgresql"; } convert(statement) { const { name } = statement; return `CREATE SCHEMA "${name}"; `; } }; PgRenameSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_schema" && dialect6 === "postgresql"; } convert(statement) { const { from, to } = statement; return `ALTER SCHEMA "${from}" RENAME TO "${to}"; `; } }; PgDropSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_schema" && dialect6 === "postgresql"; } convert(statement) { const { name } = statement; return `DROP SCHEMA "${name}"; `; } }; PgAlterTableSetSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_set_schema" && dialect6 === "postgresql"; } convert(statement) { const { tableName, schemaFrom, schemaTo } = statement; return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}"; `; } }; PgAlterTableSetNewSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql"; } convert(statement) { const { tableName, to, from } = statement; const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}"; `; } }; PgAlterTableRemoveFromSchemaConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql"; } convert(statement) { const { tableName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public; `; } }; SqliteDropIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { name } = PgSquasher.unsquashIdx(statement.data); return `DROP INDEX \`${name}\`;`; } }; MySqlDropIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_index" && dialect6 === "mysql"; } convert(statement) { const { name } = MySqlSquasher.unsquashIdx(statement.data); return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`; } }; SingleStoreDropIndexConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_index" && dialect6 === "singlestore"; } convert(statement) { const { name } = SingleStoreSquasher.unsquashIdx(statement.data); return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`; } }; SQLiteRecreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "recreate_table" && dialect6 === "sqlite"; } convert(statement) { const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement; const columnNames = columns.map((it) => `"${it.name}"`).join(", "); const newTableName = `__new_${tableName}`; const sqlStatements = []; sqlStatements.push(`PRAGMA foreign_keys=OFF;`); const mappedCheckConstraints = checkConstraints.map( (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`) ); sqlStatements.push( new SQLiteCreateTableConvertor().convert({ type: "sqlite_create_table", tableName: newTableName, columns, referenceData, compositePKs, checkConstraints: mappedCheckConstraints }) ); sqlStatements.push( `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;` ); sqlStatements.push( new SQLiteDropTableConvertor().convert({ type: "drop_table", tableName, schema: "" }) ); sqlStatements.push( new SqliteRenameTableConvertor().convert({ fromSchema: "", tableNameFrom: newTableName, tableNameTo: tableName, toSchema: "", type: "rename_table" }) ); sqlStatements.push(`PRAGMA foreign_keys=ON;`); return sqlStatements; } }; LibSQLRecreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "recreate_table" && dialect6 === "turso"; } convert(statement) { const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement; const columnNames = columns.map((it) => `"${it.name}"`).join(", "); const newTableName = `__new_${tableName}`; const sqlStatements = []; const mappedCheckConstraints = checkConstraints.map( (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`) ); sqlStatements.push(`PRAGMA foreign_keys=OFF;`); sqlStatements.push( new SQLiteCreateTableConvertor().convert({ type: "sqlite_create_table", tableName: newTableName, columns, referenceData, compositePKs, checkConstraints: mappedCheckConstraints }) ); sqlStatements.push( `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;` ); sqlStatements.push( new SQLiteDropTableConvertor().convert({ type: "drop_table", tableName, schema: "" }) ); sqlStatements.push( new SqliteRenameTableConvertor().convert({ fromSchema: "", tableNameFrom: newTableName, tableNameTo: tableName, toSchema: "", type: "rename_table" }) ); sqlStatements.push(`PRAGMA foreign_keys=ON;`); return sqlStatements; } }; SingleStoreRecreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore"; } convert(statement) { const { tableName, columns, compositePKs, uniqueConstraints } = statement; const columnNames = columns.map((it) => `\`${it.name}\``).join(", "); const newTableName = `__new_${tableName}`; const sqlStatements = []; sqlStatements.push( new SingleStoreCreateTableConvertor().convert({ type: "create_table", tableName: newTableName, columns, compositePKs, uniqueConstraints, schema: "" }) ); sqlStatements.push( `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;` ); sqlStatements.push( new SingleStoreDropTableConvertor().convert({ type: "drop_table", tableName, schema: "" }) ); sqlStatements.push( new SingleStoreRenameTableConvertor().convert({ fromSchema: "", tableNameFrom: newTableName, tableNameTo: tableName, toSchema: "", type: "rename_table" }) ); return sqlStatements; } }; convertors = []; convertors.push(new PgCreateTableConvertor()); convertors.push(new MySqlCreateTableConvertor()); convertors.push(new SingleStoreCreateTableConvertor()); convertors.push(new SingleStoreRecreateTableConvertor()); convertors.push(new SQLiteCreateTableConvertor()); convertors.push(new SQLiteRecreateTableConvertor()); convertors.push(new LibSQLRecreateTableConvertor()); convertors.push(new PgCreateViewConvertor()); convertors.push(new PgDropViewConvertor()); convertors.push(new PgRenameViewConvertor()); convertors.push(new PgAlterViewSchemaConvertor()); convertors.push(new PgAlterViewAddWithOptionConvertor()); convertors.push(new PgAlterViewDropWithOptionConvertor()); convertors.push(new PgAlterViewAlterTablespaceConvertor()); convertors.push(new PgAlterViewAlterUsingConvertor()); convertors.push(new MySqlCreateViewConvertor()); convertors.push(new MySqlDropViewConvertor()); convertors.push(new MySqlRenameViewConvertor()); convertors.push(new MySqlAlterViewConvertor()); convertors.push(new SqliteCreateViewConvertor()); convertors.push(new SqliteDropViewConvertor()); convertors.push(new CreateTypeEnumConvertor()); convertors.push(new DropTypeEnumConvertor()); convertors.push(new AlterTypeAddValueConvertor()); convertors.push(new AlterTypeSetSchemaConvertor()); convertors.push(new AlterRenameTypeConvertor()); convertors.push(new AlterTypeDropValueConvertor()); convertors.push(new CreatePgSequenceConvertor()); convertors.push(new DropPgSequenceConvertor()); convertors.push(new RenamePgSequenceConvertor()); convertors.push(new MovePgSequenceConvertor()); convertors.push(new AlterPgSequenceConvertor()); convertors.push(new PgDropTableConvertor()); convertors.push(new MySQLDropTableConvertor()); convertors.push(new SingleStoreDropTableConvertor()); convertors.push(new SQLiteDropTableConvertor()); convertors.push(new PgRenameTableConvertor()); convertors.push(new MySqlRenameTableConvertor()); convertors.push(new SingleStoreRenameTableConvertor()); convertors.push(new SqliteRenameTableConvertor()); convertors.push(new PgAlterTableRenameColumnConvertor()); convertors.push(new MySqlAlterTableRenameColumnConvertor()); convertors.push(new SingleStoreAlterTableRenameColumnConvertor()); convertors.push(new SQLiteAlterTableRenameColumnConvertor()); convertors.push(new PgAlterTableDropColumnConvertor()); convertors.push(new MySqlAlterTableDropColumnConvertor()); convertors.push(new SingleStoreAlterTableDropColumnConvertor()); convertors.push(new SQLiteAlterTableDropColumnConvertor()); convertors.push(new PgAlterTableAddColumnConvertor()); convertors.push(new MySqlAlterTableAddColumnConvertor()); convertors.push(new SingleStoreAlterTableAddColumnConvertor()); convertors.push(new SQLiteAlterTableAddColumnConvertor()); convertors.push(new PgAlterTableAlterColumnSetTypeConvertor()); convertors.push(new PgAlterTableAddUniqueConstraintConvertor()); convertors.push(new PgAlterTableDropUniqueConstraintConvertor()); convertors.push(new PgAlterTableAddCheckConstraintConvertor()); convertors.push(new PgAlterTableDeleteCheckConstraintConvertor()); convertors.push(new MySqlAlterTableAddCheckConstraintConvertor()); convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor()); convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor()); convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor()); convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor()); convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor()); convertors.push(new CreatePgIndexConvertor()); convertors.push(new CreateMySqlIndexConvertor()); convertors.push(new CreateSingleStoreIndexConvertor()); convertors.push(new CreateSqliteIndexConvertor()); convertors.push(new PgDropIndexConvertor()); convertors.push(new SqliteDropIndexConvertor()); convertors.push(new MySqlDropIndexConvertor()); convertors.push(new SingleStoreDropIndexConvertor()); convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor()); convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor()); convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor()); convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor()); convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor()); convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor()); convertors.push(new PgAlterPolicyConvertor()); convertors.push(new PgCreatePolicyConvertor()); convertors.push(new PgDropPolicyConvertor()); convertors.push(new PgRenamePolicyConvertor()); convertors.push(new PgAlterIndPolicyConvertor()); convertors.push(new PgCreateIndPolicyConvertor()); convertors.push(new PgDropIndPolicyConvertor()); convertors.push(new PgRenameIndPolicyConvertor()); convertors.push(new PgEnableRlsConvertor()); convertors.push(new PgDisableRlsConvertor()); convertors.push(new PgDropRoleConvertor()); convertors.push(new PgAlterRoleConvertor()); convertors.push(new PgCreateRoleConvertor()); convertors.push(new PgRenameRoleConvertor()); convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor()); convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor()); convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor()); convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor()); convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor()); convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor()); convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor()); convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor()); convertors.push(new MySqlModifyColumn()); convertors.push(new LibSQLModifyColumn()); convertors.push(new SingleStoreModifyColumn()); convertors.push(new PgCreateForeignKeyConvertor()); convertors.push(new MySqlCreateForeignKeyConvertor()); convertors.push(new PgAlterForeignKeyConvertor()); convertors.push(new PgDeleteForeignKeyConvertor()); convertors.push(new MySqlDeleteForeignKeyConvertor()); convertors.push(new PgCreateSchemaConvertor()); convertors.push(new PgRenameSchemaConvertor()); convertors.push(new PgDropSchemaConvertor()); convertors.push(new PgAlterTableSetSchemaConvertor()); convertors.push(new PgAlterTableSetNewSchemaConvertor()); convertors.push(new PgAlterTableRemoveFromSchemaConvertor()); convertors.push(new LibSQLCreateForeignKeyConvertor()); convertors.push(new PgAlterTableAlterColumnDropGenerated()); convertors.push(new PgAlterTableAlterColumnSetGenerated()); convertors.push(new PgAlterTableAlterColumnAlterGenerated()); convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor()); convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor()); convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor()); convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor()); convertors.push(new MySqlAlterTableDropPk()); convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor()); convertors.push(new MySqlAlterTableAddPk()); convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor()); convertors.push(new SingleStoreAlterTableDropPk()); convertors.push(new SingleStoreAlterTableAddPk()); https: ` create table users ( id int, name character varying(128) ); create type venum as enum('one', 'two', 'three'); alter table users add column typed venum; insert into users(id, name, typed) values (1, 'name1', 'one'); insert into users(id, name, typed) values (2, 'name2', 'two'); insert into users(id, name, typed) values (3, 'name3', 'three'); alter type venum rename to __venum; create type venum as enum ('one', 'two', 'three', 'four', 'five'); ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum; insert into users(id, name, typed) values (4, 'name4', 'four'); insert into users(id, name, typed) values (5, 'name5', 'five'); drop type __venum; `; } }); // src/cli/commands/sqlitePushUtils.ts var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn; var init_sqlitePushUtils = __esm({ "src/cli/commands/sqlitePushUtils.ts"() { "use strict"; init_source(); init_sqliteSchema(); init_sqlgenerator(); init_utils(); _moveDataStatements = (tableName, json, dataLoss = false) => { const statements = []; const newTableName = `__new_${tableName}`; const tableColumns = Object.values(json.tables[tableName].columns); const referenceData = Object.values(json.tables[tableName].foreignKeys); const compositePKs = Object.values( json.tables[tableName].compositePrimaryKeys ).map((it) => SQLiteSquasher.unsquashPK(it)); const checkConstraints = Object.values(json.tables[tableName].checkConstraints); const mappedCheckConstraints = checkConstraints.map( (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`) ); const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it)); statements.push( new SQLiteCreateTableConvertor().convert({ type: "sqlite_create_table", tableName: newTableName, columns: tableColumns, referenceData: fks, compositePKs, checkConstraints: mappedCheckConstraints }) ); if (!dataLoss) { const columns = Object.keys(json.tables[tableName].columns).map( (c5) => `"${c5}"` ); statements.push( `INSERT INTO \`${newTableName}\`(${columns.join( ", " )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;` ); } statements.push( new SQLiteDropTableConvertor().convert({ type: "drop_table", tableName, schema: "" }) ); statements.push( new SqliteRenameTableConvertor().convert({ fromSchema: "", tableNameFrom: newTableName, tableNameTo: tableName, toSchema: "", type: "rename_table" }) ); for (const idx of Object.values(json.tables[tableName].indexes)) { statements.push( new CreateSqliteIndexConvertor().convert({ type: "create_index", tableName, schema: "", data: idx }) ); } return statements; }; getOldTableName = (tableName, meta) => { for (const key of Object.keys(meta.tables)) { const value = meta.tables[key]; if (`"${tableName}"` === value) { return key.substring(1, key.length - 1); } } return tableName; }; getNewTableName = (tableName, meta) => { if (typeof meta.tables[`"${tableName}"`] !== "undefined") { return meta.tables[`"${tableName}"`].substring( 1, meta.tables[`"${tableName}"`].length - 1 ); } return tableName; }; logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => { let shouldAskForApprove = false; const statementsToExecute = []; const infoToPrint = []; const tablesToRemove = []; const columnsToRemove = []; const schemasToRemove = []; const tablesToTruncate = []; for (const statement of statements) { if (statement.type === "drop_table") { const res = await connection.query( `select count(*) as count from \`${statement.tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( statement.tableName )} table with ${count} items` ); tablesToRemove.push(statement.tableName); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "alter_table_drop_column") { const tableName = statement.tableName; const columnName = statement.columnName; const res = await connection.query( `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( columnName )} column in ${tableName} table with ${count} items` ); columnsToRemove.push(`${tableName}_${statement.columnName}`); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) { const tableName = statement.tableName; const columnName = statement.column.name; const res = await connection.query( `select count(*) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to add not-null ${source_default.underline( columnName )} column without default value, which contains ${count} items` ); tablesToTruncate.push(tableName); statementsToExecute.push(`delete from ${tableName};`); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "recreate_table") { const tableName = statement.tableName; const oldTableName = getOldTableName(tableName, meta); let dataLoss = false; const prevColumnNames = Object.keys(json1.tables[oldTableName].columns); const currentColumnNames = Object.keys(json2.tables[tableName].columns); const { removedColumns, addedColumns } = findAddedAndRemoved( prevColumnNames, currentColumnNames ); if (removedColumns.length) { for (const removedColumn of removedColumns) { const res = await connection.query( `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( removedColumn )} column in ${tableName} table with ${count} items` ); columnsToRemove.push(removedColumn); shouldAskForApprove = true; } } } if (addedColumns.length) { for (const addedColumn of addedColumns) { const [res] = await connection.query( `select count(*) as count from \`${tableName}\`` ); const columnConf = json2.tables[tableName].columns[addedColumn]; const count = Number(res.count); if (count > 0 && columnConf.notNull && !columnConf.default) { dataLoss = true; infoToPrint.push( `\xB7 You're about to add not-null ${source_default.underline( addedColumn )} column without default value to table, which contains ${count} items` ); shouldAskForApprove = true; tablesToTruncate.push(tableName); statementsToExecute.push(`DELETE FROM \`${tableName}\`;`); } } } const tablesReferencingCurrent = []; for (const table6 of Object.values(json2.tables)) { const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t6) => SQLiteSquasher.unsquashPushFK(t6).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom); tablesReferencingCurrent.push(...tablesRefs); } if (!tablesReferencingCurrent.length) { statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss)); continue; } const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`); if (pragmaState) { statementsToExecute.push(`PRAGMA foreign_keys=OFF;`); } statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss)); if (pragmaState) { statementsToExecute.push(`PRAGMA foreign_keys=ON;`); } } else { const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } } return { statementsToExecute, shouldAskForApprove, infoToPrint, columnsToRemove: [...new Set(columnsToRemove)], schemasToRemove: [...new Set(schemasToRemove)], tablesToTruncate: [...new Set(tablesToTruncate)], tablesToRemove: [...new Set(tablesToRemove)] }; }; } }); // src/jsonStatements.ts var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView; var init_jsonStatements = __esm({ "src/jsonStatements.ts"() { "use strict"; init_source(); init_sqlitePushUtils(); init_views(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); preparePgCreateTableJson = (table6, json2) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6; const tableKey2 = `${schema6 || "public"}.${name}`; const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : ""; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName, uniqueConstraints: Object.values(uniqueConstraints), policies: Object.values(policies), checkConstraints: Object.values(checkConstraints), isRLSEnabled: isRLSEnabled ?? false }; }; prepareMySqlCreateTableJson = (table6, json2, internals) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "", uniqueConstraints: Object.values(uniqueConstraints), internals, checkConstraints: Object.values(checkConstraints) }; }; prepareSingleStoreCreateTableJson = (table6, json2, internals) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "", uniqueConstraints: Object.values(uniqueConstraints), internals }; }; prepareSQLiteCreateTable = (table6, action) => { const { name, columns, uniqueConstraints, checkConstraints } = table6; const references2 = Object.values(table6.foreignKeys); const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); return { type: "sqlite_create_table", tableName: name, columns: Object.values(columns), referenceData: fks, compositePKs: composites, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) }; }; prepareDropTableJson = (table6) => { return { type: "drop_table", tableName: table6.name, schema: table6.schema, policies: table6.policies ? Object.values(table6.policies) : [] }; }; prepareRenameTableJson = (tableFrom, tableTo) => { return { type: "rename_table", fromSchema: tableTo.schema, toSchema: tableTo.schema, tableNameFrom: tableFrom.name, tableNameTo: tableTo.name }; }; prepareCreateEnumJson = (name, schema6, values) => { return { type: "create_type_enum", name, schema: schema6, values }; }; prepareAddValuesToEnumJson = (name, schema6, values) => { return values.map((it) => { return { type: "alter_type_add_value", name, schema: schema6, value: it.value, before: it.before }; }); }; prepareDropEnumValues = (name, schema6, removedValues, json2) => { if (!removedValues.length) return []; const affectedColumns = []; for (const tableKey2 in json2.tables) { const table6 = json2.tables[tableKey2]; for (const columnKey in table6.columns) { const column6 = table6.columns[columnKey]; const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const parsedColumnType = column6.type.replace(arrayDefinitionRegex, ""); if (parsedColumnType === name && column6.typeSchema === schema6) { affectedColumns.push({ tableSchema: table6.schema, table: table6.name, column: column6.name, columnType: column6.type, default: column6.default }); } } } return [{ type: "alter_type_drop_value", name, enumSchema: schema6, deletedValues: removedValues, newValues: json2.enums[`${schema6}.${name}`].values, columnsWithEnum: affectedColumns }]; }; prepareDropEnumJson = (name, schema6) => { return { type: "drop_type_enum", name, schema: schema6 }; }; prepareMoveEnumJson = (name, schemaFrom, schemaTo) => { return { type: "move_type_enum", name, schemaFrom, schemaTo }; }; prepareRenameEnumJson = (nameFrom, nameTo, schema6) => { return { type: "rename_type_enum", nameFrom, nameTo, schema: schema6 }; }; prepareCreateSequenceJson = (seq) => { const values = PgSquasher.unsquashSequence(seq.values); return { type: "create_sequence", name: seq.name, schema: seq.schema, values }; }; prepareAlterSequenceJson = (seq) => { const values = PgSquasher.unsquashSequence(seq.values); return [ { type: "alter_sequence", schema: seq.schema, name: seq.name, values } ]; }; prepareDropSequenceJson = (name, schema6) => { return { type: "drop_sequence", name, schema: schema6 }; }; prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => { return { type: "move_sequence", name, schemaFrom, schemaTo }; }; prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => { return { type: "rename_sequence", nameFrom, nameTo, schema: schema6 }; }; prepareCreateRoleJson = (role) => { return { type: "create_role", name: role.name, values: { createDb: role.createDb, createRole: role.createRole, inherit: role.inherit } }; }; prepareAlterRoleJson = (role) => { return { type: "alter_role", name: role.name, values: { createDb: role.createDb, createRole: role.createRole, inherit: role.inherit } }; }; prepareDropRoleJson = (name) => { return { type: "drop_role", name }; }; prepareRenameRoleJson = (nameFrom, nameTo) => { return { type: "rename_role", nameFrom, nameTo }; }; prepareCreateSchemasJson = (values) => { return values.map((it) => { return { type: "create_schema", name: it }; }); }; prepareRenameSchemasJson = (values) => { return values.map((it) => { return { type: "rename_schema", from: it.from, to: it.to }; }); }; prepareDeleteSchemasJson = (values) => { return values.map((it) => { return { type: "drop_schema", name: it }; }); }; prepareRenameColumns = (tableName, schema6, pairs) => { return pairs.map((it) => { return { type: "alter_table_rename_column", tableName, oldColumnName: it.from.name, newColumnName: it.to.name, schema: schema6 }; }); }; _prepareDropColumns = (taleName, schema6, columns) => { return columns.map((it) => { return { type: "alter_table_drop_column", tableName: taleName, columnName: it.name, schema: schema6 }; }); }; _prepareAddColumns = (tableName, schema6, columns) => { return columns.map((it) => { return { type: "alter_table_add_column", tableName, column: it, schema: schema6 }; }); }; _prepareSqliteAddColumns = (tableName, columns, referenceData) => { const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue)); return columns.map((it) => { const columnsWithReference = unsquashed.find((t6) => t6.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, schema6, columns, json1, json2, action) => { let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column6 of columns) { const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name; const table6 = json2.tables[tableName]; const snapshotColumn = table6.columns[columnName]; const columnType = snapshotColumn.type; const columnDefault = snapshotColumn.default; const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0; const columnNotNull = table6.columns[columnName].notNull; const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false; const columnPk = table6.columns[columnName].primaryKey; if (column6.autoincrement?.type === "added") { statements.push({ type: "alter_table_alter_column_set_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.autoincrement?.type === "changed") { const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement"; statements.push({ type, tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.autoincrement?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } } for (const column6 of columns) { const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name; const columnType = json2.tables[tableName].columns[columnName].type; const columnDefault = json2.tables[tableName].columns[columnName].default; const columnGenerated = json2.tables[tableName].columns[columnName].generated; const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate; const columnNotNull = json2.tables[tableName].columns[columnName].notNull; const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement; const columnPk = json2.tables[tableName].columns[columnName].primaryKey; const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`]; if (typeof column6.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column6.name.old, newColumnName: column6.name.new, schema: schema6 }); } if (column6.type?.type === "changed") { statements.push({ type: "alter_table_alter_column_set_type", tableName, columnName, newDataType: column6.type.new, oldDataType: column6.type.old, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (column6.default?.type === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.new, oldDefaultValue: column6.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_default", tableName, columnName, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.notNull?.type === "added") { statements.push({ type: "alter_table_alter_column_set_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "changed") { const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull"; statements.push({ type, tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.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: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.generated?.type === "changed" && action !== "push") { statements.push({ type: "alter_table_alter_column_alter_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.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: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated, oldColumn: json1.tables[tableName].columns[columnName] }); } if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) { const wasAutoincrement = statements.filter( (it) => it.type === "alter_table_alter_column_set_autoincrement" ); if (wasAutoincrement.length === 0) { setPkStatements.push({ type: "alter_table_alter_column_set_pk", tableName, schema: schema6, columnName }); } } if (column6.onUpdate?.type === "added") { statements.push({ type: "alter_table_alter_column_set_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.onUpdate?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } } return [...dropPkStatements, ...setPkStatements, ...statements]; }; preparePgAlterColumns = (_tableName, schema6, columns, json2, json1, action) => { const tableKey2 = `${schema6 || "public"}.${_tableName}`; let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column6 of columns) { const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name; const tableName = json2.tables[tableKey2].name; const columnType = json2.tables[tableKey2].columns[columnName].type; const columnDefault = json2.tables[tableKey2].columns[columnName].default; const columnGenerated = json2.tables[tableKey2].columns[columnName].generated; const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate; const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull; const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement; const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey; const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema; const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema; const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`]; if (typeof column6.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column6.name.old, newColumnName: column6.name.new, schema: schema6 }); } if (column6.type?.type === "changed") { const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const parsedNewColumnType = column6.type.new.replace(arrayDefinitionRegex, ""); const parsedOldColumnType = column6.type.old.replace(arrayDefinitionRegex, ""); const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`]; const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`]; statements.push({ type: "pg_alter_table_alter_column_set_type", tableName, columnName, typeSchema, newDataType: { name: column6.type.new, isEnum: isNewTypeIsEnum ? true : false }, oldDataType: { name: column6.type.old, isEnum: isOldTypeIsEnum ? true : false }, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (column6.default?.type === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.new, oldDefaultValue: column6.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_default", tableName, columnName, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.notNull?.type === "added") { statements.push({ type: "alter_table_alter_column_set_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "changed") { const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull"; statements.push({ type, tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.identity?.type === "added") { statements.push({ type: "alter_table_alter_column_set_identity", tableName, columnName, schema: schema6, identity: column6.identity.value }); } if (column6.identity?.type === "changed") { statements.push({ type: "alter_table_alter_column_change_identity", tableName, columnName, schema: schema6, identity: column6.identity.new, oldIdentity: column6.identity.old }); } if (column6.identity?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_identity", tableName, columnName, schema: schema6 }); } if (column6.generated?.type === "added") { statements.push({ type: "alter_table_alter_column_set_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.generated?.type === "changed" && action !== "push") { statements.push({ type: "alter_table_alter_column_alter_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.generated?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) { const wasAutoincrement = statements.filter( (it) => it.type === "alter_table_alter_column_set_autoincrement" ); if (wasAutoincrement.length === 0) { setPkStatements.push({ type: "alter_table_alter_column_set_pk", tableName, schema: schema6, columnName }); } } if (column6.onUpdate?.type === "added") { statements.push({ type: "alter_table_alter_column_set_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.onUpdate?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } } return [...dropPkStatements, ...setPkStatements, ...statements]; }; prepareSqliteAlterColumns = (tableName, schema6, columns, json2) => { let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column6 of columns) { const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name; const columnType = json2.tables[tableName].columns[columnName].type; const columnDefault = json2.tables[tableName].columns[columnName].default; const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate; const columnNotNull = json2.tables[tableName].columns[columnName].notNull; const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement; const columnPk = json2.tables[tableName].columns[columnName].primaryKey; const columnGenerated = json2.tables[tableName].columns[columnName].generated; const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`]; if (column6.autoincrement?.type === "added") { statements.push({ type: "alter_table_alter_column_set_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.autoincrement?.type === "changed") { const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement"; statements.push({ type, tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.autoincrement?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (typeof column6.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column6.name.old, newColumnName: column6.name.new, schema: schema6 }); } if (column6.type?.type === "changed") { statements.push({ type: "alter_table_alter_column_set_type", tableName, columnName, newDataType: column6.type.new, oldDataType: column6.type.old, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (column6.default?.type === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column6.default.new, oldDefaultValue: column6.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.default?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_default", tableName, columnName, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (column6.notNull?.type === "added") { statements.push({ type: "alter_table_alter_column_set_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "changed") { const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull"; statements.push({ type, tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.notNull?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_notnull", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.generated?.type === "added") { if (columnGenerated?.type === "virtual") { statements.push({ type: "alter_table_alter_column_set_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } else { warning( `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"` ); } } if (column6.generated?.type === "changed") { if (columnGenerated?.type === "virtual") { statements.push({ type: "alter_table_alter_column_alter_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } else { warning( `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"` ); } } if (column6.generated?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_generated", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) { const wasAutoincrement = statements.filter( (it) => it.type === "alter_table_alter_column_set_autoincrement" ); if (wasAutoincrement.length === 0) { setPkStatements.push({ type: "alter_table_alter_column_set_pk", tableName, schema: schema6, columnName }); } } if (column6.onUpdate?.type === "added") { statements.push({ type: "alter_table_alter_column_set_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (column6.onUpdate?.type === "deleted") { statements.push({ type: "alter_table_alter_column_drop_on_update", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } } return [...dropPkStatements, ...setPkStatements, ...statements]; }; prepareRenamePolicyJsons = (tableName, schema6, renames) => { return renames.map((it) => { return { type: "rename_policy", tableName, oldName: it.from.name, newName: it.to.name, schema: schema6 }; }); }; prepareRenameIndPolicyJsons = (renames) => { return renames.map((it) => { return { type: "rename_ind_policy", tableKey: it.from.on, oldName: it.from.name, newName: it.to.name }; }); }; prepareCreatePolicyJsons = (tableName, schema6, policies) => { return policies.map((it) => { return { type: "create_policy", tableName, data: it, schema: schema6 }; }); }; prepareCreateIndPolicyJsons = (policies) => { return policies.map((it) => { return { type: "create_ind_policy", tableName: it.on, data: it }; }); }; prepareDropPolicyJsons = (tableName, schema6, policies) => { return policies.map((it) => { return { type: "drop_policy", tableName, data: it, schema: schema6 }; }); }; prepareDropIndPolicyJsons = (policies) => { return policies.map((it) => { return { type: "drop_ind_policy", tableName: it.on, data: it }; }); }; prepareAlterPolicyJson = (tableName, schema6, oldPolicy, newPolicy) => { return { type: "alter_policy", tableName, oldData: oldPolicy, newData: newPolicy, schema: schema6 }; }; prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => { return { type: "alter_ind_policy", oldData: oldPolicy, newData: newPolicy }; }; preparePgCreateIndexesJson = (tableName, schema6, indexes, fullSchema, action) => { if (action === "push") { return Object.values(indexes).map((indexData) => { const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData); const data = fullSchema.tables[`${schema6 === "" ? "public" : schema6}.${tableName}`].indexes[unsquashedIndex.name]; return { type: "create_index_pg", tableName, data, schema: schema6 }; }); } return Object.values(indexes).map((indexData) => { return { type: "create_index_pg", tableName, data: PgSquasher.unsquashIdx(indexData), schema: schema6 }; }); }; prepareCreateIndexesJson = (tableName, schema6, indexes, internal) => { return Object.values(indexes).map((indexData) => { return { type: "create_index", tableName, data: indexData, schema: schema6, internal }; }); }; prepareCreateReferencesJson = (tableName, schema6, foreignKeys) => { return Object.values(foreignKeys).map((fkData) => { return { type: "create_reference", tableName, data: fkData, schema: schema6 }; }); }; prepareLibSQLCreateReferencesJson = (tableName, schema6, foreignKeys, json2, action) => { return Object.values(foreignKeys).map((fkData) => { const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData); let isMulticolumn = false; if (columnsFrom.length > 1 || columnsTo.length > 1) { isMulticolumn = true; return { type: "create_reference", tableName, data: fkData, schema: schema6, isMulticolumn }; } const columnFrom = columnsFrom[0]; const { notNull: columnNotNull, default: columnDefault, type: columnType } = json2.tables[tableFrom].columns[columnFrom]; return { type: "create_reference", tableName, data: fkData, schema: schema6, columnNotNull, columnDefault, columnType }; }); }; prepareDropReferencesJson = (tableName, schema6, foreignKeys) => { return Object.values(foreignKeys).map((fkData) => { return { type: "delete_reference", tableName, data: fkData, schema: schema6 }; }); }; prepareLibSQLDropReferencesJson = (tableName, schema6, foreignKeys, json2, meta, action) => { const statements = Object.values(foreignKeys).map((fkData) => { const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData); const keys = Object.keys(json2.tables[tableName].columns); const filtered = columnsFrom.filter((it) => keys.includes(it)); const fullDrop = filtered.length === 0; if (fullDrop) return; let isMulticolumn = false; if (columnsFrom.length > 1 || columnsTo.length > 1) { isMulticolumn = true; return { type: "delete_reference", tableName, data: fkData, schema: schema6, isMulticolumn }; } const columnFrom = columnsFrom[0]; const newTableName = getNewTableName(tableFrom, meta); const { notNull: columnNotNull, default: columnDefault, type: columnType } = json2.tables[newTableName].columns[columnFrom]; const fkToSquash = { columnsFrom, columnsTo, name, tableFrom: newTableName, tableTo, onDelete, onUpdate }; const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash); return { type: "delete_reference", tableName, data: foreignKey, schema: schema6, columnNotNull, columnDefault, columnType }; }); return statements.filter((it) => it); }; prepareAlterReferencesJson = (tableName, schema6, foreignKeys) => { const stmts = []; Object.values(foreignKeys).map((val2) => { stmts.push({ type: "delete_reference", tableName, schema: schema6, data: val2.__old }); stmts.push({ type: "create_reference", tableName, schema: schema6, data: val2.__new }); }); return stmts; }; prepareDropIndexesJson = (tableName, schema6, indexes) => { return Object.values(indexes).map((indexData) => { return { type: "drop_index", tableName, data: indexData, schema: schema6 }; }); }; prepareAddCompositePrimaryKeySqlite = (tableName, pks) => { return Object.values(pks).map((it) => { return { type: "create_composite_pk", tableName, data: it }; }); }; prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => { return Object.values(pks).map((it) => { return { type: "delete_composite_pk", tableName, data: it }; }); }; prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => { return Object.values(pks).map((it) => { return { type: "alter_composite_pk", tableName, old: it.__old, new: it.__new }; }); }; prepareAddCompositePrimaryKeyPg = (tableName, schema6, pks, json2) => { return Object.values(pks).map((it) => { const unsquashed = PgSquasher.unsquashPK(it); return { type: "create_composite_pk", tableName, data: it, schema: schema6, constraintName: PgSquasher.unsquashPK(it).name }; }); }; prepareDeleteCompositePrimaryKeyPg = (tableName, schema6, pks, json1) => { return Object.values(pks).map((it) => { return { type: "delete_composite_pk", tableName, data: it, schema: schema6, constraintName: PgSquasher.unsquashPK(it).name }; }); }; prepareAlterCompositePrimaryKeyPg = (tableName, schema6, pks, json1, json2) => { return Object.values(pks).map((it) => { return { type: "alter_composite_pk", tableName, old: it.__old, new: it.__new, schema: schema6, oldConstraintName: PgSquasher.unsquashPK(it.__old).name, newConstraintName: PgSquasher.unsquashPK(it.__new).name }; }); }; prepareAddUniqueConstraintPg = (tableName, schema6, unqs) => { return Object.values(unqs).map((it) => { return { type: "create_unique_constraint", tableName, data: it, schema: schema6 }; }); }; prepareDeleteUniqueConstraintPg = (tableName, schema6, unqs) => { return Object.values(unqs).map((it) => { return { type: "delete_unique_constraint", tableName, data: it, schema: schema6 }; }); }; prepareAddCheckConstraint = (tableName, schema6, check) => { return Object.values(check).map((it) => { return { type: "create_check_constraint", tableName, data: it, schema: schema6 }; }); }; prepareDeleteCheckConstraint = (tableName, schema6, check) => { return Object.values(check).map((it) => { return { type: "delete_check_constraint", tableName, constraintName: PgSquasher.unsquashCheck(it).name, schema: schema6 }; }); }; prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => { 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 }; }); }; prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => { return Object.values(pks).map((it) => { return { type: "alter_composite_pk", tableName, old: it.__old, new: it.__new, oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name, newConstraintName: json2.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name }; }); }; preparePgCreateViewJson = (name, schema6, definition, materialized, withNoData = false, withOption, using, tablespace) => { return { type: "create_view", name, schema: schema6, definition, with: withOption, materialized, withNoData, using, tablespace }; }; prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => { const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta); return { type: "mysql_create_view", name, definition, algorithm, sqlSecurity, withCheckOption, replace }; }; prepareSqliteCreateViewJson = (name, definition) => { return { type: "sqlite_create_view", name, definition }; }; prepareDropViewJson = (name, schema6, materialized) => { const resObject = { name, type: "drop_view" }; if (schema6) resObject["schema"] = schema6; if (materialized) resObject["materialized"] = materialized; return resObject; }; prepareRenameViewJson = (to, from, schema6, materialized) => { const resObject = { type: "rename_view", nameTo: to, nameFrom: from }; if (schema6) resObject["schema"] = schema6; if (materialized) resObject["materialized"] = materialized; return resObject; }; preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => { const returnObject = { type: "alter_view_alter_schema", fromSchema: from, toSchema: to, name }; if (materialized) returnObject["materialized"] = materialized; return returnObject; }; preparePgAlterViewAddWithOptionJson = (name, schema6, materialized, withOption) => { return { type: "alter_view_add_with_option", name, schema: schema6, materialized, with: withOption }; }; preparePgAlterViewDropWithOptionJson = (name, schema6, materialized, withOption) => { return { type: "alter_view_drop_with_option", name, schema: schema6, materialized, with: withOption }; }; preparePgAlterViewAlterTablespaceJson = (name, schema6, materialized, to) => { return { type: "alter_view_alter_tablespace", name, schema: schema6, materialized, toTablespace: to }; }; preparePgAlterViewAlterUsingJson = (name, schema6, materialized, to) => { return { type: "alter_view_alter_using", name, schema: schema6, materialized, toUsing: to }; }; prepareMySqlAlterView = (view5) => { return { type: "alter_mysql_view", ...view5 }; }; } }); // src/statementCombiner.ts var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements; var init_statementCombiner = __esm({ "src/statementCombiner.ts"() { "use strict"; init_jsonStatements(); init_sqliteSchema(); prepareLibSQLRecreateTable = (table6, action) => { const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6; const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const references2 = Object.values(table6.foreignKeys); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); const statements = [ { type: "recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, referenceData: fks, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; prepareSQLiteRecreateTable = (table6, action) => { const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6; const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const references2 = Object.values(table6.foreignKeys); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); const statements = [ { type: "recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, referenceData: fks, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; libSQLCombineStatements = (statements, json2, action) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") { const { tableName: tableName2, columnName, columnPk } = statement; const columnIsPartOfForeignKey = Object.values( json2.tables[tableName2].foreignKeys ).some((it) => { const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it); return unsquashFk.columnsFrom.includes(columnName); }); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } } continue; } if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { newStatements[tableName2].push(statement); } continue; } newStatements[tableName2] = [statement]; continue; } if (statement.type === "create_reference") { const tableName2 = statement.tableName; const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement]; continue; } if (!statement.isMulticolumn && statementsForTable2.some( (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0] )) { continue; } if (statement.isMulticolumn) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { newStatements[tableName2].push(statement); } continue; } if (statement.type === "delete_reference") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; sqliteCombineStatements = (statements, json2, action) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "create_reference") { const tableName2 = statement.tableName; const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (data.columnsFrom.length === 1 && statementsForTable2.some( (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0] )) { continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; prepareSingleStoreRecreateTable = (table6) => { const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6; const composites = Object.values(compositePrimaryKeys); const statements = [ { type: "singlestore_recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, uniqueConstraints: Object.values(uniqueConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; singleStoreCombineStatements = (statements, json2) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some( ({ type }) => type === "rename_table" || type === "alter_table_rename_column" ); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; } }); // src/snapshotsDiffer.ts var snapshotsDiffer_exports = {}; __export(snapshotsDiffer_exports, { alteredPgViewSchema: () => alteredPgViewSchema, alteredTableScheme: () => alteredTableScheme, applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff, applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff, applyPgSnapshotsDiff: () => applyPgSnapshotsDiff, applySingleStoreSnapshotsDiff: () => applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff: () => applySqliteSnapshotsDiff, diffResultScheme: () => diffResultScheme, diffResultSchemeMysql: () => diffResultSchemeMysql, diffResultSchemeSQLite: () => diffResultSchemeSQLite, diffResultSchemeSingleStore: () => diffResultSchemeSingleStore, makePatched: () => makePatched, makeSelfOrPatched: () => makeSelfOrPatched }); var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff; var init_snapshotsDiffer = __esm({ "src/snapshotsDiffer.ts"() { "use strict"; init_esm(); init_jsonDiffer(); init_sqlgenerator(); init_jsonStatements(); init_global(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); init_statementCombiner(); init_utils(); makeChanged = (schema6) => { return objectType({ type: enumType(["changed"]), old: schema6, new: schema6 }); }; makeSelfOrChanged = (schema6) => { return unionType([ schema6, objectType({ type: enumType(["changed"]), old: schema6, new: schema6 }) ]); }; makePatched = (schema6) => { return unionType([ objectType({ type: literalType("added"), value: schema6 }), objectType({ type: literalType("deleted"), value: schema6 }), objectType({ type: literalType("changed"), old: schema6, new: schema6 }) ]); }; makeSelfOrPatched = (schema6) => { return unionType([ objectType({ type: literalType("none"), value: schema6 }), objectType({ type: literalType("added"), value: schema6 }), objectType({ type: literalType("deleted"), value: schema6 }), objectType({ type: literalType("changed"), old: schema6, new: schema6 }) ]); }; columnSchema = objectType({ name: stringType(), type: stringType(), typeSchema: stringType().optional(), primaryKey: booleanType().optional(), default: anyType().optional(), notNull: booleanType().optional(), // should it be optional? should if be here? autoincrement: booleanType().optional(), onUpdate: booleanType().optional(), isUnique: anyType().optional(), uniqueName: stringType().optional(), nullsNotDistinct: booleanType().optional(), generated: objectType({ as: stringType(), type: enumType(["stored", "virtual"]).default("stored") }).optional(), identity: stringType().optional() }).strict(); alteredColumnSchema = objectType({ name: makeSelfOrChanged(stringType()), type: makeChanged(stringType()).optional(), default: makePatched(anyType()).optional(), primaryKey: makePatched(booleanType()).optional(), notNull: makePatched(booleanType()).optional(), typeSchema: makePatched(stringType()).optional(), onUpdate: makePatched(booleanType()).optional(), autoincrement: makePatched(booleanType()).optional(), generated: makePatched( objectType({ as: stringType(), type: enumType(["stored", "virtual"]).default("stored") }) ).optional(), identity: makePatched(stringType()).optional() }).strict(); enumSchema3 = objectType({ name: stringType(), schema: stringType(), values: arrayType(stringType()) }).strict(); changedEnumSchema = objectType({ name: stringType(), schema: stringType(), addedValues: objectType({ before: stringType(), value: stringType() }).array(), deletedValues: arrayType(stringType()) }).strict(); tableScheme = objectType({ name: stringType(), schema: stringType().default(""), columns: recordType(stringType(), columnSchema), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()).default({}), uniqueConstraints: recordType(stringType(), stringType()).default({}), policies: recordType(stringType(), stringType()).default({}), checkConstraints: recordType(stringType(), stringType()).default({}), isRLSEnabled: booleanType().default(false) }).strict(); alteredTableScheme = objectType({ name: stringType(), schema: stringType(), altered: alteredColumnSchema.array(), addedIndexes: recordType(stringType(), stringType()), deletedIndexes: recordType(stringType(), stringType()), alteredIndexes: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }).strict() ), addedForeignKeys: recordType(stringType(), stringType()), deletedForeignKeys: recordType(stringType(), stringType()), alteredForeignKeys: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }).strict() ), addedCompositePKs: recordType(stringType(), stringType()), deletedCompositePKs: recordType(stringType(), stringType()), alteredCompositePKs: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedUniqueConstraints: recordType(stringType(), stringType()), deletedUniqueConstraints: recordType(stringType(), stringType()), alteredUniqueConstraints: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedPolicies: recordType(stringType(), stringType()), deletedPolicies: recordType(stringType(), stringType()), alteredPolicies: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedCheckConstraints: recordType( stringType(), stringType() ), deletedCheckConstraints: recordType( stringType(), stringType() ), alteredCheckConstraints: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ) }).strict(); alteredViewCommon = objectType({ name: stringType(), alteredDefinition: objectType({ __old: stringType(), __new: stringType() }).strict().optional(), alteredExisting: objectType({ __old: booleanType(), __new: booleanType() }).strict().optional() }); alteredPgViewSchema = alteredViewCommon.merge( objectType({ schema: stringType(), deletedWithOption: mergedViewWithOption2.optional(), addedWithOption: mergedViewWithOption2.optional(), addedWith: mergedViewWithOption2.optional(), deletedWith: mergedViewWithOption2.optional(), alteredWith: mergedViewWithOption2.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: sequenceSquashed2.array(), alteredRoles: roleSchema2.array(), alteredPolicies: policySquashed2.array(), alteredViews: alteredPgViewSchema.array() }).strict(); diffResultSchemeMysql = objectType({ alteredTablesWithColumns: alteredTableScheme.array(), alteredEnums: neverType().array(), alteredViews: alteredMySqlViewSchema.array() }); diffResultSchemeSingleStore = objectType({ alteredTablesWithColumns: alteredTableScheme.array(), alteredEnums: neverType().array() }); diffResultSchemeSQLite = objectType({ alteredTablesWithColumns: alteredTableScheme.array(), alteredEnums: neverType().array(), alteredViews: alteredViewCommon.array() }); schemaChangeFor = (table6, renamedSchemas) => { for (let ren of renamedSchemas) { if (table6.schema === ren.from.name) { return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name }; } } return { key: `${table6.schema || "public"}.${table6.name}`, schema: table6.schema }; }; nameChangeFor = (table6, renamed) => { for (let ren of renamed) { if (table6.name === ren.from.name) { return { name: ren.to.name }; } } return { name: table6.name }; }; nameSchemaChangeFor = (table6, renamedTables) => { for (let ren of renamedTables) { if (table6.name === ren.from.name && table6.schema === ren.from.schema) { return { key: `${ren.to.schema || "public"}.${ren.to.name}`, name: ren.to.name, schema: ren.to.schema }; } } return { key: `${table6.schema || "public"}.${table6.name}`, name: table6.name, schema: table6.schema }; }; columnChangeFor = (column6, renamedColumns) => { for (let ren of renamedColumns) { if (column6 === ren.from.name) { return ren.to.name; } } return column6; }; applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas); const { created: createdSchemas, deleted: deletedSchemas, renamed: renamedSchemas } = await schemasResolver2({ created: schemasDiff.added.map((it) => ({ name: it })), deleted: schemasDiff.deleted.map((it) => ({ name: it })) }); const schemasPatchedSnap1 = copy(json1); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; } ); schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; }); const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums); const { created: createdEnums, deleted: deletedEnums, renamed: renamedEnums, moved: movedEnums } = await enumsResolver2({ created: enumsDiff.added, deleted: enumsDiff.deleted }); schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums); it.name = name; it.schema = schema6; return [key, it]; }); const columnTypesChangeMap = renamedEnums.reduce( (acc, it) => { acc[`${it.from.schema}.${it.from.name}`] = { nameFrom: it.from.name, nameTo: it.to.name, schemaFrom: it.from.schema, schemaTo: it.to.schema }; return acc; }, {} ); const columnTypesMovesMap = movedEnums.reduce( (acc, it) => { acc[`${it.schemaFrom}.${it.name}`] = { nameFrom: it.name, nameTo: it.name, schemaFrom: it.schemaFrom, schemaTo: it.schemaTo }; return acc; }, {} ); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapValues(tableValue.columns, (column6) => { const key = `${column6.typeSchema || "public"}.${column6.type}`; const change = columnTypesChangeMap[key] || columnTypesMovesMap[key]; if (change) { column6.type = change.nameTo; column6.typeSchema = change.schemaTo; } return column6; }); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); schemasPatchedSnap1.sequences = mapEntries( schemasPatchedSnap1.sequences, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; } ); const sequencesDiff = diffSchemasOrTables( schemasPatchedSnap1.sequences, json2.sequences ); const { created: createdSequences, deleted: deletedSequences, renamed: renamedSequences, moved: movedSequences } = await sequencesResolver2({ created: sequencesDiff.added, deleted: sequencesDiff.deleted }); schemasPatchedSnap1.sequences = mapEntries( schemasPatchedSnap1.sequences, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences); it.name = name; it.schema = schema6; return [key, it]; } ); const sequencesChangeMap = renamedSequences.reduce( (acc, it) => { acc[`${it.from.schema}.${it.from.name}`] = { nameFrom: it.from.name, nameTo: it.to.name, schemaFrom: it.from.schema, schemaTo: it.to.schema }; return acc; }, {} ); const sequencesMovesMap = movedSequences.reduce( (acc, it) => { acc[`${it.schemaFrom}.${it.name}`] = { nameFrom: it.name, nameTo: it.name, schemaFrom: it.schemaFrom, schemaTo: it.schemaTo }; return acc; }, {} ); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapValues(tableValue.columns, (column6) => { const key = `${column6.typeSchema || "public"}.${column6.type}`; const change = sequencesChangeMap[key] || sequencesMovesMap[key]; if (change) { column6.type = change.nameTo; column6.typeSchema = change.schemaTo; } return column6; }); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const rolesDiff = diffSchemasOrTables( schemasPatchedSnap1.roles, json2.roles ); const { created: createdRoles, deleted: deletedRoles, renamed: renamedRoles } = await roleResolver2({ created: rolesDiff.added, deleted: rolesDiff.deleted }); schemasPatchedSnap1.roles = mapEntries( schemasPatchedSnap1.roles, (_3, it) => { const { name } = nameChangeFor(it, renamedRoles); it.name = name; return [name, it]; } ); const rolesChangeMap = renamedRoles.reduce( (acc, it) => { acc[it.from.name] = { nameFrom: it.from.name, nameTo: it.to.name }; return acc; }, {} ); schemasPatchedSnap1.roles = mapEntries( schemasPatchedSnap1.roles, (roleKey, roleValue) => { const key = roleKey; const change = rolesChangeMap[key]; if (change) { roleValue.name = change.nameTo; } return [roleKey, roleValue]; } ); const tablesDiff = diffSchemasOrTables( schemasPatchedSnap1.tables, json2.tables ); const { created: createdTables, deleted: deletedTables, moved: movedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(schemasPatchedSnap1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables); it.name = name; it.schema = schema6; return [key, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created2.length > 0) { columnCreates.push({ table: entry.name, schema: entry.schema, columns: created2 }); } if (deleted2.length > 0) { columnDeletes.push({ table: entry.name, schema: entry.schema, columns: deleted2 }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, schema: entry.schema, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[`${it.schema || "public"}.${it.table}`] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column6) => { const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || []; const newName = columnChangeFor(columnKey, rens); column6.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables); const policyRenames = []; const policyCreates = []; const policyDeletes = []; for (let entry of Object.values(policyRes)) { const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.policies.deleted.map( action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy ), created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy) }); if (created2.length > 0) { policyCreates.push({ table: entry.name, schema: entry.schema, columns: created2 }); } if (deleted2.length > 0) { policyDeletes.push({ table: entry.name, schema: entry.schema, columns: deleted2 }); } if (renamed.length > 0) { policyRenames.push({ table: entry.name, schema: entry.schema, renames: renamed }); } } const policyRenamesDict = columnRenames.reduce( (acc, it) => { acc[`${it.schema || "public"}.${it.table}`] = it.renames; return acc; }, {} ); const policyPatchedSnap1 = copy(tablesPatchedSnap1); policyPatchedSnap1.tables = mapEntries( policyPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedPolicies = mapKeys( tableValue.policies, (policyKey, policy5) => { const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || []; const newName = columnChangeFor(policyKey, rens); const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5); unsquashedPolicy.name = newName; policy5 = PgSquasher.squashPolicy(unsquashedPolicy); return newName; } ); tableValue.policies = patchedPolicies; return [tableKey2, tableValue]; } ); const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies); const indPolicyCreates = []; const indPolicyDeletes = []; const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({ deleted: indPolicyRes.deleted.map( (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values) ), created: indPolicyRes.added.map( (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values) ) }); if (created.length > 0) { indPolicyCreates.push({ policies: created }); } if (deleted.length > 0) { indPolicyDeletes.push({ policies: deleted }); } const indPolicyRenamesDict = indPolicyRenames.reduce( (acc, it) => { acc[it.from.name] = { nameFrom: it.from.name, nameTo: it.to.name }; return acc; }, {} ); const indPolicyPatchedSnap1 = copy(policyPatchedSnap1); indPolicyPatchedSnap1.policies = mapEntries( indPolicyPatchedSnap1.policies, (policyKey, policyValue) => { const key = policyKey; const change = indPolicyRenamesDict[key]; if (change) { policyValue.name = change.nameTo; } return [policyKey, policyValue]; } ); const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json2.views); const { created: createdViews, deleted: deletedViews, renamed: renamedViews, moved: movedViews } = await viewsResolver2({ created: viewsDiff.added, deleted: viewsDiff.deleted }); const renamesViewDic = {}; renamedViews.forEach((it) => { renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name }; }); const movedViewDic = {}; movedViews.forEach((it) => { movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom }; }); const viewsPatchedSnap1 = copy(policyPatchedSnap1); viewsPatchedSnap1.views = mapEntries( viewsPatchedSnap1.views, (viewKey, viewValue) => { const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`]; const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`]; if (rename) { viewValue.name = rename.to; viewKey = `${viewValue.schema}.${viewValue.name}`; } if (moved) viewKey = `${moved.to}.${viewValue.name}`; return [viewKey, viewValue]; } ); const diffResult = applyJsonDiff(viewsPatchedSnap1, json2); const typedResult = diffResultScheme.parse(diffResult); const jsonStatements = []; const jsonCreateIndexesForCreatedTables = createdTables.map((it) => { return preparePgCreateIndexesJson( it.name, it.schema, it.indexes, curFull, action ); }).flat(); const jsonDropTables = deletedTables.map((it) => { return prepareDropTableJson(it); }); const jsonRenameTables = renamedTables.map((it) => { return prepareRenameTableJson(it.from, it.to); }); const alteredTables = typedResult.alteredTablesWithColumns; const jsonRenameColumnsStatements = []; const jsonDropColumnsStatemets = []; const jsonAddColumnsStatemets = []; for (let it of columnRenames) { jsonRenameColumnsStatements.push( ...prepareRenameColumns(it.table, it.schema, it.renames) ); } for (let it of columnDeletes) { jsonDropColumnsStatemets.push( ..._prepareDropColumns(it.table, it.schema, it.columns) ); } for (let it of columnCreates) { jsonAddColumnsStatemets.push( ..._prepareAddColumns(it.table, it.schema, it.columns) ); } const jsonAddedCompositePKs = []; const jsonDeletedCompositePKs = []; const jsonAlteredCompositePKs = []; const jsonAddedUniqueConstraints = []; const jsonDeletedUniqueConstraints = []; const jsonAlteredUniqueConstraints = []; const jsonSetTableSchemas = []; if (movedTables) { for (let it of movedTables) { jsonSetTableSchemas.push({ type: "alter_table_set_schema", tableName: it.name, schemaFrom: it.schemaFrom || "public", schemaTo: it.schemaTo || "public" }); } } const jsonDeletedCheckConstraints = []; const jsonCreatedCheckConstraints = []; for (let it of alteredTables) { let addedColumns; for (const addedPkName of Object.keys(it.addedCompositePKs)) { const addedPkColumns = it.addedCompositePKs[addedPkName]; addedColumns = PgSquasher.unsquashPK(addedPkColumns); } let deletedColumns; for (const deletedPkName of Object.keys(it.deletedCompositePKs)) { const deletedPkColumns = it.deletedCompositePKs[deletedPkName]; deletedColumns = PgSquasher.unsquashPK(deletedPkColumns); } const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {}); let addedCompositePKs = []; let deletedCompositePKs = []; let alteredCompositePKs = []; if (doPerformDeleteAndCreate) { addedCompositePKs = prepareAddCompositePrimaryKeyPg( it.name, it.schema, it.addedCompositePKs, curFull ); deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg( it.name, it.schema, it.deletedCompositePKs, prevFull ); } alteredCompositePKs = prepareAlterCompositePrimaryKeyPg( it.name, it.schema, it.alteredCompositePKs, prevFull, curFull ); let addedUniqueConstraints = []; let deletedUniqueConstraints = []; let alteredUniqueConstraints = []; let createCheckConstraints = []; let deleteCheckConstraints = []; addedUniqueConstraints = prepareAddUniqueConstraintPg( it.name, it.schema, it.addedUniqueConstraints ); deletedUniqueConstraints = prepareDeleteUniqueConstraintPg( it.name, it.schema, it.deletedUniqueConstraints ); if (it.alteredUniqueConstraints) { const added = {}; const deleted2 = {}; for (const k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted2[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredCheckConstraints)) { added[k5] = it.alteredCheckConstraints[k5].__new; deleted2[k5] = it.alteredCheckConstraints[k5].__old; } createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2)); } jsonCreatedCheckConstraints.push(...createCheckConstraints); jsonDeletedCheckConstraints.push(...deleteCheckConstraints); jsonAddedCompositePKs.push(...addedCompositePKs); jsonDeletedCompositePKs.push(...deletedCompositePKs); jsonAlteredCompositePKs.push(...alteredCompositePKs); jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); } const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = alteredTables.map((it) => { return preparePgAlterColumns( it.name, it.schema, it.altered, json2, json1, action ); }).flat(); const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => { return preparePgCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull, action ); }).flat(); const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); const jsonCreatePoliciesStatements = []; const jsonDropPoliciesStatements = []; const jsonAlterPoliciesStatements = []; const jsonRenamePoliciesStatements = []; const jsonRenameIndPoliciesStatements = []; const jsonCreateIndPoliciesStatements = []; const jsonDropIndPoliciesStatements = []; const jsonAlterIndPoliciesStatements = []; const jsonEnableRLSStatements = []; const jsonDisableRLSStatements = []; for (let it of indPolicyRenames) { jsonRenameIndPoliciesStatements.push( ...prepareRenameIndPolicyJsons([it]) ); } for (const it of indPolicyCreates) { jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( it.policies ) ); } for (const it of indPolicyDeletes) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( it.policies ) ); } typedResult.alteredPolicies.forEach(({ values }) => { const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values); const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values); if (newPolicy.as !== oldPolicy.as) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( [oldPolicy] ) ); jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( [newPolicy] ) ); return; } if (newPolicy.for !== oldPolicy.for) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( [oldPolicy] ) ); jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( [newPolicy] ) ); return; } jsonAlterIndPoliciesStatements.push( prepareAlterIndPolicyJson( oldPolicy, newPolicy ) ); }); for (let it of policyRenames) { jsonRenamePoliciesStatements.push( ...prepareRenamePolicyJsons(it.table, it.schema, it.renames) ); } for (const it of policyCreates) { jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.table, it.schema, it.columns ) ); } for (const it of policyDeletes) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.table, it.schema, it.columns ) ); } alteredTables.forEach((it) => { Object.keys(it.alteredPolicies).forEach((policyName) => { const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old); if (newPolicy.as !== oldPolicy.as) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.name, it.schema, [oldPolicy] ) ); jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.name, it.schema, [newPolicy] ) ); return; } if (newPolicy.for !== oldPolicy.for) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.name, it.schema, [oldPolicy] ) ); jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.name, it.schema, [newPolicy] ) ); return; } jsonAlterPoliciesStatements.push( prepareAlterPolicyJson( it.name, it.schema, it.alteredPolicies[policyName].__old, it.alteredPolicies[policyName].__new ) ); }); for (const table6 of Object.values(json2.tables)) { const policiesInCurrentState = Object.keys(table6.policies); const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`]; const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : []; if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) { jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema }); } if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false; if (table6.isRLSEnabled !== wasRlsEnabled) { if (table6.isRLSEnabled) { jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema }); } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } } } for (const table6 of Object.values(columnsPatchedSnap1.tables)) { const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`]; if (tableInCurrentState === void 0 && !table6.isRLSEnabled) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } } const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesFoAlteredTables.push( ...preparePgCreateIndexesJson( it.name, it.schema, createdIndexes || {}, curFull, action ) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonCreateReferencesForCreatedTables = createdTables.map((it) => { return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys); }).flat(); const jsonReferencesForAlteredTables = alteredTables.map((it) => { const forAdded = prepareCreateReferencesJson( it.name, it.schema, it.addedForeignKeys ); const forAltered = prepareDropReferencesJson( it.name, it.schema, it.deletedForeignKeys ); const alteredFKs = prepareAlterReferencesJson( it.name, it.schema, it.alteredForeignKeys ); return [...forAdded, ...forAltered, ...alteredFKs]; }).flat(); const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter( (t6) => t6.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter( (t6) => t6.type === "delete_reference" ); const createEnums = createdEnums.map((it) => { return prepareCreateEnumJson(it.name, it.schema, it.values); }) ?? []; const dropEnums = deletedEnums.map((it) => { return prepareDropEnumJson(it.name, it.schema); }); const moveEnums = movedEnums.map((it) => { return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo); }); const renameEnums = renamedEnums.map((it) => { return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema); }); const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => { return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues); }).flat() ?? []; const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => { return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull); }).flat() ?? []; const createSequences = createdSequences.map((it) => { return prepareCreateSequenceJson(it); }) ?? []; const dropSequences = deletedSequences.map((it) => { return prepareDropSequenceJson(it.name, it.schema); }); const moveSequences = movedSequences.map((it) => { return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo); }); const renameSequences = renamedSequences.map((it) => { return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema); }); const jsonAlterSequences = typedResult.alteredSequences.map((it) => { return prepareAlterSequenceJson(it); }).flat() ?? []; const createRoles = createdRoles.map((it) => { return prepareCreateRoleJson(it); }) ?? []; const dropRoles = deletedRoles.map((it) => { return prepareDropRoleJson(it.name); }); const renameRoles = renamedRoles.map((it) => { return prepareRenameRoleJson(it.from.name, it.to.name); }); const jsonAlterRoles = typedResult.alteredRoles.map((it) => { return prepareAlterRoleJson(it); }).flat() ?? []; const createSchemas = prepareCreateSchemasJson( createdSchemas.map((it) => it.name) ); const renameSchemas = prepareRenameSchemasJson( renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name })) ); const dropSchemas = prepareDeleteSchemasJson( deletedSchemas.map((it) => it.name) ); const createTables = createdTables.map((it) => { return preparePgCreateTableJson(it, curFull); }); jsonCreatePoliciesStatements.push(...[].concat( ...createdTables.map( (it) => prepareCreatePolicyJsons( it.name, it.schema, Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy) ) ) )); const createViews = []; const dropViews = []; const renameViews = []; const alterViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return preparePgCreateViewJson( it.name, it.schema, it.definition, it.materialized, it.withNoData, it.with, it.using, it.tablespace ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name, it.schema, it.materialized); }) ); renameViews.push( ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => { return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized); }) ); alterViews.push( ...movedViews.filter( (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting ).map((it) => { return preparePgAlterViewAlterSchemaJson( it.schemaTo, it.schemaFrom, it.name, json2.views[`${it.schemaTo}.${it.name}`].materialized ); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting); for (const alteredView of alteredViews) { const viewKey = `${alteredView.schema}.${alteredView.name}`; const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey]; if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") { dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized)); createViews.push( preparePgCreateViewJson( alteredView.name, alteredView.schema, definition, materialized, withNoData, withOption, using, tablespace ) ); continue; } if (alteredView.addedWithOption) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.addedWithOption ) ); } if (alteredView.deletedWithOption) { alterViews.push( preparePgAlterViewDropWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.deletedWithOption ) ); } if (alteredView.addedWith) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.addedWith ) ); } if (alteredView.deletedWith) { alterViews.push( preparePgAlterViewDropWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.deletedWith ) ); } if (alteredView.alteredWith) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredWith ) ); } if (alteredView.alteredTablespace) { alterViews.push( preparePgAlterViewAlterTablespaceJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredTablespace.__new ) ); } if (alteredView.alteredUsing) { alterViews.push( preparePgAlterViewAlterUsingJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredUsing.__new ) ); } } jsonStatements.push(...createSchemas); jsonStatements.push(...renameSchemas); jsonStatements.push(...createEnums); jsonStatements.push(...moveEnums); jsonStatements.push(...renameEnums); jsonStatements.push(...jsonAlterEnumsWithAddedValues); jsonStatements.push(...createSequences); jsonStatements.push(...moveSequences); jsonStatements.push(...renameSequences); jsonStatements.push(...jsonAlterSequences); jsonStatements.push(...renameRoles); jsonStatements.push(...dropRoles); jsonStatements.push(...createRoles); jsonStatements.push(...jsonAlterRoles); jsonStatements.push(...createTables); jsonStatements.push(...jsonEnableRLSStatements); jsonStatements.push(...jsonDisableRLSStatements); jsonStatements.push(...dropViews); jsonStatements.push(...renameViews); jsonStatements.push(...alterViews); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonSetTableSchemas); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonAlterEnumsWithDroppedValues); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateReferencesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonCreateIndexesFoAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonAlteredUniqueConstraints); jsonStatements.push(...createViews); jsonStatements.push(...jsonRenamePoliciesStatements); jsonStatements.push(...jsonDropPoliciesStatements); jsonStatements.push(...jsonCreatePoliciesStatements); jsonStatements.push(...jsonAlterPoliciesStatements); jsonStatements.push(...jsonRenameIndPoliciesStatements); jsonStatements.push(...jsonDropIndPoliciesStatements); jsonStatements.push(...jsonCreateIndPoliciesStatements); jsonStatements.push(...jsonAlterIndPoliciesStatements); jsonStatements.push(...dropEnums); jsonStatements.push(...dropSequences); jsonStatements.push(...dropSchemas); const filteredJsonStatements = jsonStatements.filter((st) => { if (st.type === "alter_table_alter_column_drop_notnull") { if (jsonStatements.find( (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema )) { return false; } } if (st.type === "alter_table_alter_column_set_notnull") { if (jsonStatements.find( (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema )) { return false; } } return true; }); const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => { if (st.type === "alter_type_add_value") { if (filteredJsonStatements.find( (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema )) { return false; } } return true; }); const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => { if (st.type === "alter_table_alter_column_set_default") { if (filteredEnumsJsonStatements.find( (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema )) { return false; } if (filteredEnumsJsonStatements.find( (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find( (column6) => column6.default === st.newDefaultValue && column6.column === st.columnName && column6.table === st.tableName && column6.tableSchema === st.schema ) )) { return false; } } return true; }); const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rSchemas = renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name })); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns); return { statements: filteredEnums2JsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { for (const tableName in json1.tables) { const table6 = json1.tables[tableName]; for (const indexName2 in table6.indexes) { const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]); if (index6.isUnique) { table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json1.tables[tableName].indexes[index6.name]; } } } for (const tableName in json2.tables) { const table6 = json2.tables[tableName]; for (const indexName2 in table6.indexes) { const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]); if (index6.isUnique) { table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json2.tables[tableName].indexes[index6.name]; } } } const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column6) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column6.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const viewsDiff = diffSchemasOrTables(json1.views, json2.views); const { created: createdViews, deleted: deletedViews, renamed: renamedViews // renamed or moved } = await viewsResolver2({ created: viewsDiff.added, deleted: viewsDiff.deleted }); const renamesViewDic = {}; renamedViews.forEach((it) => { renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name }; }); const viewsPatchedSnap1 = copy(columnsPatchedSnap1); viewsPatchedSnap1.views = mapEntries( viewsPatchedSnap1.views, (viewKey, viewValue) => { const rename = renamesViewDic[viewValue.name]; if (rename) { viewValue.name = rename.to; viewKey = rename.to; } return [viewKey, viewValue]; } ); const diffResult = applyJsonDiff(viewsPatchedSnap1, json2); const typedResult = diffResultSchemeMysql.parse(diffResult); const jsonStatements = []; const jsonCreateIndexesForCreatedTables = createdTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.indexes, curFull.internal ); }).flat(); const jsonDropTables = deletedTables.map((it) => { return prepareDropTableJson(it); }); const jsonRenameTables = renamedTables.map((it) => { return prepareRenameTableJson(it.from, it.to); }); const alteredTables = typedResult.alteredTablesWithColumns; const jsonAddedCompositePKs = []; const jsonDeletedCompositePKs = []; const jsonAlteredCompositePKs = []; const jsonAddedUniqueConstraints = []; const jsonDeletedUniqueConstraints = []; const jsonAlteredUniqueConstraints = []; const jsonCreatedCheckConstraints = []; const jsonDeletedCheckConstraints = []; const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat(); const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat(); const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat(); alteredTables.forEach((it) => { let addedColumns = []; for (const addedPkName of Object.keys(it.addedCompositePKs)) { const addedPkColumns = it.addedCompositePKs[addedPkName]; addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns; } let deletedColumns = []; for (const deletedPkName of Object.keys(it.deletedCompositePKs)) { const deletedPkColumns = it.deletedCompositePKs[deletedPkName]; deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns; } const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns); let addedCompositePKs = []; let deletedCompositePKs = []; let alteredCompositePKs = []; addedCompositePKs = prepareAddCompositePrimaryKeyMySql( it.name, it.addedCompositePKs, prevFull, curFull ); deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql( it.name, it.deletedCompositePKs, prevFull ); alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql( it.name, it.alteredCompositePKs, prevFull, curFull ); let addedUniqueConstraints = []; let deletedUniqueConstraints = []; let alteredUniqueConstraints = []; let createdCheckConstraints = []; let deletedCheckConstraints = []; addedUniqueConstraints = prepareAddUniqueConstraintPg( it.name, it.schema, it.addedUniqueConstraints ); deletedUniqueConstraints = prepareDeleteUniqueConstraintPg( it.name, it.schema, it.deletedUniqueConstraints ); if (it.alteredUniqueConstraints) { const added = {}; const deleted = {}; for (const k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredCheckConstraints)) { added[k5] = it.alteredCheckConstraints[k5].__new; deleted[k5] = it.alteredCheckConstraints[k5].__old; } createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted)); } jsonAddedCompositePKs.push(...addedCompositePKs); jsonDeletedCompositePKs.push(...deletedCompositePKs); jsonAlteredCompositePKs.push(...alteredCompositePKs); jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); jsonCreatedCheckConstraints.push(...createdCheckConstraints); jsonDeletedCheckConstraints.push(...deletedCheckConstraints); }); const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = alteredTables.map((it) => { return prepareAlterColumnsMysql( it.name, it.schema, it.altered, json1, json2, action ); }).flat(); const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull.internal ); }).flat(); const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); alteredTables.forEach((it) => { const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesForAllAlteredTables.push( ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {}) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonCreateReferencesForCreatedTables = createdTables.map((it) => { return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys); }).flat(); const jsonReferencesForAllAlteredTables = alteredTables.map((it) => { const forAdded = prepareCreateReferencesJson( it.name, it.schema, it.addedForeignKeys ); const forAltered = prepareDropReferencesJson( it.name, it.schema, it.deletedForeignKeys ); const alteredFKs = prepareAlterReferencesJson( it.name, it.schema, it.alteredForeignKeys ); return [...forAdded, ...forAltered, ...alteredFKs]; }).flat(); const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "delete_reference" ); const jsonMySqlCreateTables = createdTables.map((it) => { return prepareMySqlCreateTableJson( it, curFull, curFull.internal ); }); const createViews = []; const dropViews = []; const renameViews = []; const alterViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return prepareMySqlCreateViewJson( it.name, it.definition, it.meta ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name); }) ); renameViews.push( ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => { return prepareRenameViewJson(it.to.name, it.from.name); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting); for (const alteredView of alteredViews) { const { definition, meta } = json2.views[alteredView.name]; if (alteredView.alteredExisting) { dropViews.push(prepareDropViewJson(alteredView.name)); createViews.push( prepareMySqlCreateViewJson( alteredView.name, definition, meta ) ); continue; } if (alteredView.alteredDefinition && action !== "push") { createViews.push( prepareMySqlCreateViewJson( alteredView.name, definition, meta, true ) ); continue; } if (alteredView.alteredMeta) { const view5 = curFull["views"][alteredView.name]; alterViews.push( prepareMySqlAlterView(view5) ); } } jsonStatements.push(...jsonMySqlCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...dropViews); jsonStatements.push(...renameViews); jsonStatements.push(...alterViews); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonCreateReferencesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...createViews); jsonStatements.push(...jsonAlteredUniqueConstraints); const sqlStatements = fromJson(jsonStatements, "mysql"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: jsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => { for (const tableName in json1.tables) { const table6 = json1.tables[tableName]; for (const indexName2 in table6.indexes) { const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]); if (index6.isUnique) { table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json1.tables[tableName].indexes[index6.name]; } } } for (const tableName in json2.tables) { const table6 = json2.tables[tableName]; for (const indexName2 in table6.indexes) { const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]); if (index6.isUnique) { table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json2.tables[tableName].indexes[index6.name]; } } } const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column6) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column6.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const diffResult = applyJsonDiff(columnsPatchedSnap1, json2); const typedResult = diffResultSchemeSingleStore.parse(diffResult); const jsonStatements = []; const jsonCreateIndexesForCreatedTables = createdTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.indexes, curFull.internal ); }).flat(); const jsonDropTables = deletedTables.map((it) => { return prepareDropTableJson(it); }); const jsonRenameTables = renamedTables.map((it) => { return prepareRenameTableJson(it.from, it.to); }); const alteredTables = typedResult.alteredTablesWithColumns; const jsonAddedCompositePKs = []; const jsonAddedUniqueConstraints = []; const jsonDeletedUniqueConstraints = []; const jsonAlteredUniqueConstraints = []; const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat(); const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat(); const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat(); alteredTables.forEach((it) => { let addedColumns = []; for (const addedPkName of Object.keys(it.addedCompositePKs)) { const addedPkColumns = it.addedCompositePKs[addedPkName]; addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns; } let deletedColumns = []; for (const deletedPkName of Object.keys(it.deletedCompositePKs)) { const deletedPkColumns = it.deletedCompositePKs[deletedPkName]; deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns; } const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns); let addedUniqueConstraints = []; let deletedUniqueConstraints = []; let alteredUniqueConstraints = []; let createdCheckConstraints = []; let deletedCheckConstraints = []; addedUniqueConstraints = prepareAddUniqueConstraintPg( it.name, it.schema, it.addedUniqueConstraints ); deletedUniqueConstraints = prepareDeleteUniqueConstraintPg( it.name, it.schema, it.deletedUniqueConstraints ); if (it.alteredUniqueConstraints) { const added = {}; const deleted = {}; for (const k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredCheckConstraints)) { added[k5] = it.alteredCheckConstraints[k5].__new; deleted[k5] = it.alteredCheckConstraints[k5].__old; } createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted)); } jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); }); const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = alteredTables.map((it) => { return prepareAlterColumnsMysql( it.name, it.schema, it.altered, json1, json2, action ); }).flat(); const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull.internal ); }).flat(); const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); alteredTables.forEach((it) => { const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesForAllAlteredTables.push( ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {}) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonSingleStoreCreateTables = createdTables.map((it) => { return prepareSingleStoreCreateTableJson( it, curFull, curFull.internal ); }); jsonStatements.push(...jsonSingleStoreCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAlteredUniqueConstraints); const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2); const sqlStatements = fromJson(combinedJsonStatements, "singlestore"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: combinedJsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column6) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column6.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const viewsDiff = diffSchemasOrTables(json1.views, json2.views); const { created: createdViews, deleted: deletedViews, renamed: renamedViews // renamed or moved } = await viewsResolver2({ created: viewsDiff.added, deleted: viewsDiff.deleted }); const renamesViewDic = {}; renamedViews.forEach((it) => { renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name }; }); const viewsPatchedSnap1 = copy(columnsPatchedSnap1); viewsPatchedSnap1.views = mapEntries( viewsPatchedSnap1.views, (viewKey, viewValue) => { const rename = renamesViewDic[viewValue.name]; if (rename) { viewValue.name = rename.to; } return [viewKey, viewValue]; } ); const diffResult = applyJsonDiff(viewsPatchedSnap1, json2); const typedResult = diffResultSchemeSQLite.parse(diffResult); const tablesMap = {}; typedResult.alteredTablesWithColumns.forEach((obj) => { tablesMap[obj.name] = obj; }); const jsonCreateTables = createdTables.map((it) => { return prepareSQLiteCreateTable(it, action); }); const jsonCreateIndexesForCreatedTables = createdTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.indexes, curFull.internal ); }).flat(); const jsonDropTables = deletedTables.map((it) => { return prepareDropTableJson(it); }); const jsonRenameTables = renamedTables.map((it) => { return prepareRenameTableJson(it.from, it.to); }); const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat(); const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat(); const jsonAddColumnsStatemets = columnCreates.map((it) => { return _prepareSqliteAddColumns( it.table, it.columns, tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : [] ); }).flat(); const allAltered = typedResult.alteredTablesWithColumns; const jsonAddedCompositePKs = []; const jsonDeletedCompositePKs = []; const jsonAlteredCompositePKs = []; const jsonAddedUniqueConstraints = []; const jsonDeletedUniqueConstraints = []; const jsonAlteredUniqueConstraints = []; const jsonDeletedCheckConstraints = []; const jsonCreatedCheckConstraints = []; allAltered.forEach((it) => { let addedColumns = []; for (const addedPkName of Object.keys(it.addedCompositePKs)) { const addedPkColumns = it.addedCompositePKs[addedPkName]; addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns); } let deletedColumns = []; for (const deletedPkName of Object.keys(it.deletedCompositePKs)) { const deletedPkColumns = it.deletedCompositePKs[deletedPkName]; deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns); } const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns); let addedCompositePKs = []; let deletedCompositePKs = []; let alteredCompositePKs = []; if (doPerformDeleteAndCreate) { addedCompositePKs = prepareAddCompositePrimaryKeySqlite( it.name, it.addedCompositePKs ); deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite( it.name, it.deletedCompositePKs ); } alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite( it.name, it.alteredCompositePKs ); let addedUniqueConstraints = []; let deletedUniqueConstraints = []; let alteredUniqueConstraints = []; addedUniqueConstraints = prepareAddUniqueConstraintPg( it.name, it.schema, it.addedUniqueConstraints ); deletedUniqueConstraints = prepareDeleteUniqueConstraintPg( it.name, it.schema, it.deletedUniqueConstraints ); if (it.alteredUniqueConstraints) { const added = {}; const deleted = {}; for (const k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredCheckConstraints)) { added[k5] = it.alteredCheckConstraints[k5].__new; deleted[k5] = it.alteredCheckConstraints[k5].__old; } createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted)); } jsonAddedCompositePKs.push(...addedCompositePKs); jsonDeletedCompositePKs.push(...deletedCompositePKs); jsonAlteredCompositePKs.push(...alteredCompositePKs); jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); jsonCreatedCheckConstraints.push(...createdCheckConstraints); jsonDeletedCheckConstraints.push(...deletedCheckConstraints); }); const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = allAltered.map((it) => { return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2); }).flat(); const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull.internal ); }).flat(); const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); allAltered.forEach((it) => { const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesForAllAlteredTables.push( ...prepareCreateIndexesJson( it.name, it.schema, createdIndexes || {}, curFull.internal ) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonReferencesForAllAlteredTables = allAltered.map((it) => { const forAdded = prepareCreateReferencesJson( it.name, it.schema, it.addedForeignKeys ); const forAltered = prepareDropReferencesJson( it.name, it.schema, it.deletedForeignKeys ); const alteredFKs = prepareAlterReferencesJson( it.name, it.schema, it.alteredForeignKeys ); return [...forAdded, ...forAltered, ...alteredFKs]; }).flat(); const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "delete_reference" ); const createViews = []; const dropViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return prepareSqliteCreateViewJson( it.name, it.definition ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name); }) ); dropViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareDropViewJson(it.from.name); }) ); createViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareSqliteCreateViewJson(it.to.name, it.to.definition); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting); for (const alteredView of alteredViews) { const { definition } = json2.views[alteredView.name]; if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") { dropViews.push(prepareDropViewJson(alteredView.name)); createViews.push( prepareSqliteCreateViewJson( alteredView.name, definition ) ); } } const jsonStatements = []; jsonStatements.push(...jsonCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...jsonAlteredUniqueConstraints); jsonStatements.push(...dropViews); jsonStatements.push(...createViews); const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action); const sqlStatements = fromJson(combinedJsonStatements, "sqlite"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: combinedJsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column6) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column6.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const viewsDiff = diffSchemasOrTables(json1.views, json2.views); const { created: createdViews, deleted: deletedViews, renamed: renamedViews // renamed or moved } = await viewsResolver2({ created: viewsDiff.added, deleted: viewsDiff.deleted }); const renamesViewDic = {}; renamedViews.forEach((it) => { renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name }; }); const viewsPatchedSnap1 = copy(columnsPatchedSnap1); viewsPatchedSnap1.views = mapEntries( viewsPatchedSnap1.views, (viewKey, viewValue) => { const rename = renamesViewDic[viewValue.name]; if (rename) { viewValue.name = rename.to; } return [viewKey, viewValue]; } ); const diffResult = applyJsonDiff(viewsPatchedSnap1, json2); const typedResult = diffResultSchemeSQLite.parse(diffResult); const tablesMap = {}; typedResult.alteredTablesWithColumns.forEach((obj) => { tablesMap[obj.name] = obj; }); const jsonCreateTables = createdTables.map((it) => { return prepareSQLiteCreateTable(it, action); }); const jsonCreateIndexesForCreatedTables = createdTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.indexes, curFull.internal ); }).flat(); const jsonDropTables = deletedTables.map((it) => { return prepareDropTableJson(it); }); const jsonRenameTables = renamedTables.map((it) => { return prepareRenameTableJson(it.from, it.to); }); const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat(); const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat(); const jsonAddColumnsStatemets = columnCreates.map((it) => { return _prepareSqliteAddColumns( it.table, it.columns, tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : [] ); }).flat(); const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); const allAltered = typedResult.alteredTablesWithColumns; const jsonAddedCompositePKs = []; const jsonDeletedCompositePKs = []; const jsonAlteredCompositePKs = []; const jsonAddedUniqueConstraints = []; const jsonDeletedUniqueConstraints = []; const jsonAlteredUniqueConstraints = []; const jsonDeletedCheckConstraints = []; const jsonCreatedCheckConstraints = []; allAltered.forEach((it) => { let addedColumns = []; for (const addedPkName of Object.keys(it.addedCompositePKs)) { const addedPkColumns = it.addedCompositePKs[addedPkName]; addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns); } let deletedColumns = []; for (const deletedPkName of Object.keys(it.deletedCompositePKs)) { const deletedPkColumns = it.deletedCompositePKs[deletedPkName]; deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns); } const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns); let addedCompositePKs = []; let deletedCompositePKs = []; let alteredCompositePKs = []; if (doPerformDeleteAndCreate) { addedCompositePKs = prepareAddCompositePrimaryKeySqlite( it.name, it.addedCompositePKs ); deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite( it.name, it.deletedCompositePKs ); } alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite( it.name, it.alteredCompositePKs ); let addedUniqueConstraints = []; let deletedUniqueConstraints = []; let alteredUniqueConstraints = []; let createdCheckConstraints = []; let deletedCheckConstraints = []; addedUniqueConstraints = prepareAddUniqueConstraintPg( it.name, it.schema, it.addedUniqueConstraints ); deletedUniqueConstraints = prepareDeleteUniqueConstraintPg( it.name, it.schema, it.deletedUniqueConstraints ); if (it.alteredUniqueConstraints) { const added = {}; const deleted = {}; for (const k5 of Object.keys(it.alteredUniqueConstraints)) { added[k5] = it.alteredUniqueConstraints[k5].__new; deleted[k5] = it.alteredUniqueConstraints[k5].__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 k5 of Object.keys(it.alteredCheckConstraints)) { added[k5] = it.alteredCheckConstraints[k5].__new; deleted[k5] = it.alteredCheckConstraints[k5].__old; } createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted)); } jsonAddedCompositePKs.push(...addedCompositePKs); jsonDeletedCompositePKs.push(...deletedCompositePKs); jsonAlteredCompositePKs.push(...alteredCompositePKs); jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); jsonCreatedCheckConstraints.push(...createdCheckConstraints); jsonDeletedCheckConstraints.push(...deletedCheckConstraints); }); const jsonTableAlternations = allAltered.map((it) => { return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2); }).flat(); const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull.internal ); }).flat(); const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); allAltered.forEach((it) => { const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesForAllAlteredTables.push( ...prepareCreateIndexesJson( it.name, it.schema, createdIndexes || {}, curFull.internal ) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonReferencesForAllAlteredTables = allAltered.map((it) => { const forAdded = prepareLibSQLCreateReferencesJson( it.name, it.schema, it.addedForeignKeys, json2, action ); const forAltered = prepareLibSQLDropReferencesJson( it.name, it.schema, it.deletedForeignKeys, json2, _meta, action ); const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys); return [...forAdded, ...forAltered, ...alteredFKs]; }).flat(); const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t6) => t6.type === "delete_reference" ); const createViews = []; const dropViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return prepareSqliteCreateViewJson( it.name, it.definition ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name); }) ); dropViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareDropViewJson(it.from.name); }) ); createViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareSqliteCreateViewJson(it.to.name, it.to.definition); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting); for (const alteredView of alteredViews) { const { definition } = json2.views[alteredView.name]; if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") { dropViews.push(prepareDropViewJson(alteredView.name)); createViews.push( prepareSqliteCreateViewJson( alteredView.name, definition ) ); } } const jsonStatements = []; jsonStatements.push(...jsonCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...dropViews); jsonStatements.push(...createViews); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...jsonAlteredUniqueConstraints); const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action); const sqlStatements = fromJson( combinedJsonStatements, "turso", action, json2 ); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); return { statements: combinedJsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; } }); // src/utils/words.ts var init_words = __esm({ "src/utils/words.ts"() { "use strict"; } }); // src/schemaValidator.ts var dialects, dialect4, commonSquashedSchema, commonSchema; var init_schemaValidator = __esm({ "src/schemaValidator.ts"() { "use strict"; init_esm(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"]; dialect4 = enumType(dialects); commonSquashedSchema = unionType([ pgSchemaSquashed, mysqlSchemaSquashed, SQLiteSchemaSquashed, singlestoreSchemaSquashed ]); commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]); } }); // 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_esm(); init_schemaValidator(); init_outputs(); sqliteDriversLiterals = [ literalType("d1-http"), literalType("expo"), literalType("durable-sqlite") ]; postgresqlDriversLiterals = [ literalType("aws-data-api"), literalType("pglite") ]; prefixes = [ "index", "timestamp", "supabase", "unix", "none" ]; prefix = enumType(prefixes); { const _3 = ""; } casingTypes = ["snake_case", "camelCase"]; casingType = enumType(casingTypes); sqliteDriver = unionType(sqliteDriversLiterals); postgresDriver = unionType(postgresqlDriversLiterals); driver = unionType([sqliteDriver, postgresDriver]); configMigrations = objectType({ table: stringType().optional(), schema: stringType().optional(), prefix: prefix.optional().default("index") }).optional(); configCommonSchema = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional(), breakpoints: booleanType().optional().default(true), verbose: booleanType().optional().default(false), driver: driver.optional(), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), migrations: configMigrations, dbCredentials: anyType().optional(), casing: casingType.optional(), sql: booleanType().default(true) }).passthrough(); casing = unionType([literalType("camel"), literalType("preserve")]).default( "camel" ); introspectParams = objectType({ schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), introspect: objectType({ casing }).default({ casing: "camel" }) }); configIntrospectCliSchema = objectType({ schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default( "camel" ) }); configGenerateSchema = objectType({ schema: unionType([stringType(), stringType().array()]), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true) }); configPushSchema = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), verbose: booleanType().default(false), strict: booleanType().default(false), out: stringType().optional() }); } }); // 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_singlestoreSchema(); 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 (e6) { console.error(e6); throw e6; } }; tablesResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "table" ); return { created, deleted, moved, renamed }; } catch (e6) { console.error(e6); throw e6; } }; viewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e6) { console.error(e6); throw e6; } }; mySqlViewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e6) { console.error(e6); throw e6; } }; sqliteViewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e6) { console.error(e6); throw e6; } }; sequencesResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "sequence" ); return { created, deleted, moved, renamed }; } catch (e6) { console.error(e6); throw e6; } }; 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 (e6) { console.error(e6); throw e6; } }; 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 index6 = 0; let leftMissing = [...missingColumns]; do { const created = newColumns[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newColumns.length); console.log( source_default.gray(`--- all columns conflicts in ${tableName} table resolved --- `) ); result.deleted.push(...leftMissing); return result; }; promptNamedConflict = async (newItems, missingItems, entity) => { if (missingItems.length === 0 || newItems.length === 0) { return { created: newItems, renamed: [], deleted: missingItems }; } const result = { created: [], renamed: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingItems]; do { const created = newItems[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newItems.length); console.log(source_default.gray(`--- all ${entity} conflicts resolved --- `)); result.deleted.push(...leftMissing); return result; }; promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => { if (missingItems.length === 0 || newItems.length === 0) { return { created: newItems, renamed: [], moved: [], deleted: missingItems }; } const result = { created: [], renamed: [], moved: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingItems]; do { const created = newItems[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newItems.length); console.log(source_default.gray(`--- all ${entity} conflicts resolved --- `)); result.deleted.push(...leftMissing); return result; }; promptSchemasConflict = async (newSchemas, missingSchemas) => { if (missingSchemas.length === 0 || newSchemas.length === 0) { return { created: newSchemas, renamed: [], deleted: missingSchemas }; } const result = { created: [], renamed: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingSchemas]; do { const created = newSchemas[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newSchemas.length); console.log(source_default.gray("--- all schemas conflicts resolved ---\n")); result.deleted.push(...leftMissing); return result; }; BREAKPOINT = "--> statement-breakpoint\n"; } }); // ../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 = (s6) => s6.replace(/[[\]\\-]/g, "\\$&"); regexpEscape = (s6) => s6.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 i6 = pos + 1; let sawStart = false; let uflag = false; let escaping = false; let negate2 = false; let endPos = pos; let rangeStart = ""; WHILE: while (i6 < glob2.length) { const c5 = glob2.charAt(i6); if ((c5 === "!" || c5 === "^") && i6 === pos + 1) { negate2 = true; i6++; continue; } if (c5 === "]" && sawStart && !escaping) { endPos = i6 + 1; break; } sawStart = true; if (c5 === "\\") { if (!escaping) { escaping = true; i6++; continue; } } if (c5 === "[" && !escaping) { for (const [cls, [unip, u5, neg]] of Object.entries(posixClasses)) { if (glob2.startsWith(cls, i6)) { if (rangeStart) { return ["$.", false, glob2.length - pos, true]; } i6 += cls.length; if (neg) negs.push(unip); else ranges.push(unip); uflag = uflag || u5; continue WHILE; } } } escaping = false; if (rangeStart) { if (c5 > rangeStart) { ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c5)); } else if (c5 === rangeStart) { ranges.push(braceEscape(c5)); } rangeStart = ""; i6++; continue; } if (glob2.startsWith("-]", i6 + 1)) { ranges.push(braceEscape(c5 + "-")); i6 += 2; continue; } if (glob2.startsWith("-", i6 + 1)) { rangeStart = c5; i6 += 2; continue; } ranges.push(braceEscape(c5)); i6++; } if (endPos < i6) { 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]) && !negate2) { const r6 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; return [regexpEscape(r6), false, endPos - pos, false]; } const sranges = "[" + (negate2 ? "^" : "") + rangesToString(ranges) + "]"; const snegs = "[" + (negate2 ? "" : "^") + 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 = (s6, { windowsPathsNoEscape = false } = {}) => { return windowsPathsNoEscape ? s6.replace(/[?*()[\]]/g, "[$&]") : s6.replace(/[?*()[\]\\]/g, "\\$&"); }; } }); // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js var unescape2; var init_unescape = __esm({ "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() { "use strict"; unescape2 = (s6, { windowsPathsNoEscape = false } = {}) => { return windowsPathsNoEscape ? s6.replace(/\[([^\/\\])\]/g, "$1") : s6.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 = (p5, pattern, options = {}) => { assertValidPattern(pattern); if (!options.nocomment && pattern.charAt(0) === "#") { return false; } return new Minimatch(pattern, options).match(p5); }; starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; starDotExtTest = (ext2) => (f7) => !f7.startsWith(".") && f7.endsWith(ext2); starDotExtTestDot = (ext2) => (f7) => f7.endsWith(ext2); starDotExtTestNocase = (ext2) => { ext2 = ext2.toLowerCase(); return (f7) => !f7.startsWith(".") && f7.toLowerCase().endsWith(ext2); }; starDotExtTestNocaseDot = (ext2) => { ext2 = ext2.toLowerCase(); return (f7) => f7.toLowerCase().endsWith(ext2); }; starDotStarRE = /^\*+\.\*+$/; starDotStarTest = (f7) => !f7.startsWith(".") && f7.includes("."); starDotStarTestDot = (f7) => f7 !== "." && f7 !== ".." && f7.includes("."); dotStarRE = /^\.\*+$/; dotStarTest = (f7) => f7 !== "." && f7 !== ".." && f7.startsWith("."); starRE = /^\*+$/; starTest = (f7) => f7.length !== 0 && !f7.startsWith("."); starTestDot = (f7) => f7.length !== 0 && f7 !== "." && f7 !== ".."; qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; qmarksTestNocase = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExt([$0]); if (!ext2) return noext; ext2 = ext2.toLowerCase(); return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2); }; qmarksTestNocaseDot = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExtDot([$0]); if (!ext2) return noext; ext2 = ext2.toLowerCase(); return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2); }; qmarksTestDot = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExtDot([$0]); return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2); }; qmarksTest = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExt([$0]); return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2); }; qmarksTestNoExt = ([$0]) => { const len = $0.length; return (f7) => f7.length === len && !f7.startsWith("."); }; qmarksTestNoExtDot = ([$0]) => { const len = $0.length; return (f7) => f7.length === len && f7 !== "." && f7 !== ".."; }; 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 = (s6) => s6.split("").reduce((set, c5) => { set[c5] = true; return set; }, {}); reSpecials = charSet("().*{}+?[]^$\\!"); addPatternStartSet = charSet("[.("); filter = (pattern, options = {}) => (p5) => minimatch(p5, pattern, options); minimatch.filter = filter; ext = (a5, b5 = {}) => Object.assign({}, a5, b5); defaults = (def) => { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch; } const orig = minimatch; const m6 = (p5, pattern, options = {}) => orig(p5, pattern, ext(def, options)); return Object.assign(m6, { 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: (s6, options = {}) => orig.unescape(s6, ext(def, options)), escape: (s6, options = {}) => orig.escape(s6, 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((f7) => mm.match(f7)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; minimatch.match = match; globUnescape = (s6) => s6.replace(/\\(.)/g, "$1"); globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; regExpEscape = (s6) => s6.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(..._3) { } make() { const pattern = this.pattern; const options = this.options; if (!options.nocomment && pattern.charAt(0) === "#") { this.comment = true; return; } if (!pattern) { this.empty = true; return; } this.parseNegate(); this.globSet = [...new Set(this.braceExpand())]; if (options.debug) { this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); const rawGlobParts = this.globSet.map((s6) => this.slashSplit(s6)); this.globParts = this.preprocess(rawGlobParts); this.debug(this.pattern, this.globParts); let set = this.globParts.map((s6, _3, __) => { if (this.isWindows && this.windowsNoMagicRoot) { const isUNC = s6[0] === "" && s6[1] === "" && (s6[2] === "?" || !globMagic.test(s6[2])) && !globMagic.test(s6[3]); const isDrive = /^[a-z]:/i.test(s6[0]); if (isUNC) { return [...s6.slice(0, 4), ...s6.slice(4).map((ss) => this.parse(ss))]; } else if (isDrive) { return [s6[0], ...s6.slice(1).map((ss) => this.parse(ss))]; } } return s6.map((ss) => this.parse(ss)); }); this.debug(this.pattern, set); this.set = set.filter((s6) => s6.indexOf(false) === -1); if (this.isWindows) { for (let i6 = 0; i6 < this.set.length; i6++) { const p5 = this.set[i6]; if (p5[0] === "" && p5[1] === "" && this.globParts[i6][2] === "?" && typeof p5[3] === "string" && /^[a-z]:$/i.test(p5[3])) { p5[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 i6 = 0; i6 < globParts.length; i6++) { for (let j5 = 0; j5 < globParts[i6].length; j5++) { if (globParts[i6][j5] === "**") { globParts[i6][j5] = "*"; } } } } 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 i6 = gs; while (parts[i6 + 1] === "**") { i6++; } if (i6 !== gs) { parts.splice(gs, i6 - 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 i6 = 1; i6 < parts.length - 1; i6++) { const p5 = parts[i6]; if (i6 === 1 && p5 === "" && parts[0] === "") continue; if (p5 === "." || p5 === "") { didSomething = true; parts.splice(i6, 1); i6--; } } 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 p5 = parts[dd - 1]; if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") { 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 p5 = parts[gs + 2]; const p22 = parts[gs + 3]; if (next !== "..") continue; if (!p5 || p5 === "." || p5 === ".." || !p22 || p22 === "." || p22 === "..") { continue; } didSomething = true; parts.splice(gs, 1); const other = parts.slice(0); other[gs] = "**"; globParts.push(other); gs--; } if (!this.preserveMultipleSlashes) { for (let i6 = 1; i6 < parts.length - 1; i6++) { const p5 = parts[i6]; if (i6 === 1 && p5 === "" && parts[0] === "") continue; if (p5 === "." || p5 === "") { didSomething = true; parts.splice(i6, 1); i6--; } } 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 p5 = parts[dd - 1]; if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") { 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 i6 = 0; i6 < globParts.length - 1; i6++) { for (let j5 = i6 + 1; j5 < globParts.length; j5++) { const matched = this.partsMatch(globParts[i6], globParts[j5], !this.preserveMultipleSlashes); if (!matched) continue; globParts[i6] = matched; globParts[j5] = []; } } return globParts.filter((gs) => gs.length); } partsMatch(a5, b5, emptyGSMatch = false) { let ai = 0; let bi = 0; let result = []; let which = ""; while (ai < a5.length && bi < b5.length) { if (a5[ai] === b5[bi]) { result.push(which === "b" ? b5[bi] : a5[ai]); ai++; bi++; } else if (emptyGSMatch && a5[ai] === "**" && b5[bi] === a5[ai + 1]) { result.push(a5[ai]); ai++; } else if (emptyGSMatch && b5[bi] === "**" && a5[ai] === b5[bi + 1]) { result.push(b5[bi]); bi++; } else if (a5[ai] === "*" && b5[bi] && (this.options.dot || !b5[bi].startsWith(".")) && b5[bi] !== "**") { if (which === "b") return false; which = "a"; result.push(a5[ai]); ai++; bi++; } else if (b5[bi] === "*" && a5[ai] && (this.options.dot || !a5[ai].startsWith(".")) && a5[ai] !== "**") { if (which === "a") return false; which = "b"; result.push(b5[bi]); ai++; bi++; } else { return false; } } return a5.length === b5.length && result; } parseNegate() { if (this.nonegate) return; const pattern = this.pattern; let negate2 = false; let negateOffset = 0; for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) { negate2 = !negate2; negateOffset++; } if (negateOffset) this.pattern = pattern.slice(negateOffset); this.negate = negate2; } // 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 p5 = pattern[pi]; var f7 = file[fi]; this.debug(pattern, p5, f7); if (p5 === false) { return false; } if (p5 === GLOBSTAR) { this.debug("GLOBSTAR", [pattern, p5, f7]); 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 p5 === "string") { hit = f7 === p5; this.debug("string match", p5, f7, hit); } else { hit = p5.test(f7); this.debug("pattern match", p5, f7, 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 m6; let fastTest = null; if (m6 = pattern.match(starRE)) { fastTest = options.dot ? starTestDot : starTest; } else if (m6 = pattern.match(starDotExtRE)) { fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m6[1]); } else if (m6 = pattern.match(qmarksRE)) { fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m6); } else if (m6 = pattern.match(starDotStarRE)) { fastTest = options.dot ? starDotStarTestDot : starDotStarTest; } else if (m6 = 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 = (p5) => p5.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 i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) { this.debug("%s %s %s %j", pattern, i6, re, c5); if (escaping) { if (c5 === "/") { return false; } if (reSpecials[c5]) { re += "\\"; } re += c5; escaping = false; continue; } switch (c5) { // Should already be path-split by now. /* c8 ignore start */ case "/": { return false; } /* c8 ignore stop */ case "\\": clearStateChar(); escaping = true; continue; // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": this.debug("%s %s %s %j <-- stateChar", pattern, i6, re, c5); this.debug("call clearStateChar %j", stateChar); clearStateChar(); stateChar = c5; if (options.noext) clearStateChar(); continue; case "(": { if (!stateChar) { re += "\\("; continue; } const plEntry = { type: stateChar, start: i6 - 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(i6 + 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(i6 + 1)); } continue; } // these are mostly the same in regexp and glob case "[": clearStateChar(); const [src, needUflag, consumed, magic] = parseClass(pattern, i6); if (consumed) { re += src; uflag = uflag || needUflag; i6 += consumed - 1; hasMagic = hasMagic || magic; } else { re += "\\["; } continue; case "]": re += "\\" + c5; continue; default: clearStateChar(); re += regExpEscape(c5); break; } } for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug(this.pattern, "setting tail", re, pl); tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => { if (!$2) { $2 = "\\"; } return $1 + $1 + $2 + "|"; }); this.debug("tail=%j\n %s", tail, tail, pl, re); const t6 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t6 + "\\(" + tail; } clearStateChar(); if (escaping) { re += "\\\\"; } const addPatternStart = addPatternStartSet[re.charAt(0)]; for (let n5 = negativeLists.length - 1; n5 > -1; n5--) { const nl = negativeLists[n5]; 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 i6 = 0; i6 < openParensBefore; i6++) { 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((p5) => typeof p5 === "string" ? regExpEscape(p5) : p5 === GLOBSTAR ? GLOBSTAR : p5._src); pp.forEach((p5, i6) => { const next = pp[i6 + 1]; const prev = pp[i6 - 1]; if (p5 !== GLOBSTAR || prev === GLOBSTAR) { return; } if (prev === void 0) { if (next !== void 0 && next !== GLOBSTAR) { pp[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next; } else { pp[i6] = twoStar; } } else if (next === void 0) { pp[i6 - 1] = prev + "(?:\\/|" + twoStar + ")?"; } else if (next !== GLOBSTAR) { pp[i6 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next; pp[i6 + 1] = GLOBSTAR; } }); return pp.filter((p5) => p5 !== 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(p5) { if (this.preserveMultipleSlashes) { return p5.split("/"); } else if (this.isWindows && /^\/\/[^\/]+/.test(p5)) { return ["", ...p5.split(/\/+/)]; } else { return p5.split(/\/+/); } } match(f7, partial = this.partial) { this.debug("match", f7, this.pattern); if (this.comment) { return false; } if (this.empty) { return f7 === ""; } if (f7 === "/" && partial) { return true; } const options = this.options; if (this.isWindows) { f7 = f7.split("\\").join("/"); } const ff = this.slashSplit(f7); 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 i6 = ff.length - 2; !filename && i6 >= 0; i6--) { filename = ff[i6]; } } for (let i6 = 0; i6 < set.length; i6++) { const pattern = set[i6]; let file = ff; if (options.matchBase && pattern.length === 1) { file = [filename]; } const hit = this.matchOne(file, pattern, partial); if (hit) { if (options.flipNegate) { return true; } return !this.negate; } } if (options.flipNegate) { return false; } return this.negate; } static defaults(def) { return minimatch.defaults(def).Minimatch; } }; minimatch.Minimatch = Minimatch; minimatch.escape = escape; minimatch.unescape = unescape2; } }); // src/extensions/vector.ts var vectorOps; var init_vector = __esm({ "src/extensions/vector.ts"() { "use strict"; vectorOps = [ "vector_l2_ops", "vector_ip_ops", "vector_cosine_ops", "vector_l1_ops", "bit_hamming_ops", "bit_jaccard_ops", "halfvec_l2_ops", "sparsevec_l2_ops" ]; } }); // src/serializer/utils.ts function getColumnCasing(column6, casing2) { if (!column6.name) return ""; return !column6.keyAsName || casing2 === void 0 ? column6.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column6.name) : (0, import_casing.toSnakeCase)(column6.name); } var import_casing, sqlToStr; var init_utils2 = __esm({ "src/serializer/utils.ts"() { "use strict"; import_casing = require("drizzle-orm/casing"); sqlToStr = (sql, casing2) => { return sql.toQuery({ escapeName: () => { throw new Error("we don't support params for `sql` default values"); }, escapeParam: () => { throw new Error("we don't support params for `sql` default values"); }, escapeString: () => { throw new Error("we don't support params for `sql` default values"); }, casing: new import_casing.CasingCache(casing2) }).sql; }; } }); // src/serializer/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 import_drizzle_orm, import_pg_core, indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery; var init_pgSerializer = __esm({ "src/serializer/pgSerializer.ts"() { "use strict"; init_source(); import_drizzle_orm = require("drizzle-orm"); import_pg_core = require("drizzle-orm/pg-core"); init_vector(); init_outputs(); init_utils(); init_utils2(); indexName = (tableName, columns) => { return `${tableName}_${columns.join("_")}_index`; }; generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => { const dialect6 = new import_pg_core.PgDialect({ casing: casing2 }); const result = {}; const resultViews = {}; const sequencesToReturn = {}; const rolesToReturn = {}; const policiesToReturn = {}; const indexesInSchema = {}; for (const table6 of tables) { const checksInTable = {}; const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema6, primaryKeys, uniqueConstraints, policies: policies2, enableRLS } = (0, import_pg_core.getTableConfig)(table6); if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) { continue; } const columnsObject = {}; const indexesObject = {}; const checksObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const policiesObject = {}; columns.forEach((column6) => { const name = getColumnCasing(column6, casing2); const notNull = column6.notNull; const primaryKey = column6.primary; const sqlTypeLowered = column6.getSQLType().toLowerCase(); const getEnumSchema = (column7) => { while ((0, import_drizzle_orm.is)(column7, import_pg_core.PgArray)) { column7 = column7.baseColumn; } return (0, import_drizzle_orm.is)(column7, import_pg_core.PgEnumColumn) ? column7.enum.schema || "public" : void 0; }; const typeSchema = getEnumSchema(column6); const generated = column6.generated; const identity = column6.generatedIdentity; const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1"; const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1"); const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType())); const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue); const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1"; const columnToSet = { name, type: column6.getSQLType(), typeSchema, primaryKey, notNull, generated: generated ? { as: (0, import_drizzle_orm.is)(generated.as, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as, type: "stored" } : void 0, identity: identity ? { type: identity.type, name: identity.sequenceName ?? `${tableName}_${name}_seq`, schema: schema6 ?? "public", increment, startWith, minValue, maxValue, cache: cache5, cycle: identity?.sequenceOptions?.cycle ?? false } : void 0 }; if (column6.isUnique) { const existingUnique = uniqueConstraintObject[column6.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( column6.uniqueName )} on the ${source_default.underline.blue( name )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns `)}` ); process.exit(1); } uniqueConstraintObject[column6.uniqueName] = { name: column6.uniqueName, nullsNotDistinct: column6.uniqueType === "not distinct", columns: [columnToSet.name] }; } if (column6.default !== void 0) { if ((0, import_drizzle_orm.is)(column6.default, import_drizzle_orm.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { if (typeof column6.default === "string") { columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`; } else { if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`; } else if (column6.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered === "timestamp") { columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`; } else { columnToSet.default = `'${column6.default.toISOString()}'`; } } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) { columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`; } else { columnToSet.default = column6.default; } } } } columnsObject[name] = columnToSet; }); primaryKeys.map((pk) => { const originalColumnNames = pk.columns.map((c5) => c5.name); const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2)); let name = pk.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnNames.length; i6++) { name = name.replace(originalColumnNames[i6], columnNames[i6]); } } primaryKeysObject[name] = { name, columns: columnNames }; }); uniqueConstraints?.map((unq) => { const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2)); const name = unq.name ?? (0, import_pg_core.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table. The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, nullsNotDistinct: unq.nullsNotDistinct, columns: columnNames }; }); const fks = foreignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete; const onUpdate = fk5.onUpdate; const reference = fk5.reference(); const tableTo = (0, import_drizzle_orm.getTableName)(reference.foreignTable); const schemaTo = (0, import_pg_core.getTableConfig)(reference.foreignTable).schema; const originalColumnsFrom = reference.columns.map((it) => it.name); const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2)); const originalColumnsTo = reference.foreignColumns.map((it) => it.name); const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2)); let name = fk5.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) { name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]); } for (let i6 = 0; i6 < originalColumnsTo.length; i6++) { name = name.replace(originalColumnsTo[i6], columnsTo[i6]); } } return { name, tableFrom, tableTo, schemaTo, columnsFrom, columnsTo, onDelete, onUpdate }; }); fks.forEach((it) => { foreignKeysObject[it.name] = it; }); indexes.forEach((value) => { const columns2 = value.config.columns; let indexColumnNames = []; columns2.forEach((it) => { if ((0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL)) { if (typeof value.config.name === "undefined") { console.log( ` ${withStyle.errorWarning( `Please specify an index name in ${(0, import_drizzle_orm.getTableName)(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.` )}` ); process.exit(1); } } it = it; const name2 = getColumnCasing(it, casing2); if (!(0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") { console.log( ` ${withStyle.errorWarning( `You are specifying an index on the ${source_default.blueBright( name2 )} column inside the ${source_default.blueBright( tableName )} table with the ${source_default.blueBright( "vector" )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}]. You can specify it using current syntax: ${source_default.underline( `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))` )} You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing ` )}` ); process.exit(1); } indexColumnNames.push(name2); }); const name = value.config.name ? value.config.name : indexName(tableName, indexColumnNames); let indexColumns = columns2.map( (it) => { if ((0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL)) { return { expression: dialect6.sqlToQuery(it, "indexes").sql, asc: true, isExpression: true, nulls: "last" }; } else { it = it; return { expression: getColumnCasing(it, casing2), isExpression: false, asc: it.indexConfig?.order === "asc", nulls: it.indexConfig?.nulls ? it.indexConfig?.nulls : it.indexConfig?.order === "desc" ? "first" : "last", opclass: it.indexConfig?.opClass }; } } ); if (typeof indexesInSchema[schema6 ?? "public"] !== "undefined") { if (indexesInSchema[schema6 ?? "public"].includes(name)) { console.log( ` ${withStyle.errorWarning( `We've found duplicated index name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue( tableName )} table or the table with the duplicated index name` )}` ); process.exit(1); } indexesInSchema[schema6 ?? "public"].push(name); } else { indexesInSchema[schema6 ?? "public"] = [name]; } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0, concurrently: value.config.concurrently ?? false, method: value.config.method ?? "btree", with: value.config.with ?? {} }; }); policies2.forEach((policy5) => { const mappedTo = []; if (!policy5.to) { mappedTo.push("public"); } else { if (policy5.to && typeof policy5.to === "string") { mappedTo.push(policy5.to); } else if (policy5.to && (0, import_drizzle_orm.is)(policy5.to, import_pg_core.PgRole)) { mappedTo.push(policy5.to.name); } else if (policy5.to && Array.isArray(policy5.to)) { policy5.to.forEach((it) => { if (typeof it === "string") { mappedTo.push(it); } else if ((0, import_drizzle_orm.is)(it, import_pg_core.PgRole)) { mappedTo.push(it.name); } }); } } if (policiesObject[policy5.name] !== void 0) { console.log( ` ${withStyle.errorWarning( `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue( policy5.name )} name` )}` ); process.exit(1); } policiesObject[policy5.name] = { name: policy5.name, as: policy5.as?.toUpperCase() ?? "PERMISSIVE", for: policy5.for?.toUpperCase() ?? "ALL", to: mappedTo.sort(), using: (0, import_drizzle_orm.is)(policy5.using, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0, withCheck: (0, import_drizzle_orm.is)(policy5.withCheck, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0 }; }); checks.forEach((check) => { const checkName = check.name; if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") { if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check.name)) { console.log( ` ${withStyle.errorWarning( `We've found duplicated check constraint name across ${source_default.underline.blue( schema6 ?? "public" )} schema in ${source_default.underline.blue( tableName )}. Please rename your check constraint in either the ${source_default.underline.blue( tableName )} table or the table with the duplicated check contraint name` )}` ); process.exit(1); } checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].push(checkName); } else { checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] = [check.name]; } checksObject[checkName] = { name: checkName, value: dialect6.sqlToQuery(check.value).sql }; }); const tableKey2 = `${schema6 ?? "public"}.${tableName}`; result[tableKey2] = { name: tableName, schema: schema6 ?? "", columns: columnsObject, indexes: indexesObject, foreignKeys: foreignKeysObject, compositePrimaryKeys: primaryKeysObject, uniqueConstraints: uniqueConstraintObject, policies: policiesObject, checkConstraints: checksObject, isRLSEnabled: enableRLS }; } for (const policy5 of policies) { if (!policy5._linkedTable) { console.log( ` ${withStyle.errorWarning( `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:` )}` ); continue; } const tableConfig = (0, import_pg_core.getTableConfig)(policy5._linkedTable); const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`; const mappedTo = []; if (!policy5.to) { mappedTo.push("public"); } else { if (policy5.to && typeof policy5.to === "string") { mappedTo.push(policy5.to); } else if (policy5.to && (0, import_drizzle_orm.is)(policy5.to, import_pg_core.PgRole)) { mappedTo.push(policy5.to.name); } else if (policy5.to && Array.isArray(policy5.to)) { policy5.to.forEach((it) => { if (typeof it === "string") { mappedTo.push(it); } else if ((0, import_drizzle_orm.is)(it, import_pg_core.PgRole)) { mappedTo.push(it.name); } }); } } if (result[tableKey2]?.policies[policy5.name] !== void 0 || policiesToReturn[policy5.name] !== void 0) { console.log( ` ${withStyle.errorWarning( `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue( policy5.name )} name` )}` ); process.exit(1); } const mappedPolicy = { name: policy5.name, as: policy5.as?.toUpperCase() ?? "PERMISSIVE", for: policy5.for?.toUpperCase() ?? "ALL", to: mappedTo.sort(), using: (0, import_drizzle_orm.is)(policy5.using, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0, withCheck: (0, import_drizzle_orm.is)(policy5.withCheck, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0 }; if (result[tableKey2]) { result[tableKey2].policies[policy5.name] = mappedPolicy; } else { policiesToReturn[policy5.name] = { ...mappedPolicy, schema: tableConfig.schema ?? "public", on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"` }; } } for (const sequence of sequences) { const name = sequence.seqName; if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") { const increment = stringFromIdentityProperty(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 cache5 = stringFromIdentityProperty(sequence?.seqOptions?.cache) ?? "1"; sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = { name, schema: sequence.schema ?? "public", increment, startWith, minValue, maxValue, cache: cache5, 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 view5 of combinedViews) { let viewName; let schema6; let query; let selectedFields; let isExisting; let withOption; let tablespace; let using; let withNoData; let materialized = false; if ((0, import_drizzle_orm.is)(view5, import_pg_core.PgView)) { ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core.getViewConfig)(view5)); } else { ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core.getMaterializedViewConfig)(view5)); materialized = true; } const viewSchema = schema6 ?? "public"; const viewKey = `${viewSchema}.${viewName}`; const columnsObject = {}; const uniqueConstraintObject = {}; const existingView = resultViews[viewKey]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm.is)(selectedFields[key], import_pg_core.PgColumn)) { const column6 = selectedFields[key]; const notNull = column6.notNull; const primaryKey = column6.primary; const sqlTypeLowered = column6.getSQLType().toLowerCase(); const typeSchema = (0, import_drizzle_orm.is)(column6, import_pg_core.PgEnumColumn) ? column6.enum.schema || "public" : void 0; const generated = column6.generated; const identity = column6.generatedIdentity; const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1"; const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1"); const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType())); const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue); const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1"; const columnToSet = { name: column6.name, type: column6.getSQLType(), typeSchema, primaryKey, notNull, generated: generated ? { as: (0, import_drizzle_orm.is)(generated.as, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as, type: "stored" } : void 0, identity: identity ? { type: identity.type, name: identity.sequenceName ?? `${viewName}_${column6.name}_seq`, schema: schema6 ?? "public", increment, startWith, minValue, maxValue, cache: cache5, cycle: identity?.sequenceOptions?.cycle ?? false } : void 0 }; if (column6.isUnique) { const existingUnique = uniqueConstraintObject[column6.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(column6.uniqueName)} on the ${source_default.underline.blue( column6.name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns ` )}` ); process.exit(1); } uniqueConstraintObject[column6.uniqueName] = { name: column6.uniqueName, nullsNotDistinct: column6.uniqueType === "not distinct", columns: [columnToSet.name] }; } if (column6.default !== void 0) { if ((0, import_drizzle_orm.is)(column6.default, import_drizzle_orm.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { if (typeof column6.default === "string") { columnToSet.default = `'${column6.default}'`; } else { if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`; } else if (column6.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered === "timestamp") { columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`; } else { columnToSet.default = `'${column6.default.toISOString()}'`; } } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) { columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`; } else { columnToSet.default = column6.default; } } } } columnsObject[column6.name] = columnToSet; } } resultViews[viewKey] = { columns: columnsObject, definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql, name: viewName, schema: viewSchema, isExisting, with: withOption, withNoData, materialized, tablespace, using }; } const enumsToReturn = enums.reduce((map2, obj) => { const enumSchema4 = obj.schema || "public"; const key = `${enumSchema4}.${obj.enumName}`; map2[key] = { name: obj.enumName, schema: enumSchema4, values: obj.enumValues }; return map2; }, {}); const schemasObject = Object.fromEntries( schemas.filter((it) => { if (schemaFilter) { return schemaFilter.includes(it.schemaName) && it.schemaName !== "public"; } else { return it.schemaName !== "public"; } }).map((it) => [it.schemaName, it.schemaName]) ); return { version: "7", dialect: "postgresql", tables: result, enums: enumsToReturn, schemas: schemasObject, sequences: sequencesToReturn, roles: rolesToReturn, policies: policiesToReturn, views: resultViews, _meta: { schemas: {}, tables: {}, columns: {} } }; }; trimChar = (str, char) => { let start = 0; let end = str.length; while (start < end && str[start] === char) ++start; while (end > start && str[end - 1] === char) --end; return start > 0 || end < str.length ? str.substring(start, end) : str.toString(); }; fromDatabase = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => { const result = {}; const views = {}; const policies = {}; const internals = { tables: {} }; const where = schemaFilters.map((t6) => `n.nspname = '${t6}'`).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((t6) => `schemaname = '${t6}'`).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((t6) => `n.nspname = '${t6}'`).join(" or "); const allEnums = await db.query( `select n.nspname as enum_schema, t.typname as enum_name, e.enumlabel as enum_value, e.enumsortorder as sort_order from pg_type t join pg_enum e on t.oid = e.enumtypid join pg_catalog.pg_namespace n ON n.oid = t.typnamespace ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`} order by enum_schema, enum_name, sort_order;` ); const enumsToReturn = {}; for (const dbEnum of allEnums) { const enumName = dbEnum.enum_name; const enumValue = dbEnum.enum_value; const enumSchema4 = dbEnum.enum_schema || "public"; const key = `${enumSchema4}.${enumName}`; if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) { enumsToReturn[key].values.push(enumValue); } else { enumsToReturn[key] = { name: enumName, values: [enumValue], schema: enumSchema4 }; } } if (progressCallback) { progressCallback("enums", Object.keys(enumsToReturn).length, "done"); } const allRoles = await db.query( `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;` ); const rolesToReturn = {}; const preparedRoles = prepareRoles(entities); if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) { for (const dbRole of allRoles) { if (preparedRoles.useRoles) { rolesToReturn[dbRole.rolname] = { createDb: dbRole.rolcreatedb, createRole: dbRole.rolcreatedb, inherit: dbRole.rolinherit, name: dbRole.rolname }; } else { if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue; if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue; if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue; if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue; rolesToReturn[dbRole.rolname] = { createDb: dbRole.rolcreatedb, createRole: dbRole.rolcreaterole, inherit: dbRole.rolinherit, name: dbRole.rolname }; } } } const schemasForLinkedPoliciesInSchema = Object.values(tsSchema?.policies ?? {}).map((it) => it.schema); const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t6) => `schemaname = '${t6}'`).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' AND con.contype = 'c';`); columnsCount += tableResponse.length; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const tableForeignKeys = await db.query( `SELECT con.contype AS constraint_type, nsp.nspname AS constraint_schema, con.conname AS constraint_name, rel.relname AS table_name, att.attname AS column_name, fnsp.nspname AS foreign_table_schema, frel.relname AS foreign_table_name, fatt.attname AS foreign_column_name, CASE con.confupdtype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'n' THEN 'SET NULL' WHEN 'c' THEN 'CASCADE' WHEN 'd' THEN 'SET DEFAULT' END AS update_rule, CASE con.confdeltype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'n' THEN 'SET NULL' WHEN 'c' THEN 'CASCADE' WHEN 'd' THEN 'SET DEFAULT' END AS delete_rule FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey) AND att.attrelid = con.conrelid LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey) AND fatt.attrelid = con.confrelid WHERE nsp.nspname = '${tableSchema}' AND rel.relname = '${tableName}' AND con.contype IN ('f');` ); foreignKeysCount += tableForeignKeys.length; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } for (const fk5 of tableForeignKeys) { const columnFrom = fk5.column_name; const tableTo = fk5.foreign_table_name; const columnTo = fk5.foreign_column_name; const schemaTo = fk5.foreign_table_schema; const foreignKeyName = fk5.constraint_name; const onUpdate = fk5.update_rule?.toLowerCase(); const onDelete = fk5.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((c5) => c5.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 i6 = 1; i6 < Number(columnDimensions); i6++) { columnTypeMapped += "[]"; } } columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char"); columnTypeMapped = trimChar(columnTypeMapped, '"'); columnToReturn[columnName] = { name: columnName, type: ( // filter vectors, but in future we should filter any extension that was installed by user columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped ), typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0, primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2, // default: isSerial ? undefined : defaultValue, notNull: columnResponse.is_nullable === "NO", generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0, identity: isIdentity ? { type: identityGeneration, name: identityName, increment: stringFromDatabaseIdentityProperty(identityIncrement), minValue: stringFromDatabaseIdentityProperty(identityMinimum), maxValue: stringFromDatabaseIdentityProperty(identityMaximum), startWith: stringFromDatabaseIdentityProperty(identityStart), cache: 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_indexdef(i.indexrelid, k.i, false)) AS column_name, CASE WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1 ELSE 0 END AS is_expression, i.indoption[k.i-1] & 1 = 1 AS descending, i.indoption[k.i-1] & 2 = 2 AS nulls_first, pg_get_expr( i.indpred, i.indrelid ) as where, opc.opcname FROM pg_class t LEFT JOIN pg_index i ON t.oid = i.indrelid LEFT JOIN pg_class ic ON ic.oid = i.indexrelid CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i) LEFT JOIN pg_attribute AS a ON i.indrelid = a.attrelid AND k.attnum = a.attnum JOIN pg_namespace c on c.oid = t.relnamespace LEFT JOIN pg_am AS am ON ic.relam = am.oid JOIN pg_opclass opc ON opc.oid = ANY(i.indclass) WHERE c.nspname = '${tableSchema}' AND t.relname = '${tableName}';` ); const dbIndexFromConstraint = await db.query( `SELECT idx.indexrelname AS index_name, idx.relname AS table_name, schemaname, CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint FROM pg_stat_user_indexes idx LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}' group by index_name, table_name,schemaname, generated_by_constraint;` ); const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map( (it) => it.index_name ); for (const dbIndex of dbIndexes) { const 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 desc = dbIndex.descending; const nullsFirst = dbIndex.nulls_first; const mappedWith = {}; if (indexWith !== null) { indexWith.forEach((it) => { const splitted = it.split("="); mappedWith[splitted[0]] = splitted[1]; }); } if (idxsInConsteraint.includes(indexName2)) continue; if (typeof indexToReturn[indexName2] !== "undefined") { indexToReturn[indexName2].columns.push({ expression: indexColumnName, asc: !desc, nulls: nullsFirst ? "first" : "last", opclass, isExpression }); } else { indexToReturn[indexName2] = { name: indexName2, columns: [ { expression: indexColumnName, asc: !desc, nulls: nullsFirst ? "first" : "last", opclass, isExpression } ], isUnique: indexIsUnique, // should not be a part of diff detects concurrently: false, method: indexMethod, where: indexWhere === null ? void 0 : indexWhere, with: mappedWith }; } } indexesCount += Object.keys(indexToReturn).length; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } result[`${tableSchema}.${tableName}`] = { name: tableName, schema: tableSchema !== "public" ? tableSchema : "", columns: columnToReturn, indexes: indexToReturn, foreignKeys: foreignKeysToReturn, compositePrimaryKeys: primaryKeys, uniqueConstraints: uniqueConstrains, checkConstraints, policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {}, isRLSEnabled: row.rls_enabled }; } catch (e6) { rej(e6); return; } res(""); }); }); if (progressCallback) { progressCallback("tables", tableCount, "done"); } for await (const _3 of all) { } const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => { return new Promise(async (res, rej) => { 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 i6 = 1; i6 < Number(columnDimensions); i6++) { columnTypeMapped += "[]"; } } columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char"); columnTypeMapped = trimChar(columnTypeMapped, '"'); columnToReturn[columnName] = { name: columnName, type: ( // filter vectors, but in future we should filter any extension that was installed by user columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped ), typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0, primaryKey, notNull: viewResponse.is_nullable === "NO", generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0, identity: isIdentity ? { type: identityGeneration, name: identityName, increment: stringFromDatabaseIdentityProperty(identityIncrement), minValue: stringFromDatabaseIdentityProperty(identityMinimum), maxValue: stringFromDatabaseIdentityProperty(identityMaximum), startWith: stringFromDatabaseIdentityProperty(identityStart), cache: 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 (e6) { rej(e6); return; } res(""); }); }); viewsCount = allViews.length; for await (const _3 of allViews) { } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("indexes", indexesCount, "done"); progressCallback("fks", foreignKeysCount, "done"); progressCallback("checks", checksCount, "done"); progressCallback("views", viewsCount, "done"); } const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it])); return { version: "7", dialect: "postgresql", tables: result, enums: enumsToReturn, schemas: schemasObject, sequences: sequencesToReturn, roles: rolesToReturn, policies, views, _meta: { schemas: {}, tables: {}, columns: {} }, internal: internals }; }; defaultForColumn = (column6, internals, tableName) => { const columnName = column6.column_name; const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false; if (column6.column_default === null || column6.column_default === void 0 || column6.data_type === "serial" || column6.data_type === "smallserial" || column6.data_type === "bigserial") { return void 0; } if (column6.column_default.endsWith("[]")) { column6.column_default = column6.column_default.slice(0, -2); } column6.column_default = column6.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, ""); const columnDefaultAsString = column6.column_default.toString(); if (isArray) { return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => { if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type.slice(0, -2))) { return value; } else if (column6.data_type.startsWith("timestamp")) { return `${value}`; } else if (column6.data_type.slice(0, -2) === "interval") { return value.replaceAll('"', `"`); } else if (column6.data_type.slice(0, -2) === "boolean") { return value === "t" ? "true" : "false"; } else if (["json", "jsonb"].includes(column6.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(column6.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 (column6.data_type.includes("numeric")) { return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`; } else if (column6.data_type === "json" || column6.data_type === "jsonb") { const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1))); return `'${jsonWithoutSpaces}'::${column6.data_type}`; } else if (column6.data_type === "boolean") { return column6.column_default === "true"; } else if (columnDefaultAsString === "NULL") { return `NULL`; } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) { return columnDefaultAsString; } else { return `${columnDefaultAsString.replace(/\\/g, "`\\")}`; } }; getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => { return db.query( `SELECT a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name a.attname AS column_name, -- Column name CASE WHEN NOT a.attisdropped THEN CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END ELSE NULL END AS is_nullable, -- NULL or NOT NULL constraint a.attndims AS array_dimensions, -- Array dimensions CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND EXISTS ( SELECT FROM pg_attrdef ad WHERE ad.adrelid = a.attrelid AND ad.adnum = a.attnum AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)' ) THEN CASE a.atttypid WHEN 'int'::regtype THEN 'serial' WHEN 'int8'::regtype THEN 'bigserial' WHEN 'int2'::regtype THEN 'smallserial' END ELSE format_type(a.atttypid, a.atttypmod) END AS data_type, -- Column data type -- ns.nspname AS type_schema, -- Schema name pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any) c.column_default, -- Column default value c.data_type AS additional_dt, -- Data type from information_schema c.udt_name AS enum_name, -- Enum type (if applicable) c.is_generated, -- Is it a generated column? c.generation_expression, -- Generation expression (if generated) c.is_identity, -- Is it an identity column? c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT) c.identity_start, -- Start value of identity column c.identity_increment, -- Increment for identity column c.identity_maximum, -- Maximum value for identity column c.identity_minimum, -- Minimum value for identity column c.identity_cycle, -- Does the identity column cycle? enum_ns.nspname AS type_schema -- Schema of the enum type FROM pg_attribute a JOIN pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info JOIN pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info LEFT JOIN information_schema.columns c ON c.column_name = a.attname AND c.table_schema = ns.nspname AND c.table_name = cls.relname -- Match schema and table/view name LEFT JOIN pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info LEFT JOIN pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema WHERE a.attnum > 0 -- Valid column numbers only AND NOT a.attisdropped -- Skip dropped columns AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m') AND ns.nspname = '${schema6}' -- Filter by schema AND cls.relname = '${table6}' -- Filter by table name ORDER BY a.attnum; -- Order by column number` ); }; } }); // src/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 text = ``; this.data.items.forEach((it, idx) => { text += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : ` ${it.label}`; text += idx != this.data.items.length - 1 ? "\n" : ""; }); return text; } result() { return { index: this.data.selectedIdx, value: this.data.items[this.data.selectedIdx].value }; } }; } }); // src/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 line of lines) { if (line.includes("GENERATED ALWAYS AS")) { const parts = line.trim().split(/\s+/); const columnName = parts[0].replace(/[`'"]/g, ""); const expression = line.substring(line.indexOf("("), line.indexOf(")") + 1).trim(); const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i)); let type = "virtual"; if (typeIndex !== -1) { type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase(); } columns[columnName] = { columnName, expression, type }; } } return columns; } function filterIgnoredTablesByField(fieldName) { return `${fieldName} != '__drizzle_migrations' AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`; } var import_drizzle_orm2, import_sqlite_core, generateSqliteSnapshot, fromDatabase2; var init_sqliteSerializer = __esm({ "src/serializer/sqliteSerializer.ts"() { "use strict"; init_source(); import_drizzle_orm2 = require("drizzle-orm"); import_sqlite_core = require("drizzle-orm/sqlite-core"); init_outputs(); init_utils(); init_utils2(); generateSqliteSnapshot = (tables, views, casing2) => { const dialect6 = new import_sqlite_core.SQLiteSyncDialect({ casing: casing2 }); const result = {}; const resultViews = {}; const internal = { indexes: {} }; for (const table6 of tables) { const columnsObject = {}; const indexesObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const checkConstraintObject = {}; const checksInTable = {}; const { name: tableName, columns, indexes, checks, foreignKeys: tableForeignKeys, primaryKeys, uniqueConstraints } = (0, import_sqlite_core.getTableConfig)(table6); columns.forEach((column6) => { const name = getColumnCasing(column6, casing2); const notNull = column6.notNull; const primaryKey = column6.primary; const generated = column6.generated; const columnToSet = { name, type: column6.getSQLType(), primaryKey, notNull, autoincrement: (0, import_drizzle_orm2.is)(column6, import_sqlite_core.SQLiteBaseInteger) ? column6.autoIncrement : false, generated: generated ? { as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`, type: generated.mode ?? "virtual" } : void 0 }; if (column6.default !== void 0) { if ((0, import_drizzle_orm2.is)(column6.default, import_drizzle_orm2.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { columnToSet.default = typeof column6.default === "string" ? `'${escapeSingleQuotes(column6.default)}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default; } } columnsObject[name] = columnToSet; if (column6.isUnique) { const existingUnique = indexesObject[column6.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( column6.uniqueName )} on the ${source_default.underline.blue( name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns `)}` ); process.exit(1); } indexesObject[column6.uniqueName] = { name: column6.uniqueName, columns: [columnToSet.name], isUnique: true }; } }); const foreignKeys = tableForeignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete ?? "no action"; const onUpdate = fk5.onUpdate ?? "no action"; const reference = fk5.reference(); const referenceFT = reference.foreignTable; const tableTo = (0, import_drizzle_orm2.getTableName)(referenceFT); const originalColumnsFrom = reference.columns.map((it) => it.name); const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2)); const originalColumnsTo = reference.foreignColumns.map((it) => it.name); const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2)); let name = fk5.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) { name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]); } for (let i6 = 0; i6 < originalColumnsTo.length; i6++) { name = name.replace(originalColumnsTo[i6], columnsTo[i6]); } } return { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate }; }); foreignKeys.forEach((it) => { foreignKeysObject[it.name] = it; }); indexes.forEach((value) => { const columns2 = value.config.columns; const name = value.config.name; let indexColumns = columns2.map((it) => { if ((0, import_drizzle_orm2.is)(it, import_drizzle_orm2.SQL)) { const sql = dialect6.sqlToQuery(it, "indexes").sql; if (typeof internal.indexes[name] === "undefined") { internal.indexes[name] = { columns: { [sql]: { isExpression: true } } }; } else { if (typeof internal.indexes[name]?.columns[sql] === "undefined") { internal.indexes[name].columns[sql] = { isExpression: true }; } else { internal.indexes[name].columns[sql].isExpression = true; } } return sql; } else { return getColumnCasing(it, casing2); } }); let where = void 0; if (value.config.where !== void 0) { if ((0, import_drizzle_orm2.is)(value.config.where, import_drizzle_orm2.SQL)) { where = dialect6.sqlToQuery(value.config.where).sql; } } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, where }; }); uniqueConstraints?.map((unq) => { const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2)); const name = unq.name ?? (0, import_sqlite_core.uniqueKeyName)(table6, columnNames); const existingUnique = indexesObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } indexesObject[name] = { name: unq.name, columns: columnNames, isUnique: true }; }); primaryKeys.forEach((it) => { if (it.columns.length > 1) { const originalColumnNames = it.columns.map((c5) => c5.name); const columnNames = it.columns.map((c5) => getColumnCasing(c5, casing2)); let name = it.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnNames.length; i6++) { name = name.replace(originalColumnNames[i6], columnNames[i6]); } } primaryKeysObject[name] = { columns: columnNames, name }; } 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: dialect6.sqlToQuery(check.value).sql }; }); result[tableName] = { name: tableName, columns: columnsObject, indexes: indexesObject, foreignKeys: foreignKeysObject, compositePrimaryKeys: primaryKeysObject, uniqueConstraints: uniqueConstraintObject, checkConstraints: checkConstraintObject }; } for (const view5 of views) { const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core.getViewConfig)(view5); const columnsObject = {}; const existingView = resultViews[name]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue( schema6 ?? "public" )} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm2.is)(selectedFields[key], import_sqlite_core.SQLiteColumn)) { const column6 = selectedFields[key]; const notNull = column6.notNull; const primaryKey = column6.primary; const generated = column6.generated; const columnToSet = { name: column6.name, type: column6.getSQLType(), primaryKey, notNull, autoincrement: (0, import_drizzle_orm2.is)(column6, import_sqlite_core.SQLiteBaseInteger) ? column6.autoIncrement : false, generated: generated ? { as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`, type: generated.mode ?? "virtual" } : void 0 }; if (column6.default !== void 0) { if ((0, import_drizzle_orm2.is)(column6.default, import_drizzle_orm2.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { columnToSet.default = typeof column6.default === "string" ? `'${column6.default}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default; } } columnsObject[column6.name] = columnToSet; } } resultViews[name] = { columns: columnsObject, name, isExisting, definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql }; } return { version: "6", dialect: "sqlite", tables: result, views: resultViews, enums: {}, _meta: { tables: {}, columns: {} }, internal }; }; fromDatabase2 = async (db, tablesFilter = (table6) => true, progressCallback) => { const result = {}; const resultViews = {}; const columns = await db.query(`SELECT m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk, p.hidden as hidden, m.sql, m.type as type FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p WHERE (m.type = 'table' OR m.type = 'view') AND ${filterIgnoredTablesByField("m.tbl_name")};`); const tablesWithSeq = []; const seq = await db.query(`SELECT * FROM sqlite_master WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*' AND ${filterIgnoredTablesByField("tbl_name")};`); for (const s6 of seq) { tablesWithSeq.push(s6.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 column6 of columns) { if (!tablesFilter(column6.tableName)) continue; if (column6.type !== "view") { columnsCount += 1; } if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const tableName = column6.tableName; tablesCount.add(tableName); if (progressCallback) { progressCallback("tables", tablesCount.size, "fetching"); } const columnName = column6.columnName; const isNotNull = column6.notNull === 1; const columnType = column6.columnType; const isPrimary = column6.pk !== 0; const columnDefault = column6.defaultValue; const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName); if (isPrimary) { if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } const table6 = result[tableName]; if (column6.hidden === 2 || column6.hidden === 3) { if (typeof tableToGeneratedColumnsInfo[column6.tableName] === "undefined") { tableToGeneratedColumnsInfo[column6.tableName] = extractGeneratedColumns( column6.sql ); } } const newColumn = { default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes( columnDefault ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`, autoincrement: isAutoincrement, name: columnName, type: mapSqlToSqliteType(columnType), primaryKey: false, notNull: isNotNull, generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? { type: tableToGeneratedColumnsInfo[tableName][columnName].type, as: tableToGeneratedColumnsInfo[tableName][columnName].expression } : void 0 }; if (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraints: {} }; } else { result[tableName].columns[columnName] = newColumn; } } for (const [key, value] of Object.entries(tableToPk)) { if (value.length > 1) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}_pk`]: { columns: value, name: `${key}_${value.join("_")}_pk` } }; } else if (value.length === 1) { result[key].columns[value[0]].primaryKey = true; } else { } } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } try { const fks = await db.query(`SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq" FROM sqlite_master m, pragma_foreign_key_list(m.name) as f WHERE ${filterIgnoredTablesByField("m.tbl_name")};`); const fkByTableName = {}; for (const fkRow of fks) { foreignKeysCount += 1; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } const tableName = fkRow.tableFrom; const columnName = fkRow.from; const refTableName = fkRow.tableTo; const refColumnName = fkRow.to; const updateRule = fkRow.onUpdate; const deleteRule = fkRow.onDelete; const sequence = fkRow.seq; const id = fkRow.id; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") { fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName); fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName); } else { fkByTableName[`${tableName}_${id}`] = { name: "", tableFrom: tableName, tableTo: refTableName, columnsFrom: [columnName], columnsTo: [refColumnName], onDelete: deleteRule?.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 (e6) { } if (progressCallback) { progressCallback("fks", foreignKeysCount, "done"); } const idxs = await db.query(`SELECT m.tbl_name as tableName, il.name as indexName, ii.name as columnName, il.[unique] as isUnique, il.seq as seq FROM sqlite_master AS m, pragma_index_list(m.name) AS il, pragma_index_info(il.name) AS ii WHERE m.type = 'table' AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\' AND ${filterIgnoredTablesByField("m.tbl_name")};`); for (const idxRow of idxs) { const tableName = idxRow.tableName; const constraintName = idxRow.indexName; const columnName = idxRow.columnName; const isUnique = idxRow.isUnique === 1; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) { tableInResult.indexes[constraintName].columns.push(columnName); } else { tableInResult.indexes[constraintName] = { name: constraintName, columns: columnName ? [columnName] : [], isUnique }; } } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); } const views = await db.query( `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';` ); viewsCount = views.length; if (progressCallback) { progressCallback("views", viewsCount, "fetching"); } for (const view5 of views) { const viewName = view5["view_name"]; const sql = view5["sql"]; const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i"); const match2 = sql.match(regex); if (!match2) { console.log("Could not process view"); process.exit(1); } const viewDefinition = match2[1]; const columns2 = result[viewName].columns; delete result[viewName]; resultViews[viewName] = { columns: columns2, isExisting: false, name: viewName, definition: viewDefinition }; } if (progressCallback) { progressCallback("views", viewsCount, "done"); } const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi; const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi; let checkCounter = 0; const checkConstraints = {}; const checks = await db.query(`SELECT name as "tableName", sql as "sql" FROM sqlite_master WHERE type = 'table' AND ${filterIgnoredTablesByField("tbl_name")};`); for (const check of checks) { if (!tablesFilter(check.tableName)) continue; const { tableName, sql } = check; let namedChecks = [...sql.matchAll(namedCheckPattern)]; if (namedChecks.length > 0) { namedChecks.forEach(([_3, checkName, checkValue]) => { checkConstraints[checkName] = { name: checkName, value: checkValue.trim() }; }); } else { let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)]; unnamedChecks.forEach(([_3, checkValue]) => { let checkName = `${tableName}_check_${++checkCounter}`; checkConstraints[checkName] = { name: checkName, value: checkValue.trim() }; }); } checksCount += Object.values(checkConstraints).length; if (progressCallback) { progressCallback("checks", checksCount, "fetching"); } const table6 = result[tableName]; if (!table6) { result[tableName] = { name: tableName, columns: {}, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraints }; } else { result[tableName].checkConstraints = checkConstraints; } } if (progressCallback) { progressCallback("checks", checksCount, "done"); } return { version: "6", dialect: "sqlite", tables: result, views: resultViews, enums: {}, _meta: { tables: {}, columns: {} } }; }; } }); // src/extensions/getTablesFilterByExtensions.ts var getTablesFilterByExtensions; var init_getTablesFilterByExtensions = __esm({ "src/extensions/getTablesFilterByExtensions.ts"() { "use strict"; getTablesFilterByExtensions = ({ extensionsFilters, dialect: dialect6 }) => { if (extensionsFilters) { if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") { return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"]; } } return []; }; } }); // src/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 import_drizzle_orm3, import_mysql_core, handleEnumType, generateMySqlSnapshot, fromDatabase3; var init_mysqlSerializer = __esm({ "src/serializer/mysqlSerializer.ts"() { "use strict"; init_source(); import_drizzle_orm3 = require("drizzle-orm"); import_mysql_core = require("drizzle-orm/mysql-core"); init_outputs(); init_utils(); init_utils2(); handleEnumType = (type) => { let str = type.split("(")[1]; str = str.substring(0, str.length - 1); const values = str.split(",").map((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.length - 1))}'`); return `enum(${values.join(",")})`; }; generateMySqlSnapshot = (tables, views, casing2) => { const dialect6 = new import_mysql_core.MySqlDialect({ casing: casing2 }); const result = {}; const resultViews = {}; const internal = { tables: {}, indexes: {} }; for (const table6 of tables) { const { name: tableName, columns, indexes, foreignKeys, schema: schema6, checks, primaryKeys, uniqueConstraints } = (0, import_mysql_core.getTableConfig)(table6); const columnsObject = {}; const indexesObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const checkConstraintObject = {}; let checksInTable = {}; columns.forEach((column6) => { const name = getColumnCasing(column6, casing2); const notNull = column6.notNull; const sqlType = column6.getSQLType(); const sqlTypeLowered = sqlType.toLowerCase(); const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement; const generated = column6.generated; const columnToSet = { name, type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType, primaryKey: false, // If field is autoincrement it's notNull by default // notNull: autoIncrement ? true : notNull, notNull, autoincrement: autoIncrement, onUpdate: column6.hasOnUpdateNow, generated: generated ? { as: (0, import_drizzle_orm3.is)(generated.as, import_drizzle_orm3.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as, type: generated.mode ?? "stored" } : void 0 }; if (column6.primary) { primaryKeysObject[`${tableName}_${name}`] = { name: `${tableName}_${name}`, columns: [name] }; } if (column6.isUnique) { const existingUnique = uniqueConstraintObject[column6.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( column6.uniqueName )} on the ${source_default.underline.blue( name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns `)}` ); process.exit(1); } uniqueConstraintObject[column6.uniqueName] = { name: column6.uniqueName, columns: [columnToSet.name] }; } if (column6.default !== void 0) { if ((0, import_drizzle_orm3.is)(column6.default, import_drizzle_orm3.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { if (typeof column6.default === "string") { columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`; } else { if (sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column6.default)}'`; } else if (column6.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column6.default; } } if (["blob", "text", "json"].includes(column6.getSQLType())) { columnToSet.default = `(${columnToSet.default})`; } } } columnsObject[name] = columnToSet; }); primaryKeys.map((pk) => { const originalColumnNames = pk.columns.map((c5) => c5.name); const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2)); let name = pk.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnNames.length; i6++) { name = name.replace(originalColumnNames[i6], columnNames[i6]); } } primaryKeysObject[name] = { name, columns: columnNames }; for (const column6 of pk.columns) { columnsObject[getColumnCasing(column6, casing2)].notNull = true; } }); uniqueConstraints?.map((unq) => { const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2)); const name = unq.name ?? (0, import_mysql_core.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, columns: columnNames }; }); const fks = foreignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete ?? "no action"; const onUpdate = fk5.onUpdate ?? "no action"; const reference = fk5.reference(); const referenceFT = reference.foreignTable; const tableTo = (0, import_drizzle_orm3.getTableName)(referenceFT); const originalColumnsFrom = reference.columns.map((it) => it.name); const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2)); const originalColumnsTo = reference.foreignColumns.map((it) => it.name); const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2)); let name = fk5.getName(); if (casing2 !== void 0) { for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) { name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]); } for (let i6 = 0; i6 < originalColumnsTo.length; i6++) { name = name.replace(originalColumnsTo[i6], columnsTo[i6]); } } return { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate }; }); fks.forEach((it) => { foreignKeysObject[it.name] = it; }); indexes.forEach((value) => { const columns2 = value.config.columns; const name = value.config.name; let indexColumns = columns2.map((it) => { if ((0, import_drizzle_orm3.is)(it, import_drizzle_orm3.SQL)) { const sql = dialect6.sqlToQuery(it, "indexes").sql; if (typeof internal.indexes[name] === "undefined") { internal.indexes[name] = { columns: { [sql]: { isExpression: true } } }; } else { if (typeof internal.indexes[name]?.columns[sql] === "undefined") { internal.indexes[name].columns[sql] = { isExpression: true }; } else { internal.indexes[name].columns[sql].isExpression = true; } } return sql; } else { return `${getColumnCasing(it, casing2)}`; } }); if (value.config.unique) { if (typeof uniqueConstraintObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique index ${source_default.underline.blue( name )} on the ${source_default.underline.blue( indexColumns.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( uniqueConstraintObject[name].columns.join(",") )} columns ` )}` ); process.exit(1); } } else { if (typeof foreignKeysObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint. We have encountered a collision between the index name on columns ${source_default.underline.blue( indexColumns.join(",") )} and the foreign key on columns ${source_default.underline.blue( foreignKeysObject[name].columnsFrom.join(",") )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html ` )}` ); process.exit(1); } } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, using: value.config.using, algorithm: value.config.algorithm, 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: dialect6.sqlToQuery(check.value).sql }; }); if (!schema6) { result[tableName] = { name: tableName, columns: columnsObject, indexes: indexesObject, foreignKeys: foreignKeysObject, compositePrimaryKeys: primaryKeysObject, uniqueConstraints: uniqueConstraintObject, checkConstraint: checkConstraintObject }; } } for (const view5 of views) { const { isExisting, name, query, schema: schema6, selectedFields, algorithm, sqlSecurity, withCheckOption } = (0, import_mysql_core.getViewConfig)(view5); const columnsObject = {}; const existingView = resultViews[name]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue( schema6 ?? "public" )} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm3.is)(selectedFields[key], import_mysql_core.MySqlColumn)) { const column6 = selectedFields[key]; const notNull = column6.notNull; const sqlTypeLowered = column6.getSQLType().toLowerCase(); const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement; const generated = column6.generated; const columnToSet = { name: column6.name, type: column6.getSQLType(), primaryKey: false, // If field is autoincrement it's notNull by default // notNull: autoIncrement ? true : notNull, notNull, autoincrement: autoIncrement, onUpdate: column6.hasOnUpdateNow, generated: generated ? { as: (0, import_drizzle_orm3.is)(generated.as, import_drizzle_orm3.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as, type: generated.mode ?? "stored" } : void 0 }; if (column6.default !== void 0) { if ((0, import_drizzle_orm3.is)(column6.default, import_drizzle_orm3.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { if (typeof column6.default === "string") { columnToSet.default = `'${column6.default}'`; } else { if (sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column6.default)}'`; } else if (column6.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column6.default; } } if (["blob", "text", "json"].includes(column6.getSQLType())) { columnToSet.default = `(${columnToSet.default})`; } } } columnsObject[column6.name] = columnToSet; } } resultViews[name] = { columns: columnsObject, name, isExisting, definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql, withCheckOption, algorithm: algorithm ?? "undefined", // set default values sqlSecurity: sqlSecurity ?? "definer" // set default values }; } return { version: "5", dialect: "mysql", tables: result, views: resultViews, _meta: { tables: {}, columns: {} }, internal }; }; fromDatabase3 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => { const result = {}; const internals = { tables: {}, indexes: {} }; const columns = await db.query(`select * from information_schema.columns where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations' order by table_name, ordinal_position;`); const response = columns; const schemas = []; let columnsCount = 0; let tablesCount = /* @__PURE__ */ new Set(); let indexesCount = 0; let foreignKeysCount = 0; let checksCount = 0; let viewsCount = 0; const idxs = await db.query( `select * from INFORMATION_SCHEMA.STATISTICS WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';` ); const idxRows = idxs; for (const column6 of response) { if (!tablesFilter(column6["TABLE_NAME"])) continue; columnsCount += 1; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const schema6 = column6["TABLE_SCHEMA"]; const tableName = column6["TABLE_NAME"]; tablesCount.add(`${schema6}.${tableName}`); if (progressCallback) { progressCallback("columns", tablesCount.size, "fetching"); } const columnName = column6["COLUMN_NAME"]; const isNullable = column6["IS_NULLABLE"] === "YES"; const dataType = column6["DATA_TYPE"]; const columnType = column6["COLUMN_TYPE"]; const isPrimary = column6["COLUMN_KEY"] === "PRI"; const columnDefault = column6["COLUMN_DEFAULT"]; const collation = column6["CHARACTER_SET_NAME"]; const geenratedExpression = column6["GENERATION_EXPRESSION"]; let columnExtra = column6["EXTRA"]; let isAutoincrement = false; let isDefaultAnExpression = false; if (typeof column6["EXTRA"] !== "undefined") { columnExtra = column6["EXTRA"]; isAutoincrement = column6["EXTRA"] === "auto_increment"; isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED"); } if (schema6 !== inputSchema) { schemas.push(schema6); } const table6 = result[tableName]; let changedType = columnType; if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) { const uniqueIdx = idxRows.filter( (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0 ); if (uniqueIdx && uniqueIdx.length === 1) { changedType = columnType.replace("bigint unsigned", "serial"); } } if (columnType.includes("decimal(10,0)")) { changedType = columnType.replace("decimal(10,0)", "decimal"); } let onUpdate = void 0; if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) { onUpdate = true; } const newColumn = { default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`, autoincrement: isAutoincrement, name: columnName, type: changedType, primaryKey: false, notNull: !isNullable, onUpdate, generated: geenratedExpression ? { as: geenratedExpression, type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored" } : void 0 }; if (isDefaultAnExpression) { if (typeof internals.tables[tableName] === "undefined") { internals.tables[tableName] = { columns: { [columnName]: { isDefaultAnExpression: true } } }; } else { if (typeof internals.tables[tableName].columns[columnName] === "undefined") { internals.tables[tableName].columns[columnName] = { isDefaultAnExpression: true }; } else { internals.tables[tableName].columns[columnName].isDefaultAnExpression = true; } } } if (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraint: {} }; } else { result[tableName].columns[columnName] = newColumn; } } const tablePks = await db.query( `SELECT table_name, column_name, ordinal_position FROM information_schema.table_constraints t LEFT JOIN information_schema.key_column_usage k USING(constraint_name,table_schema,table_name) WHERE t.constraint_type='PRIMARY KEY' and table_name != '__drizzle_migrations' AND t.table_schema = '${inputSchema}' ORDER BY ordinal_position` ); const tableToPk = {}; const tableToPkRows = tablePks; for (const tableToPkRow of tableToPkRows) { const tableName = tableToPkRow["TABLE_NAME"]; const columnName = tableToPkRow["COLUMN_NAME"]; const position = tableToPkRow["ordinal_position"]; if (typeof result[tableName] === "undefined") { continue; } if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } for (const [key, value] of Object.entries(tableToPk)) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}`]: { name: `${key}_${value.join("_")}`, columns: value } }; } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } try { const fks = await db.query( `SELECT kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME, rc.UPDATE_RULE, rc.DELETE_RULE FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu LEFT JOIN information_schema.referential_constraints rc ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY' AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;` ); const fkRows = fks; for (const fkRow of fkRows) { foreignKeysCount += 1; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } const tableSchema = fkRow["TABLE_SCHEMA"]; const tableName = fkRow["TABLE_NAME"]; const constraintName = fkRow["CONSTRAINT_NAME"]; const columnName = fkRow["COLUMN_NAME"]; const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"]; const refTableName = fkRow["REFERENCED_TABLE_NAME"]; const refColumnName = fkRow["REFERENCED_COLUMN_NAME"]; const updateRule = fkRow["UPDATE_RULE"]; const deleteRule = fkRow["DELETE_RULE"]; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") { tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName); tableInResult.foreignKeys[constraintName].columnsTo.push( refColumnName ); } else { tableInResult.foreignKeys[constraintName] = { name: constraintName, tableFrom: tableName, tableTo: refTableName, columnsFrom: [columnName], columnsTo: [refColumnName], onDelete: deleteRule?.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 (e6) { } if (progressCallback) { progressCallback("fks", foreignKeysCount, "done"); } for (const idxRow of idxRows) { const tableSchema = idxRow["TABLE_SCHEMA"]; const tableName = idxRow["TABLE_NAME"]; const constraintName = idxRow["INDEX_NAME"]; const columnName = idxRow["COLUMN_NAME"]; const isUnique = idxRow["NON_UNIQUE"] === 0; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (isUnique) { if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") { tableInResult.uniqueConstraints[constraintName].columns.push( columnName ); } else { tableInResult.uniqueConstraints[constraintName] = { name: constraintName, columns: [columnName] }; } } else { if (typeof tableInResult.foreignKeys[constraintName] === "undefined") { if (typeof tableInResult.indexes[constraintName] !== "undefined") { tableInResult.indexes[constraintName].columns.push(columnName); } else { tableInResult.indexes[constraintName] = { name: constraintName, columns: [columnName], isUnique }; } } } } const views = await db.query( `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';` ); const resultViews = {}; viewsCount = views.length; if (progressCallback) { progressCallback("views", viewsCount, "fetching"); } for await (const view5 of views) { const viewName = view5["TABLE_NAME"]; const definition = view5["VIEW_DEFINITION"]; const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase(); const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase(); const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`); const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/); const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0; const columns2 = result[viewName].columns; delete result[viewName]; resultViews[viewName] = { columns: columns2, isExisting: false, name: viewName, algorithm, definition, sqlSecurity, withCheckOption }; } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); progressCallback("views", viewsCount, "done"); } const checkConstraints = await db.query( `SELECT tc.table_name, tc.constraint_name, cc.check_clause FROM information_schema.table_constraints tc JOIN information_schema.check_constraints cc ON tc.constraint_name = cc.constraint_name WHERE tc.constraint_schema = '${inputSchema}' AND tc.constraint_type = 'CHECK';` ); checksCount += checkConstraints.length; if (progressCallback) { progressCallback("checks", checksCount, "fetching"); } for (const checkConstraintRow of checkConstraints) { const constraintName = checkConstraintRow["CONSTRAINT_NAME"]; const constraintValue = checkConstraintRow["CHECK_CLAUSE"]; const tableName = checkConstraintRow["TABLE_NAME"]; const tableInResult = result[tableName]; tableInResult.checkConstraint[constraintName] = { name: constraintName, value: constraintValue }; } if (progressCallback) { progressCallback("checks", checksCount, "done"); } return { version: "5", dialect: "mysql", tables: result, views: resultViews, _meta: { tables: {}, columns: {} }, internal: internals }; }; } }); // src/cli/validations/cli.ts var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck; var init_cli = __esm({ "src/cli/validations/cli.ts"() { "use strict"; init_esm(); init_schemaValidator(); init_common(); cliConfigGenerate = objectType({ dialect: dialect4.optional(), schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), config: stringType().optional(), name: stringType().optional(), prefix: prefix.optional(), breakpoints: booleanType().optional().default(true), custom: booleanType().optional().default(false) }).strict(); pushParams = objectType({ dialect: dialect4, casing: casingType.optional(), schema: unionType([stringType(), stringType().array()]), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]), extensionsFilters: literalType("postgis").array().optional(), verbose: booleanType().optional(), strict: booleanType().optional(), entities: objectType({ roles: booleanType().or(objectType({ provider: stringType().optional(), include: stringType().array().optional(), exclude: stringType().array().optional() })).optional().default(false) }).optional() }).passthrough(); pullParams = objectType({ config: stringType().optional(), dialect: dialect4, out: stringType().optional().default("drizzle"), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]), extensionsFilters: literalType("postgis").array().optional(), casing, breakpoints: booleanType().optional().default(true), migrations: objectType({ prefix: prefix.optional().default("index") }).optional(), entities: objectType({ roles: booleanType().or(objectType({ provider: stringType().optional(), include: stringType().array().optional(), exclude: stringType().array().optional() })).optional().default(false) }).optional() }).passthrough(); configCheck = objectType({ dialect: dialect4.optional(), out: stringType().optional() }); cliConfigCheck = intersectionType( objectType({ config: stringType().optional() }), configCheck ); } }); // src/cli/validations/gel.ts var gelCredentials; var init_gel = __esm({ "src/cli/validations/gel.ts"() { "use strict"; init_esm(); init_views(); init_common(); gelCredentials = unionType([ objectType({ driver: undefinedType(), host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), tlsSecurity: unionType([ literalType("insecure"), literalType("no_host_verification"), literalType("strict"), literalType("default") ]).optional() }).transform((o5) => { delete o5.driver; return o5; }), objectType({ driver: undefinedType(), url: stringType().min(1), tlsSecurity: unionType([ literalType("insecure"), literalType("no_host_verification"), literalType("strict"), literalType("default") ]).optional() }).transform((o5) => { delete o5.driver; return o5; }), objectType({ driver: undefinedType() }).transform((o5) => { return void 0; }) ]); } }); // src/cli/validations/libsql.ts var libSQLCredentials; var init_libsql = __esm({ "src/cli/validations/libsql.ts"() { "use strict"; init_esm(); init_views(); init_common(); libSQLCredentials = objectType({ url: stringType().min(1), authToken: stringType().min(1).optional() }); } }); // src/cli/validations/mysql.ts var mysqlCredentials; var init_mysql = __esm({ "src/cli/validations/mysql.ts"() { "use strict"; init_esm(); init_views(); init_common(); init_outputs(); mysqlCredentials = unionType([ objectType({ host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ stringType(), objectType({ pfx: stringType().optional(), key: stringType().optional(), passphrase: stringType().optional(), cert: stringType().optional(), ca: unionType([stringType(), stringType().array()]).optional(), crl: unionType([stringType(), stringType().array()]).optional(), ciphers: stringType().optional(), rejectUnauthorized: booleanType().optional() }) ]).optional() }), objectType({ url: stringType().min(1) }) ]); } }); // src/cli/validations/postgres.ts var postgresCredentials; var init_postgres = __esm({ "src/cli/validations/postgres.ts"() { "use strict"; init_esm(); init_views(); init_common(); postgresCredentials = unionType([ objectType({ driver: undefinedType(), host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ literalType("require"), literalType("allow"), literalType("prefer"), literalType("verify-full"), booleanType(), objectType({}).passthrough() ]).optional() }).transform((o5) => { delete o5.driver; return o5; }), objectType({ driver: undefinedType(), url: stringType().min(1) }).transform((o5) => { delete o5.driver; return o5; }), 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/singlestore.ts var singlestoreCredentials; var init_singlestore = __esm({ "src/cli/validations/singlestore.ts"() { "use strict"; init_esm(); init_views(); init_common(); init_outputs(); singlestoreCredentials = unionType([ objectType({ host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ stringType(), objectType({ pfx: stringType().optional(), key: stringType().optional(), passphrase: stringType().optional(), cert: stringType().optional(), ca: unionType([stringType(), stringType().array()]).optional(), crl: unionType([stringType(), stringType().array()]).optional(), ciphers: stringType().optional(), rejectUnauthorized: booleanType().optional() }) ]).optional() }), objectType({ url: stringType().min(1) }) ]); } }); // src/cli/validations/sqlite.ts var sqliteCredentials; var init_sqlite = __esm({ "src/cli/validations/sqlite.ts"() { "use strict"; init_global(); init_esm(); init_views(); init_common(); sqliteCredentials = unionType([ objectType({ driver: literalType("turso"), url: stringType().min(1), authToken: stringType().min(1).optional() }), objectType({ driver: literalType("d1-http"), accountId: stringType().min(1), databaseId: stringType().min(1), token: stringType().min(1) }), objectType({ driver: undefinedType(), url: stringType().min(1) }).transform((o5) => { delete o5.driver; return o5; }) ]); } }); // src/cli/validations/studio.ts var credentials, studioCliParams, studioConfig; var init_studio = __esm({ "src/cli/validations/studio.ts"() { "use strict"; init_esm(); init_schemaValidator(); init_common(); init_mysql(); init_postgres(); init_sqlite(); credentials = intersectionType( postgresCredentials, mysqlCredentials, sqliteCredentials ); studioCliParams = objectType({ port: coerce.number().optional().default(4983), host: stringType().optional().default("127.0.0.1"), config: stringType().optional() }); studioConfig = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]).optional(), casing: casingType.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_utils3 = __esm({ "src/cli/commands/utils.ts"() { "use strict"; import_hanji7 = __toESM(require_hanji()); init_esm(); init_getTablesFilterByExtensions(); init_global(); init_schemaValidator(); init_serializer(); init_cli(); init_common(); init_gel(); init_libsql(); init_mysql(); init_outputs(); init_postgres(); init_singlestore(); init_sqlite(); init_studio(); init_views(); assertES5 = async (unregister) => { try { init_es5(); } catch (e6) { if ("errors" in e6 && Array.isArray(e6.errors) && e6.errors.length > 0) { const es5Error = e6.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(e6); 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: dialect4, out: stringType().optional().default("drizzle"), migrations: configMigrations }); } }); // src/serializer/pgImports.ts var import_drizzle_orm4, import_pg_core2, import_relations, prepareFromExports; var init_pgImports = __esm({ "src/serializer/pgImports.ts"() { "use strict"; import_drizzle_orm4 = require("drizzle-orm"); import_pg_core2 = require("drizzle-orm/pg-core"); import_relations = require("drizzle-orm/relations"); init_utils3(); prepareFromExports = (exports2) => { const tables = []; const enums = []; const schemas = []; const sequences = []; const roles = []; const policies = []; const views = []; const matViews = []; const relations = []; const i0values = Object.values(exports2); i0values.forEach((t6) => { if ((0, import_pg_core2.isPgEnum)(t6)) { enums.push(t6); return; } if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgTable)) { tables.push(t6); } if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgSchema)) { schemas.push(t6); } if ((0, import_pg_core2.isPgView)(t6)) { views.push(t6); } if ((0, import_pg_core2.isPgMaterializedView)(t6)) { matViews.push(t6); } if ((0, import_pg_core2.isPgSequence)(t6)) { sequences.push(t6); } if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgRole)) { roles.push(t6); } if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgPolicy)) { policies.push(t6); } if ((0, import_drizzle_orm4.is)(t6, import_relations.Relations)) { relations.push(t6); } }); return { tables, enums, schemas, sequences, views, matViews, roles, policies, relations }; }; } }); // src/serializer/singlestoreSerializer.ts function clearDefaults2(defaultValue, collate) { if (typeof collate === "undefined" || collate === null) { collate = `utf8mb4`; } let resultDefault = defaultValue; collate = `_${collate}`; if (defaultValue.startsWith(collate)) { resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, ""); if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) { return `('${resultDefault.substring(1, resultDefault.length - 1)}')`; } else { return `'${resultDefault}'`; } } else { return `(${resultDefault})`; } } var import_drizzle_orm5, import_singlestore_core, dialect5, generateSingleStoreSnapshot, fromDatabase4; var init_singlestoreSerializer = __esm({ "src/serializer/singlestoreSerializer.ts"() { "use strict"; init_source(); import_drizzle_orm5 = require("drizzle-orm"); import_singlestore_core = require("drizzle-orm/singlestore-core"); init_outputs(); init_utils2(); dialect5 = new import_singlestore_core.SingleStoreDialect(); generateSingleStoreSnapshot = (tables, casing2) => { const dialect6 = new import_singlestore_core.SingleStoreDialect({ casing: casing2 }); const result = {}; const internal = { tables: {}, indexes: {} }; for (const table6 of tables) { const { name: tableName, columns, indexes, schema: schema6, primaryKeys, uniqueConstraints } = (0, import_singlestore_core.getTableConfig)(table6); const columnsObject = {}; const indexesObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; columns.forEach((column6) => { const notNull = column6.notNull; const sqlTypeLowered = column6.getSQLType().toLowerCase(); const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement; const generated = column6.generated; const columnToSet = { name: column6.name, type: column6.getSQLType(), primaryKey: false, // If field is autoincrement it's notNull by default // notNull: autoIncrement ? true : notNull, notNull, autoincrement: autoIncrement, onUpdate: column6.hasOnUpdateNow, generated: generated ? { as: (0, import_drizzle_orm5.is)(generated.as, import_drizzle_orm5.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as, type: generated.mode ?? "stored" } : void 0 }; if (column6.primary) { primaryKeysObject[`${tableName}_${column6.name}`] = { name: `${tableName}_${column6.name}`, columns: [column6.name] }; } if (column6.isUnique) { const existingUnique = uniqueConstraintObject[column6.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( column6.uniqueName )} on the ${source_default.underline.blue( column6.name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns `)}` ); process.exit(1); } uniqueConstraintObject[column6.uniqueName] = { name: column6.uniqueName, columns: [columnToSet.name] }; } if (column6.default !== void 0) { if ((0, import_drizzle_orm5.is)(column6.default, import_drizzle_orm5.SQL)) { columnToSet.default = sqlToStr(column6.default, casing2); } else { if (typeof column6.default === "string") { columnToSet.default = `'${column6.default}'`; } else { if (sqlTypeLowered === "json" || Array.isArray(column6.default)) { columnToSet.default = `'${JSON.stringify(column6.default)}'`; } else if (column6.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column6.default; } } } } columnsObject[column6.name] = columnToSet; }); primaryKeys.map((pk) => { const columnNames = pk.columns.map((c5) => c5.name); primaryKeysObject[pk.getName()] = { name: pk.getName(), columns: columnNames }; for (const column6 of pk.columns) { columnsObject[column6.name].notNull = true; } }); uniqueConstraints?.map((unq) => { const columnNames = unq.columns.map((c5) => c5.name); const name = unq.name ?? (0, import_singlestore_core.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, columns: columnNames }; }); indexes.forEach((value) => { const columns2 = value.config.columns; const name = value.config.name; let indexColumns = columns2.map((it) => { if ((0, import_drizzle_orm5.is)(it, import_drizzle_orm5.SQL)) { const sql = dialect6.sqlToQuery(it, "indexes").sql; if (typeof internal.indexes[name] === "undefined") { internal.indexes[name] = { columns: { [sql]: { isExpression: true } } }; } else { if (typeof internal.indexes[name]?.columns[sql] === "undefined") { internal.indexes[name].columns[sql] = { isExpression: true }; } else { internal.indexes[name].columns[sql].isExpression = true; } } return sql; } else { return `${it.name}`; } }); if (value.config.unique) { if (typeof uniqueConstraintObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique index ${source_default.underline.blue( name )} on the ${source_default.underline.blue( indexColumns.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( uniqueConstraintObject[name].columns.join(",") )} columns ` )}` ); process.exit(1); } } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, using: value.config.using, algorithm: value.config.algorithm, lock: value.config.lock }; }); if (!schema6) { result[tableName] = { name: tableName, columns: columnsObject, indexes: indexesObject, compositePrimaryKeys: primaryKeysObject, uniqueConstraints: uniqueConstraintObject }; } } return { version: "1", dialect: "singlestore", tables: result, /* views: resultViews, */ _meta: { tables: {}, columns: {} }, internal }; }; fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => { const result = {}; const internals = { tables: {}, indexes: {} }; const columns = await db.query(`select * from information_schema.columns where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations' order by table_name, ordinal_position;`); const response = columns; const schemas = []; let columnsCount = 0; let tablesCount = /* @__PURE__ */ new Set(); let indexesCount = 0; const idxs = await db.query( `select * from INFORMATION_SCHEMA.STATISTICS WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';` ); const idxRows = idxs; for (const column6 of response) { if (!tablesFilter(column6["TABLE_NAME"])) continue; columnsCount += 1; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const schema6 = column6["TABLE_SCHEMA"]; const tableName = column6["TABLE_NAME"]; tablesCount.add(`${schema6}.${tableName}`); if (progressCallback) { progressCallback("columns", tablesCount.size, "fetching"); } const columnName = column6["COLUMN_NAME"]; const isNullable = column6["IS_NULLABLE"] === "YES"; const dataType = column6["DATA_TYPE"]; const columnType = column6["COLUMN_TYPE"]; const isPrimary = column6["COLUMN_KEY"] === "PRI"; let columnDefault = column6["COLUMN_DEFAULT"]; const collation = column6["CHARACTER_SET_NAME"]; const geenratedExpression = column6["GENERATION_EXPRESSION"]; let columnExtra = column6["EXTRA"]; let isAutoincrement = false; let isDefaultAnExpression = false; if (typeof column6["EXTRA"] !== "undefined") { columnExtra = column6["EXTRA"]; isAutoincrement = column6["EXTRA"] === "auto_increment"; isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED"); } if (schema6 !== inputSchema) { schemas.push(schema6); } const table6 = result[tableName]; let changedType = columnType; if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) { const uniqueIdx = idxRows.filter( (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0 ); if (uniqueIdx && uniqueIdx.length === 1) { changedType = columnType.replace("bigint unsigned", "serial"); } } if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) { changedType = columnType.replace(/\(\s*[^)]*\)$/, ""); } if (columnType.includes("decimal(10,0)")) { changedType = columnType.replace("decimal(10,0)", "decimal"); } if (columnDefault?.endsWith(".")) { columnDefault = columnDefault.slice(0, -1); } let onUpdate = void 0; if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) { onUpdate = true; } const newColumn = { default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`, autoincrement: isAutoincrement, name: columnName, type: changedType, primaryKey: false, notNull: !isNullable, onUpdate, generated: geenratedExpression ? { as: geenratedExpression, type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored" } : void 0 }; if (isDefaultAnExpression) { if (typeof internals.tables[tableName] === "undefined") { internals.tables[tableName] = { columns: { [columnName]: { isDefaultAnExpression: true } } }; } else { if (typeof internals.tables[tableName].columns[columnName] === "undefined") { internals.tables[tableName].columns[columnName] = { isDefaultAnExpression: true }; } else { internals.tables[tableName].columns[columnName].isDefaultAnExpression = true; } } } if (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, uniqueConstraints: {} }; } else { result[tableName].columns[columnName] = newColumn; } } const tablePks = await db.query( `SELECT table_name, column_name, ordinal_position FROM information_schema.table_constraints t LEFT JOIN information_schema.key_column_usage k USING(constraint_name,table_schema,table_name) WHERE t.constraint_type='UNIQUE' and table_name != '__drizzle_migrations' AND t.table_schema = '${inputSchema}' ORDER BY ordinal_position` ); const tableToPk = {}; const tableToPkRows = tablePks; for (const tableToPkRow of tableToPkRows) { const tableName = tableToPkRow["table_name"]; const columnName = tableToPkRow["column_name"]; const position = tableToPkRow["ordinal_position"]; if (typeof result[tableName] === "undefined") { continue; } if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } for (const [key, value] of Object.entries(tableToPk)) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}`]: { name: `${key}_${value.join("_")}`, columns: value } }; } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } for (const idxRow of idxRows) { const tableSchema = idxRow["TABLE_SCHEMA"]; const tableName = idxRow["TABLE_NAME"]; const constraintName = idxRow["INDEX_NAME"]; const columnName = idxRow["COLUMN_NAME"]; const isUnique = idxRow["NON_UNIQUE"] === 0; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (isUnique) { if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") { tableInResult.uniqueConstraints[constraintName].columns.push( columnName ); } else { tableInResult.uniqueConstraints[constraintName] = { name: constraintName, columns: [columnName] }; } } } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); } return { version: "1", dialect: "singlestore", tables: result, /* views: resultViews, */ _meta: { tables: {}, columns: {} }, internal: internals }; }; } }); // ../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs function writeFromReadableStream(stream, writable) { if (stream.locked) { throw new TypeError("ReadableStream is locked."); } else if (writable.destroyed) { stream.cancel(); return; } const reader = stream.getReader(); writable.on("close", cancel); writable.on("error", cancel); reader.read().then(flow, cancel); return reader.closed.finally(() => { writable.off("close", cancel); writable.off("error", cancel); }); function cancel(error2) { reader.cancel(error2).catch(() => { }); if (error2) { writable.destroy(error2); } } function onDrain() { reader.read().then(flow, cancel); } function flow({ done, value }) { try { if (done) { writable.end(); } else if (!writable.write(value)) { writable.once("drain", onDrain); } else { return reader.read().then(flow, cancel); } } catch (e6) { cancel(e6); } } } var import_http, import_http2, import_stream, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, _body, _init, _a, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve; var init_dist = __esm({ "../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs"() { "use strict"; import_http = require("http"); import_http2 = require("http2"); import_stream = require("stream"); import_crypto = __toESM(require("crypto"), 1); RequestError = class extends Error { constructor(message, options) { super(message, options); this.name = "RequestError"; } }; toRequestError = (e6) => { if (e6 instanceof RequestError) { return e6; } return new RequestError(e6.message, { cause: e6 }); }; GlobalRequest = global.Request; Request2 = class extends GlobalRequest { constructor(input, options) { if (typeof input === "object" && getRequestCache in input) { input = input[getRequestCache](); } if (typeof options?.body?.getReader !== "undefined") { ; options.duplex ??= "half"; } super(input, options); } }; newRequestFromIncoming = (method, url, incoming, abortController) => { const headerRecord = []; const rawHeaders = incoming.rawHeaders; for (let i6 = 0; i6 < rawHeaders.length; i6 += 2) { const { [i6]: key, [i6 + 1]: value } = rawHeaders; if (key.charCodeAt(0) !== /*:*/ 58) { headerRecord.push([key, value]); } } const init2 = { method, headers: headerRecord, signal: abortController.signal }; if (method === "TRACE") { init2.method = "GET"; const req = new Request2(url, init2); Object.defineProperty(req, "method", { get() { return "TRACE"; } }); return req; } if (!(method === "GET" || method === "HEAD")) { if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { init2.body = new ReadableStream({ start(controller) { controller.enqueue(incoming.rawBody); controller.close(); } }); } else { init2.body = import_stream.Readable.toWeb(incoming); } } return new Request2(url, init2); }; getRequestCache = Symbol("getRequestCache"); requestCache = Symbol("requestCache"); incomingKey = Symbol("incomingKey"); urlKey = Symbol("urlKey"); abortControllerKey = Symbol("abortControllerKey"); getAbortController = Symbol("getAbortController"); requestPrototype = { get method() { return this[incomingKey].method || "GET"; }, get url() { return this[urlKey]; }, [getAbortController]() { this[getRequestCache](); return this[abortControllerKey]; }, [getRequestCache]() { this[abortControllerKey] ||= new AbortController(); return this[requestCache] ||= newRequestFromIncoming( this.method, this[urlKey], this[incomingKey], this[abortControllerKey] ); } }; [ "body", "bodyUsed", "cache", "credentials", "destination", "headers", "integrity", "mode", "redirect", "referrer", "referrerPolicy", "signal", "keepalive" ].forEach((k5) => { Object.defineProperty(requestPrototype, k5, { get() { return this[getRequestCache]()[k5]; } }); }); ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => { Object.defineProperty(requestPrototype, k5, { value: function() { return this[getRequestCache]()[k5](); } }); }); Object.setPrototypeOf(requestPrototype, Request2.prototype); newRequest = (incoming, defaultHostname) => { const req = Object.create(requestPrototype); req[incomingKey] = incoming; const incomingUrl = incoming.url || ""; if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { if (incoming instanceof import_http2.Http2ServerRequest) { throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); } try { const url2 = new URL(incomingUrl); req[urlKey] = url2.href; } catch (e6) { throw new RequestError("Invalid absolute URL", { cause: e6 }); } return req; } const host = (incoming instanceof import_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; if (!host) { throw new RequestError("Missing host header"); } let scheme; if (incoming instanceof import_http2.Http2ServerRequest) { scheme = incoming.scheme; if (!(scheme === "http" || scheme === "https")) { throw new RequestError("Unsupported scheme"); } } else { scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; } const url = new URL(`${scheme}://${host}${incomingUrl}`); if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { throw new RequestError("Invalid host header"); } req[urlKey] = url.href; return req; }; responseCache = Symbol("responseCache"); getResponseCache = Symbol("getResponseCache"); cacheKey = Symbol("cache"); GlobalResponse = global.Response; Response2 = (_a = class { constructor(body, init2) { __privateAdd(this, _body); __privateAdd(this, _init); let headers; __privateSet(this, _body, body); if (init2 instanceof _a) { const cachedGlobalResponse = init2[responseCache]; if (cachedGlobalResponse) { __privateSet(this, _init, cachedGlobalResponse); this[getResponseCache](); return; } else { __privateSet(this, _init, __privateGet(init2, _init)); headers = new Headers(__privateGet(init2, _init).headers); } } else { __privateSet(this, _init, init2); } if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { headers ||= init2?.headers || { "content-type": "text/plain; charset=UTF-8" }; this[cacheKey] = [init2?.status || 200, body, headers]; } } [getResponseCache]() { delete this[cacheKey]; return this[responseCache] ||= new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init)); } get headers() { const cache5 = this[cacheKey]; if (cache5) { if (!(cache5[2] instanceof Headers)) { cache5[2] = new Headers(cache5[2]); } return cache5[2]; } return this[getResponseCache]().headers; } get status() { return this[cacheKey]?.[0] ?? this[getResponseCache]().status; } get ok() { const status = this.status; return status >= 200 && status < 300; } }, _body = new WeakMap(), _init = new WeakMap(), _a); ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k5) => { Object.defineProperty(Response2.prototype, k5, { get() { return this[getResponseCache]()[k5]; } }); }); ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => { Object.defineProperty(Response2.prototype, k5, { value: function() { return this[getResponseCache]()[k5](); } }); }); Object.setPrototypeOf(Response2, GlobalResponse); Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); buildOutgoingHttpHeaders = (headers) => { const res = {}; if (!(headers instanceof Headers)) { headers = new Headers(headers ?? void 0); } const cookies = []; for (const [k5, v6] of headers) { if (k5 === "set-cookie") { cookies.push(v6); } else { res[k5] = v6; } } if (cookies.length > 0) { res["set-cookie"] = cookies; } res["content-type"] ??= "text/plain; charset=UTF-8"; return res; }; X_ALREADY_SENT = "x-hono-already-sent"; webFetch = global.fetch; if (typeof global.crypto === "undefined") { global.crypto = import_crypto.default; } global.fetch = (info2, init2) => { init2 = { // Disable compression handling so people can return the result of a fetch // directly in the loader without messing with the Content-Encoding header. compress: false, ...init2 }; return webFetch(info2, init2); }; regBuffer = /^no$/i; regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i; handleRequestError = () => new Response(null, { status: 400 }); handleFetchError = (e6) => new Response(null, { status: e6 instanceof Error && (e6.name === "TimeoutError" || e6.constructor.name === "TimeoutError") ? 504 : 500 }); handleResponseError = (e6, outgoing) => { const err2 = e6 instanceof Error ? e6 : new Error("unknown error", { cause: e6 }); if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") { console.info("The user aborted a request."); } else { console.error(e6); if (!outgoing.headersSent) { outgoing.writeHead(500, { "Content-Type": "text/plain" }); } outgoing.end(`Error: ${err2.message}`); outgoing.destroy(err2); } }; responseViaCache = async (res, outgoing) => { let [status, body, header] = res[cacheKey]; if (header instanceof Headers) { header = buildOutgoingHttpHeaders(header); } if (typeof body === "string") { header["Content-Length"] = Buffer.byteLength(body); } else if (body instanceof Uint8Array) { header["Content-Length"] = body.byteLength; } else if (body instanceof Blob) { header["Content-Length"] = body.size; } outgoing.writeHead(status, header); if (typeof body === "string" || body instanceof Uint8Array) { outgoing.end(body); } else if (body instanceof Blob) { outgoing.end(new Uint8Array(await body.arrayBuffer())); } else { return writeFromReadableStream(body, outgoing)?.catch( (e6) => handleResponseError(e6, outgoing) ); } }; responseViaResponseObject = async (res, outgoing, options = {}) => { if (res instanceof Promise) { if (options.errorHandler) { try { res = await res; } catch (err2) { const errRes = await options.errorHandler(err2); if (!errRes) { return; } res = errRes; } } else { res = await res.catch(handleFetchError); } } if (cacheKey in res) { return responseViaCache(res, outgoing); } const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); if (res.body) { const { "transfer-encoding": transferEncoding, "content-encoding": contentEncoding, "content-length": contentLength, "x-accel-buffering": accelBuffering, "content-type": contentType } = resHeaderRecord; if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) { outgoing.writeHead(res.status, resHeaderRecord); await writeFromReadableStream(res.body, outgoing); } else { const buffer = await res.arrayBuffer(); resHeaderRecord["content-length"] = buffer.byteLength; outgoing.writeHead(res.status, resHeaderRecord); outgoing.end(new Uint8Array(buffer)); } } else if (resHeaderRecord[X_ALREADY_SENT]) { } else { outgoing.writeHead(res.status, resHeaderRecord); outgoing.end(); } }; getRequestListener = (fetchCallback, options = {}) => { if (options.overrideGlobalObjects !== false && global.Request !== Request2) { Object.defineProperty(global, "Request", { value: Request2 }); Object.defineProperty(global, "Response", { value: Response2 }); } return async (incoming, outgoing) => { let res, req; try { req = newRequest(incoming, options.hostname); outgoing.on("close", () => { const abortController = req[abortControllerKey]; if (!abortController) { return; } if (incoming.errored) { req[abortControllerKey].abort(incoming.errored.toString()); } else if (!outgoing.writableFinished) { req[abortControllerKey].abort("Client connection prematurely closed."); } }); res = fetchCallback(req, { incoming, outgoing }); if (cacheKey in res) { return responseViaCache(res, outgoing); } } catch (e6) { if (!res) { if (options.errorHandler) { res = await options.errorHandler(req ? e6 : toRequestError(e6)); if (!res) { return; } } else if (!req) { res = handleRequestError(); } else { res = handleFetchError(e6); } } else { return handleResponseError(e6, outgoing); } } try { return await responseViaResponseObject(res, outgoing, options); } catch (e6) { return handleResponseError(e6, outgoing); } }; }; createAdaptorServer = (options) => { const fetchCallback = options.fetch; const requestListener = getRequestListener(fetchCallback, { hostname: options.hostname, overrideGlobalObjects: options.overrideGlobalObjects }); const createServer2 = options.createServer || import_http.createServer; const server = createServer2(options.serverOptions || {}, requestListener); return server; }; serve = (options, listeningListener) => { const server = createAdaptorServer(options); server.listen(options?.port ?? 3e3, options.hostname, () => { const serverInfo = server.address(); listeningListener && listeningListener(serverInfo); }); return server; }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecode, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_; var init_url = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js"() { "use strict"; splitPath = (path3) => { const paths = path3.split("/"); if (paths[0] === "") { paths.shift(); } return paths; }; splitRoutingPath = (routePath) => { const { groups, path: path3 } = extractGroupsFromPath(routePath); const paths = splitPath(path3); return replaceGroupMarks(paths, groups); }; extractGroupsFromPath = (path3) => { const groups = []; path3 = path3.replace(/\{[^}]+\}/g, (match2, index6) => { const mark = `@${index6}`; groups.push([mark, match2]); return mark; }); return { groups, path: path3 }; }; replaceGroupMarks = (paths, groups) => { for (let i6 = groups.length - 1; i6 >= 0; i6--) { const [mark] = groups[i6]; for (let j5 = paths.length - 1; j5 >= 0; j5--) { if (paths[j5].includes(mark)) { paths[j5] = paths[j5].replace(mark, groups[i6][1]); break; } } } return paths; }; patternCache = {}; getPattern = (label, next) => { if (label === "*") { return "*"; } const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); if (match2) { const cacheKey2 = `${label}#${next}`; if (!patternCache[cacheKey2]) { if (match2[2]) { patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)]; } else { patternCache[cacheKey2] = [label, match2[1], true]; } } return patternCache[cacheKey2]; } return null; }; tryDecode = (str, decoder) => { try { return decoder(str); } catch { return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => { try { return decoder(match2); } catch { return match2; } }); } }; tryDecodeURI = (str) => tryDecode(str, decodeURI); getPath = (request2) => { const url = request2.url; const start = url.indexOf("/", 8); let i6 = start; for (; i6 < url.length; i6++) { const charCode = url.charCodeAt(i6); if (charCode === 37) { const queryIndex = url.indexOf("?", i6); const path3 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex); return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3); } else if (charCode === 63) { break; } } return url.slice(start, i6); }; getPathNoStrict = (request2) => { const result = getPath(request2); return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; }; mergePath = (base, sub, ...rest) => { if (rest.length) { sub = mergePath(sub, ...rest); } return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; }; checkOptionalParameter = (path3) => { if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) { return null; } const segments = path3.split("/"); const results = []; let basePath = ""; segments.forEach((segment) => { if (segment !== "" && !/\:/.test(segment)) { basePath += "/" + segment; } else if (/\:/.test(segment)) { if (/\?/.test(segment)) { if (results.length === 0 && basePath === "") { results.push("/"); } else { results.push(basePath); } const optionalSegment = segment.replace("?", ""); basePath += "/" + optionalSegment; results.push(basePath); } else { basePath += "/" + segment; } } }); return results.filter((v6, i6, a5) => a5.indexOf(v6) === i6); }; _decodeURI = (value) => { if (!/[%+]/.test(value)) { return value; } if (value.indexOf("+") !== -1) { value = value.replace(/\+/g, " "); } return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value; }; _getQueryParam = (url, key, multiple) => { let encoded; if (!multiple && key && !/[%+]/.test(key)) { let keyIndex2 = url.indexOf(`?${key}`, 8); if (keyIndex2 === -1) { keyIndex2 = url.indexOf(`&${key}`, 8); } while (keyIndex2 !== -1) { const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); if (trailingKeyCode === 61) { const valueIndex = keyIndex2 + key.length + 2; const endIndex = url.indexOf("&", valueIndex); return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { return ""; } keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); } encoded = /[%+]/.test(url); if (!encoded) { return void 0; } } const results = {}; encoded ??= /[%+]/.test(url); let keyIndex = url.indexOf("?", 8); while (keyIndex !== -1) { const nextKeyIndex = url.indexOf("&", keyIndex + 1); let valueIndex = url.indexOf("=", keyIndex); if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { valueIndex = -1; } let name = url.slice( keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex ); if (encoded) { name = _decodeURI(name); } keyIndex = nextKeyIndex; if (name === "") { continue; } let value; if (valueIndex === -1) { value = ""; } else { value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); if (encoded) { value = _decodeURI(value); } } if (multiple) { if (!(results[name] && Array.isArray(results[name]))) { results[name] = []; } ; results[name].push(value); } else { results[name] ??= value; } } return key ? results[key] : results; }; getQueryParam = _getQueryParam; getQueryParams = (url, key) => { return _getQueryParam(url, key, true); }; decodeURIComponent_ = decodeURIComponent; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js var validCookieNameRegEx, validCookieValueRegEx, parse2; var init_cookie = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js"() { "use strict"; init_url(); validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/; validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/; parse2 = (cookie, name) => { if (name && cookie.indexOf(name) === -1) { return {}; } const pairs = cookie.trim().split(";"); const parsedCookie = {}; for (let pairStr of pairs) { pairStr = pairStr.trim(); const valueStartPos = pairStr.indexOf("="); if (valueStartPos === -1) { continue; } const cookieName = pairStr.substring(0, valueStartPos).trim(); if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) { continue; } let cookieValue = pairStr.substring(valueStartPos + 1).trim(); if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) { cookieValue = cookieValue.slice(1, -1); } if (validCookieValueRegEx.test(cookieValue)) { parsedCookie[cookieName] = decodeURIComponent_(cookieValue); if (name) { break; } } } return parsedCookie; }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js var getCookie; var init_cookie2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js"() { "use strict"; init_cookie(); getCookie = (c5, key, prefix2) => { const cookie = c5.req.raw.headers.get("Cookie"); if (typeof key === "string") { if (!cookie) { return void 0; } let finalKey = key; if (prefix2 === "secure") { finalKey = "__Secure-" + key; } else if (prefix2 === "host") { finalKey = "__Host-" + key; } const obj2 = parse2(cookie, finalKey); return obj2[finalKey]; } if (!cookie) { return {}; } const obj = parse2(cookie); return obj; }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js var HTTPException; var init_http_exception = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js"() { "use strict"; HTTPException = class extends Error { constructor(status = 500, options) { super(options?.message, { cause: options?.cause }); __publicField(this, "res"); __publicField(this, "status"); this.res = options?.res; this.status = status; } getResponse() { if (this.res) { const newResponse = new Response(this.res.body, { status: this.status, headers: this.res.headers }); return newResponse; } return new Response(this.message, { status: this.status }); } }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js var init_crypto = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js"() { "use strict"; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js var bufferToFormData; var init_buffer = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js"() { "use strict"; init_crypto(); bufferToFormData = (arrayBuffer, contentType) => { const response = new Response(arrayBuffer, { headers: { "Content-Type": contentType } }); return response.formData(); }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js var jsonRegex, multipartRegex, urlencodedRegex, validator; var init_validator = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js"() { "use strict"; init_cookie2(); init_http_exception(); init_buffer(); jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/; urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; validator = (target, validationFunc) => { return async (c5, next) => { let value = {}; const contentType = c5.req.header("Content-Type"); switch (target) { case "json": if (!contentType || !jsonRegex.test(contentType)) { break; } try { value = await c5.req.json(); } catch { const message = "Malformed JSON in request body"; throw new HTTPException(400, { message }); } break; case "form": { if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) { break; } let formData; if (c5.req.bodyCache.formData) { formData = await c5.req.bodyCache.formData; } else { try { const arrayBuffer = await c5.req.arrayBuffer(); formData = await bufferToFormData(arrayBuffer, contentType); c5.req.bodyCache.formData = formData; } catch (e6) { let message = "Malformed FormData request."; message += e6 instanceof Error ? ` ${e6.message}` : ` ${String(e6)}`; throw new HTTPException(400, { message }); } } const form = {}; formData.forEach((value2, key) => { if (key.endsWith("[]")) { ; (form[key] ??= []).push(value2); } else if (Array.isArray(form[key])) { ; form[key].push(value2); } else if (key in form) { form[key] = [form[key], value2]; } else { form[key] = value2; } }); value = form; break; } case "query": value = Object.fromEntries( Object.entries(c5.req.queries()).map(([k5, v6]) => { return v6.length === 1 ? [k5, v6[0]] : [k5, v6]; }) ); break; case "param": value = c5.req.param(); break; case "header": value = c5.req.header(); break; case "cookie": value = getCookie(c5); break; } const res = await validationFunc(value, c5); if (res instanceof Response) { return res; } c5.req.addValidatedData(target, res); await next(); }; }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js var init_validator2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js"() { "use strict"; init_validator(); } }); // ../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js var zValidator; var init_esm2 = __esm({ "../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js"() { "use strict"; init_validator2(); zValidator = (target, schema6, hook) => ( // @ts-expect-error not typed well validator(target, async (value, c5) => { const result = await schema6.safeParseAsync(value); if (hook) { const hookResult = await hook({ data: value, ...result }, c5); if (hookResult) { if (hookResult instanceof Response) { return hookResult; } if ("response" in hookResult) { return hookResult.response; } } } if (!result.success) { return c5.json(result, 400); } return result.data; }) ); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js var compose; var init_compose = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js"() { "use strict"; compose = (middleware, onError, onNotFound) => { return (context, next) => { let index6 = -1; return dispatch(0); async function dispatch(i6) { if (i6 <= index6) { throw new Error("next() called multiple times"); } index6 = i6; let res; let isError = false; let handler; if (middleware[i6]) { handler = middleware[i6][0][0]; context.req.routeIndex = i6; } else { handler = i6 === middleware.length && next || void 0; } if (handler) { try { res = await handler(context, () => dispatch(i6 + 1)); } catch (err2) { if (err2 instanceof Error && onError) { context.error = err2; res = await onError(err2, context); isError = true; } else { throw err2; } } } else { if (context.finalized === false && onNotFound) { res = await onNotFound(context); } } if (res && (context.finalized === false || isError)) { context.res = res; } return context; } }; }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js async function parseFormData(request2, options) { const formData = await request2.formData(); if (formData) { return convertFormDataToBodyData(formData, options); } return {}; } function convertFormDataToBodyData(formData, options) { const form = /* @__PURE__ */ Object.create(null); formData.forEach((value, key) => { const shouldParseAllValues = options.all || key.endsWith("[]"); if (!shouldParseAllValues) { form[key] = value; } else { handleParsingAllValues(form, key, value); } }); if (options.dot) { Object.entries(form).forEach(([key, value]) => { const shouldParseDotValues = key.includes("."); if (shouldParseDotValues) { handleParsingNestedValues(form, key, value); delete form[key]; } }); } return form; } var parseBody, handleParsingAllValues, handleParsingNestedValues; var init_body = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js"() { "use strict"; init_request(); parseBody = async (request2, options = /* @__PURE__ */ Object.create(null)) => { const { all = false, dot = false } = options; const headers = request2 instanceof HonoRequest ? request2.raw.headers : request2.headers; const contentType = headers.get("Content-Type"); if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { return parseFormData(request2, { all, dot }); } return {}; }; handleParsingAllValues = (form, key, value) => { if (form[key] !== void 0) { if (Array.isArray(form[key])) { ; form[key].push(value); } else { form[key] = [form[key], value]; } } else { form[key] = value; } }; handleParsingNestedValues = (form, key, value) => { let nestedForm = form; const keys = key.split("."); keys.forEach((key2, index6) => { if (index6 === keys.length - 1) { nestedForm[key2] = value; } else { if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { nestedForm[key2] = /* @__PURE__ */ Object.create(null); } nestedForm = nestedForm[key2]; } }); }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js var tryDecodeURIComponent, _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _a2, HonoRequest; var init_request = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js"() { "use strict"; init_body(); init_url(); tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); HonoRequest = (_a2 = class { constructor(request2, path3 = "/", matchResult = [[]]) { __privateAdd(this, _HonoRequest_instances); __publicField(this, "raw"); __privateAdd(this, _validatedData); __privateAdd(this, _matchResult); __publicField(this, "routeIndex", 0); __publicField(this, "path"); __publicField(this, "bodyCache", {}); __privateAdd(this, _cachedBody, (key) => { const { bodyCache, raw: raw2 } = this; const cachedBody = bodyCache[key]; if (cachedBody) { return cachedBody; } const anyCachedKey = Object.keys(bodyCache)[0]; if (anyCachedKey) { return bodyCache[anyCachedKey].then((body) => { if (anyCachedKey === "json") { body = JSON.stringify(body); } return new Response(body)[key](); }); } return bodyCache[key] = raw2[key](); }); this.raw = request2; this.path = path3; __privateSet(this, _matchResult, matchResult); __privateSet(this, _validatedData, {}); } param(key) { return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this); } query(key) { return getQueryParam(this.url, key); } queries(key) { return getQueryParams(this.url, key); } header(name) { if (name) { return this.raw.headers.get(name) ?? void 0; } const headerData = {}; this.raw.headers.forEach((value, key) => { headerData[key] = value; }); return headerData; } async parseBody(options) { return this.bodyCache.parsedBody ??= await parseBody(this, options); } json() { return __privateGet(this, _cachedBody).call(this, "json"); } text() { return __privateGet(this, _cachedBody).call(this, "text"); } arrayBuffer() { return __privateGet(this, _cachedBody).call(this, "arrayBuffer"); } blob() { return __privateGet(this, _cachedBody).call(this, "blob"); } formData() { return __privateGet(this, _cachedBody).call(this, "formData"); } addValidatedData(target, data) { __privateGet(this, _validatedData)[target] = data; } valid(target) { return __privateGet(this, _validatedData)[target]; } get url() { return this.raw.url; } get method() { return this.raw.method; } get matchedRoutes() { return __privateGet(this, _matchResult)[0].map(([[, route]]) => route); } get routePath() { return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path; } }, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) { const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key]; const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey); return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0; }, getAllDecodedParams_fn = function() { const decoded = {}; const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]); for (const key of keys) { const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]); if (value && typeof value === "string") { decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; } } return decoded; }, getParamValue_fn = function(paramKey) { return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey; }, _cachedBody = new WeakMap(), _a2); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js var HtmlEscapedCallbackPhase, raw, resolveCallback; var init_html = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js"() { "use strict"; HtmlEscapedCallbackPhase = { Stringify: 1, BeforeStream: 2, Stream: 3 }; raw = (value, callbacks) => { const escapedString = new String(value); escapedString.isEscaped = true; escapedString.callbacks = callbacks; return escapedString; }; resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { if (typeof str === "object" && !(str instanceof String)) { if (!(str instanceof Promise)) { str = str.toString(); } if (str instanceof Promise) { str = await str; } } const callbacks = str.callbacks; if (!callbacks?.length) { return Promise.resolve(str); } if (buffer) { buffer[0] += str; } else { buffer = [str]; } const resStr = Promise.all(callbacks.map((c5) => c5({ phase, buffer, context }))).then( (res) => Promise.all( res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer)) ).then(() => buffer[0]) ); if (preserveCallbacks) { return raw(await resStr, callbacks); } else { return resStr; } }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js var TEXT_PLAIN, setHeaders, _rawRequest, _req, _var, _status, _executionCtx, _headers, _preparedHeaders, _res, _isFresh, _layout, _renderer, _notFoundHandler, _matchResult2, _path, _Context_instances, newResponse_fn, _a3, Context; var init_context = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js"() { "use strict"; init_request(); init_html(); TEXT_PLAIN = "text/plain; charset=UTF-8"; setHeaders = (headers, map2 = {}) => { for (const key of Object.keys(map2)) { headers.set(key, map2[key]); } return headers; }; Context = (_a3 = class { constructor(req, options) { __privateAdd(this, _Context_instances); __privateAdd(this, _rawRequest); __privateAdd(this, _req); __publicField(this, "env", {}); __privateAdd(this, _var); __publicField(this, "finalized", false); __publicField(this, "error"); __privateAdd(this, _status, 200); __privateAdd(this, _executionCtx); __privateAdd(this, _headers); __privateAdd(this, _preparedHeaders); __privateAdd(this, _res); __privateAdd(this, _isFresh, true); __privateAdd(this, _layout); __privateAdd(this, _renderer); __privateAdd(this, _notFoundHandler); __privateAdd(this, _matchResult2); __privateAdd(this, _path); __publicField(this, "render", (...args) => { __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content)); return __privateGet(this, _renderer).call(this, ...args); }); __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout)); __publicField(this, "getLayout", () => __privateGet(this, _layout)); __publicField(this, "setRenderer", (renderer) => { __privateSet(this, _renderer, renderer); }); __publicField(this, "header", (name, value, options) => { if (this.finalized) { __privateSet(this, _res, new Response(__privateGet(this, _res).body, __privateGet(this, _res))); } if (value === void 0) { if (__privateGet(this, _headers)) { __privateGet(this, _headers).delete(name); } else if (__privateGet(this, _preparedHeaders)) { delete __privateGet(this, _preparedHeaders)[name.toLocaleLowerCase()]; } if (this.finalized) { this.res.headers.delete(name); } return; } if (options?.append) { if (!__privateGet(this, _headers)) { __privateSet(this, _isFresh, false); __privateSet(this, _headers, new Headers(__privateGet(this, _preparedHeaders))); __privateSet(this, _preparedHeaders, {}); } __privateGet(this, _headers).append(name, value); } else { if (__privateGet(this, _headers)) { __privateGet(this, _headers).set(name, value); } else { __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {}); __privateGet(this, _preparedHeaders)[name.toLowerCase()] = value; } } if (this.finalized) { if (options?.append) { this.res.headers.append(name, value); } else { this.res.headers.set(name, value); } } }); __publicField(this, "status", (status) => { __privateSet(this, _isFresh, false); __privateSet(this, _status, status); }); __publicField(this, "set", (key, value) => { __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map()); __privateGet(this, _var).set(key, value); }); __publicField(this, "get", (key) => { return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0; }); __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args)); __publicField(this, "body", (data, arg, headers) => { return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg); }); __publicField(this, "text", (text, arg, headers) => { if (!__privateGet(this, _preparedHeaders)) { if (__privateGet(this, _isFresh) && !headers && !arg) { return new Response(text); } __privateSet(this, _preparedHeaders, {}); } __privateGet(this, _preparedHeaders)["content-type"] = TEXT_PLAIN; if (typeof arg === "number") { return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, headers); } return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg); }); __publicField(this, "json", (object, arg, headers) => { const body = JSON.stringify(object); __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {}); __privateGet(this, _preparedHeaders)["content-type"] = "application/json"; return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg); }); __publicField(this, "html", (html, arg, headers) => { __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {}); __privateGet(this, _preparedHeaders)["content-type"] = "text/html; charset=UTF-8"; if (typeof html === "object") { return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => { return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg); }); } return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg); }); __publicField(this, "redirect", (location, status) => { __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers()); __privateGet(this, _headers).set("Location", String(location)); return this.newResponse(null, status ?? 302); }); __publicField(this, "notFound", () => { __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => new Response()); return __privateGet(this, _notFoundHandler).call(this, this); }); __privateSet(this, _rawRequest, req); if (options) { __privateSet(this, _executionCtx, options.executionCtx); this.env = options.env; __privateSet(this, _notFoundHandler, options.notFoundHandler); __privateSet(this, _path, options.path); __privateSet(this, _matchResult2, options.matchResult); } } get req() { __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2))); return __privateGet(this, _req); } get event() { if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) { return __privateGet(this, _executionCtx); } else { throw Error("This context has no FetchEvent"); } } get executionCtx() { if (__privateGet(this, _executionCtx)) { return __privateGet(this, _executionCtx); } else { throw Error("This context has no ExecutionContext"); } } get res() { __privateSet(this, _isFresh, false); return __privateGet(this, _res) || __privateSet(this, _res, new Response("404 Not Found", { status: 404 })); } set res(_res2) { __privateSet(this, _isFresh, false); if (__privateGet(this, _res) && _res2) { _res2 = new Response(_res2.body, _res2); for (const [k5, v6] of __privateGet(this, _res).headers.entries()) { if (k5 === "content-type") { continue; } if (k5 === "set-cookie") { const cookies = __privateGet(this, _res).headers.getSetCookie(); _res2.headers.delete("set-cookie"); for (const cookie of cookies) { _res2.headers.append("set-cookie", cookie); } } else { _res2.headers.set(k5, v6); } } } __privateSet(this, _res, _res2); this.finalized = true; } get var() { if (!__privateGet(this, _var)) { return {}; } return Object.fromEntries(__privateGet(this, _var)); } }, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _headers = new WeakMap(), _preparedHeaders = new WeakMap(), _res = new WeakMap(), _isFresh = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) { if (__privateGet(this, _isFresh) && !headers && !arg && __privateGet(this, _status) === 200) { return new Response(data, { headers: __privateGet(this, _preparedHeaders) }); } if (arg && typeof arg !== "number") { const header = new Headers(arg.headers); if (__privateGet(this, _headers)) { __privateGet(this, _headers).forEach((v6, k5) => { if (k5 === "set-cookie") { header.append(k5, v6); } else { header.set(k5, v6); } }); } const headers2 = setHeaders(header, __privateGet(this, _preparedHeaders)); return new Response(data, { headers: headers2, status: arg.status ?? __privateGet(this, _status) }); } const status = typeof arg === "number" ? arg : __privateGet(this, _status); __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {}); __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers()); setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders)); if (__privateGet(this, _res)) { __privateGet(this, _res).headers.forEach((v6, k5) => { if (k5 === "set-cookie") { __privateGet(this, _headers)?.append(k5, v6); } else { __privateGet(this, _headers)?.set(k5, v6); } }); setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders)); } headers ??= {}; for (const [k5, v6] of Object.entries(headers)) { if (typeof v6 === "string") { __privateGet(this, _headers).set(k5, v6); } else { __privateGet(this, _headers).delete(k5); for (const v22 of v6) { __privateGet(this, _headers).append(k5, v22); } } } return new Response(data, { status, headers: __privateGet(this, _headers) }); }, _a3); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js var METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS, MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError; var init_router = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js"() { "use strict"; METHOD_NAME_ALL = "ALL"; METHOD_NAME_ALL_LOWERCASE = "all"; METHODS = ["get", "post", "put", "delete", "options", "patch"]; MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; UnsupportedPathError = class extends Error { }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js var COMPOSED_HANDLER; var init_constants = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js"() { "use strict"; COMPOSED_HANDLER = "__COMPOSED_HANDLER"; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js var notFoundHandler, errorHandler, _path2, _Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _a4, Hono; var init_hono_base = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js"() { "use strict"; init_compose(); init_context(); init_router(); init_constants(); init_url(); notFoundHandler = (c5) => { return c5.text("404 Not Found", 404); }; errorHandler = (err2, c5) => { if ("getResponse" in err2) { return err2.getResponse(); } console.error(err2); return c5.text("Internal Server Error", 500); }; Hono = (_a4 = class { constructor(options = {}) { __privateAdd(this, _Hono_instances); __publicField(this, "get"); __publicField(this, "post"); __publicField(this, "put"); __publicField(this, "delete"); __publicField(this, "options"); __publicField(this, "patch"); __publicField(this, "all"); __publicField(this, "on"); __publicField(this, "use"); __publicField(this, "router"); __publicField(this, "getPath"); __publicField(this, "_basePath", "/"); __privateAdd(this, _path2, "/"); __publicField(this, "routes", []); __privateAdd(this, _notFoundHandler2, notFoundHandler); __publicField(this, "errorHandler", errorHandler); __publicField(this, "onError", (handler) => { this.errorHandler = handler; return this; }); __publicField(this, "notFound", (handler) => { __privateSet(this, _notFoundHandler2, handler); return this; }); __publicField(this, "fetch", (request2, ...rest) => { return __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, rest[1], rest[0], request2.method); }); __publicField(this, "request", (input, requestInit, Env, executionCtx) => { if (input instanceof Request) { return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); } input = input.toString(); return this.fetch( new Request( /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit ), Env, executionCtx ); }); __publicField(this, "fire", () => { addEventListener("fetch", (event) => { event.respondWith(__privateMethod(this, _Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method)); }); }); const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; allMethods.forEach((method) => { this[method] = (args1, ...args) => { if (typeof args1 === "string") { __privateSet(this, _path2, args1); } else { __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1); } args.forEach((handler) => { __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler); }); return this; }; }); this.on = (method, path3, ...handlers) => { for (const p5 of [path3].flat()) { __privateSet(this, _path2, p5); for (const m6 of [method].flat()) { handlers.map((handler) => { __privateMethod(this, _Hono_instances, addRoute_fn).call(this, m6.toUpperCase(), __privateGet(this, _path2), handler); }); } } return this; }; this.use = (arg1, ...handlers) => { if (typeof arg1 === "string") { __privateSet(this, _path2, arg1); } else { __privateSet(this, _path2, "*"); handlers.unshift(arg1); } handlers.forEach((handler) => { __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler); }); return this; }; const { strict, ...optionsWithoutStrict } = options; Object.assign(this, optionsWithoutStrict); this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; } route(path3, app) { const subApp = this.basePath(path3); app.routes.map((r6) => { var _a15; let handler; if (app.errorHandler === errorHandler) { handler = r6.handler; } else { handler = async (c5, next) => (await compose([], app.errorHandler)(c5, () => r6.handler(c5, next))).res; handler[COMPOSED_HANDLER] = r6.handler; } __privateMethod(_a15 = subApp, _Hono_instances, addRoute_fn).call(_a15, r6.method, r6.path, handler); }); return this; } basePath(path3) { const subApp = __privateMethod(this, _Hono_instances, clone_fn).call(this); subApp._basePath = mergePath(this._basePath, path3); return subApp; } mount(path3, applicationHandler, options) { let replaceRequest; let optionHandler; if (options) { if (typeof options === "function") { optionHandler = options; } else { optionHandler = options.optionHandler; if (options.replaceRequest === false) { replaceRequest = (request2) => request2; } else { replaceRequest = options.replaceRequest; } } } const getOptions = optionHandler ? (c5) => { const options2 = optionHandler(c5); return Array.isArray(options2) ? options2 : [options2]; } : (c5) => { let executionContext = void 0; try { executionContext = c5.executionCtx; } catch { } return [c5.env, executionContext]; }; replaceRequest ||= (() => { const mergedPath = mergePath(this._basePath, path3); const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; return (request2) => { const url = new URL(request2.url); url.pathname = url.pathname.slice(pathPrefixLength) || "/"; return new Request(url, request2); }; })(); const handler = async (c5, next) => { const res = await applicationHandler(replaceRequest(c5.req.raw), ...getOptions(c5)); if (res) { return res; } await next(); }; __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path3, "*"), handler); return this; } }, _path2 = new WeakMap(), _Hono_instances = new WeakSet(), clone_fn = function() { const clone2 = new Hono({ router: this.router, getPath: this.getPath }); clone2.errorHandler = this.errorHandler; __privateSet(clone2, _notFoundHandler2, __privateGet(this, _notFoundHandler2)); clone2.routes = this.routes; return clone2; }, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path3, handler) { method = method.toUpperCase(); path3 = mergePath(this._basePath, path3); const r6 = { path: path3, method, handler }; this.router.add(method, path3, [handler, r6]); this.routes.push(r6); }, handleError_fn = function(err2, c5) { if (err2 instanceof Error) { return this.errorHandler(err2, c5); } throw err2; }, dispatch_fn = function(request2, executionCtx, env4, method) { if (method === "HEAD") { return (async () => new Response(null, await __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, executionCtx, env4, "GET")))(); } const path3 = this.getPath(request2, { env: env4 }); const matchResult = this.router.match(method, path3); const c5 = new Context(request2, { path: path3, matchResult, env: env4, executionCtx, notFoundHandler: __privateGet(this, _notFoundHandler2) }); if (matchResult[0].length === 1) { let res; try { res = matchResult[0][0][0][0](c5, async () => { c5.res = await __privateGet(this, _notFoundHandler2).call(this, c5); }); } catch (err2) { return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5); } return res instanceof Promise ? res.then( (resolved) => resolved || (c5.finalized ? c5.res : __privateGet(this, _notFoundHandler2).call(this, c5)) ).catch((err2) => __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c5); } const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2)); return (async () => { try { const context = await composed(c5); if (!context.finalized) { throw new Error( "Context is not finalized. Did you forget to return a Response object or `await next()`?" ); } return context.res; } catch (err2) { return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5); } })(); }, _a4); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js function compareKey(a5, b5) { if (a5.length === 1) { return b5.length === 1 ? a5 < b5 ? -1 : 1 : -1; } if (b5.length === 1) { return 1; } if (a5 === ONLY_WILDCARD_REG_EXP_STR || a5 === TAIL_WILDCARD_REG_EXP_STR) { return 1; } else if (b5 === ONLY_WILDCARD_REG_EXP_STR || b5 === TAIL_WILDCARD_REG_EXP_STR) { return -1; } if (a5 === LABEL_REG_EXP_STR) { return 1; } else if (b5 === LABEL_REG_EXP_STR) { return -1; } return a5.length === b5.length ? a5 < b5 ? -1 : 1 : b5.length - a5.length; } var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, _index, _varIndex, _children, _a5, Node; var init_node = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js"() { "use strict"; LABEL_REG_EXP_STR = "[^/]+"; ONLY_WILDCARD_REG_EXP_STR = ".*"; TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; PATH_ERROR = Symbol(); regExpMetaChars = new Set(".\\+*[^]$()"); Node = (_a5 = class { constructor() { __privateAdd(this, _index); __privateAdd(this, _varIndex); __privateAdd(this, _children, /* @__PURE__ */ Object.create(null)); } insert(tokens, index6, paramMap, context, pathErrorCheckOnly) { if (tokens.length === 0) { if (__privateGet(this, _index) !== void 0) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } __privateSet(this, _index, index6); return; } const [token, ...restTokens] = tokens; const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); let node; if (pattern) { const name = pattern[1]; let regexpStr = pattern[2] || LABEL_REG_EXP_STR; if (name && pattern[2]) { regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); if (/\((?!\?:)/.test(regexpStr)) { throw PATH_ERROR; } } node = __privateGet(this, _children)[regexpStr]; if (!node) { if (Object.keys(__privateGet(this, _children)).some( (k5) => k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR )) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } node = __privateGet(this, _children)[regexpStr] = new Node(); if (name !== "") { __privateSet(node, _varIndex, context.varIndex++); } } if (!pathErrorCheckOnly && name !== "") { paramMap.push([name, __privateGet(node, _varIndex)]); } } else { node = __privateGet(this, _children)[token]; if (!node) { if (Object.keys(__privateGet(this, _children)).some( (k5) => k5.length > 1 && k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR )) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } node = __privateGet(this, _children)[token] = new Node(); } } node.insert(restTokens, index6, paramMap, context, pathErrorCheckOnly); } buildRegExpStr() { const childKeys = Object.keys(__privateGet(this, _children)).sort(compareKey); const strList = childKeys.map((k5) => { const c5 = __privateGet(this, _children)[k5]; return (typeof __privateGet(c5, _varIndex) === "number" ? `(${k5})@${__privateGet(c5, _varIndex)}` : regExpMetaChars.has(k5) ? `\\${k5}` : k5) + c5.buildRegExpStr(); }); if (typeof __privateGet(this, _index) === "number") { strList.unshift(`#${__privateGet(this, _index)}`); } if (strList.length === 0) { return ""; } if (strList.length === 1) { return strList[0]; } return "(?:" + strList.join("|") + ")"; } }, _index = new WeakMap(), _varIndex = new WeakMap(), _children = new WeakMap(), _a5); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js var _context, _root, _a6, Trie; var init_trie = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js"() { "use strict"; init_node(); Trie = (_a6 = class { constructor() { __privateAdd(this, _context, { varIndex: 0 }); __privateAdd(this, _root, new Node()); } insert(path3, index6, pathErrorCheckOnly) { const paramAssoc = []; const groups = []; for (let i6 = 0; ; ) { let replaced = false; path3 = path3.replace(/\{[^}]+\}/g, (m6) => { const mark = `@\\${i6}`; groups[i6] = [mark, m6]; i6++; replaced = true; return mark; }); if (!replaced) { break; } } const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; for (let i6 = groups.length - 1; i6 >= 0; i6--) { const [mark] = groups[i6]; for (let j5 = tokens.length - 1; j5 >= 0; j5--) { if (tokens[j5].indexOf(mark) !== -1) { tokens[j5] = tokens[j5].replace(mark, groups[i6][1]); break; } } } __privateGet(this, _root).insert(tokens, index6, paramAssoc, __privateGet(this, _context), pathErrorCheckOnly); return paramAssoc; } buildRegExp() { let regexp = __privateGet(this, _root).buildRegExpStr(); if (regexp === "") { return [/^$/, [], []]; } let captureIndex = 0; const indexReplacementMap = []; const paramReplacementMap = []; regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_3, handlerIndex, paramIndex) => { if (handlerIndex !== void 0) { indexReplacementMap[++captureIndex] = Number(handlerIndex); return "$()"; } if (paramIndex !== void 0) { paramReplacementMap[Number(paramIndex)] = ++captureIndex; return ""; } return ""; }); return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; } }, _context = new WeakMap(), _root = new WeakMap(), _a6); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js function buildWildcardRegExp(path3) { return wildcardRegExpCache[path3] ??= new RegExp( path3 === "*" ? "" : `^${path3.replace( /\/\*$|([.\\+*[^\]$()])/g, (_3, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" )}$` ); } function clearWildcardRegExpCache() { wildcardRegExpCache = /* @__PURE__ */ Object.create(null); } function buildMatcherFromPreprocessedRoutes(routes) { const trie = new Trie(); const handlerData = []; if (routes.length === 0) { return nullMatcher; } const routesWithStaticPathFlag = routes.map( (route) => [!/\*|\/:/.test(route[0]), ...route] ).sort( ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length ); const staticMap = /* @__PURE__ */ Object.create(null); for (let i6 = 0, j5 = -1, len = routesWithStaticPathFlag.length; i6 < len; i6++) { const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i6]; if (pathErrorCheckOnly) { staticMap[path3] = [handlers.map(([h6]) => [h6, /* @__PURE__ */ Object.create(null)]), emptyParam]; } else { j5++; } let paramAssoc; try { paramAssoc = trie.insert(path3, j5, pathErrorCheckOnly); } catch (e6) { throw e6 === PATH_ERROR ? new UnsupportedPathError(path3) : e6; } if (pathErrorCheckOnly) { continue; } handlerData[j5] = handlers.map(([h6, paramCount]) => { const paramIndexMap = /* @__PURE__ */ Object.create(null); paramCount -= 1; for (; paramCount >= 0; paramCount--) { const [key, value] = paramAssoc[paramCount]; paramIndexMap[key] = value; } return [h6, paramIndexMap]; }); } const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); for (let i6 = 0, len = handlerData.length; i6 < len; i6++) { for (let j5 = 0, len2 = handlerData[i6].length; j5 < len2; j5++) { const map2 = handlerData[i6][j5]?.[1]; if (!map2) { continue; } const keys = Object.keys(map2); for (let k5 = 0, len3 = keys.length; k5 < len3; k5++) { map2[keys[k5]] = paramReplacementMap[map2[keys[k5]]]; } } } const handlerMap = []; for (const i6 in indexReplacementMap) { handlerMap[i6] = handlerData[indexReplacementMap[i6]]; } return [regexp, handlerMap, staticMap]; } function findMiddleware(middleware, path3) { if (!middleware) { return void 0; } for (const k5 of Object.keys(middleware).sort((a5, b5) => b5.length - a5.length)) { if (buildWildcardRegExp(k5).test(path3)) { return [...middleware[k5]]; } } return void 0; } var emptyParam, nullMatcher, wildcardRegExpCache, _middleware, _routes, _RegExpRouter_instances, buildAllMatchers_fn, buildMatcher_fn, _a7, RegExpRouter; var init_router2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js"() { "use strict"; init_router(); init_url(); init_node(); init_trie(); emptyParam = []; nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; wildcardRegExpCache = /* @__PURE__ */ Object.create(null); RegExpRouter = (_a7 = class { constructor() { __privateAdd(this, _RegExpRouter_instances); __publicField(this, "name", "RegExpRouter"); __privateAdd(this, _middleware); __privateAdd(this, _routes); __privateSet(this, _middleware, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); __privateSet(this, _routes, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); } add(method, path3, handler) { const middleware = __privateGet(this, _middleware); const routes = __privateGet(this, _routes); if (!middleware || !routes) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); } if (!middleware[method]) { ; [middleware, routes].forEach((handlerMap) => { handlerMap[method] = /* @__PURE__ */ Object.create(null); Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p5) => { handlerMap[method][p5] = [...handlerMap[METHOD_NAME_ALL][p5]]; }); }); } if (path3 === "/*") { path3 = "*"; } const paramCount = (path3.match(/\/:/g) || []).length; if (/\*$/.test(path3)) { const re = buildWildcardRegExp(path3); if (method === METHOD_NAME_ALL) { Object.keys(middleware).forEach((m6) => { middleware[m6][path3] ||= findMiddleware(middleware[m6], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []; }); } else { middleware[method][path3] ||= findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []; } Object.keys(middleware).forEach((m6) => { if (method === METHOD_NAME_ALL || method === m6) { Object.keys(middleware[m6]).forEach((p5) => { re.test(p5) && middleware[m6][p5].push([handler, paramCount]); }); } }); Object.keys(routes).forEach((m6) => { if (method === METHOD_NAME_ALL || method === m6) { Object.keys(routes[m6]).forEach( (p5) => re.test(p5) && routes[m6][p5].push([handler, paramCount]) ); } }); return; } const paths = checkOptionalParameter(path3) || [path3]; for (let i6 = 0, len = paths.length; i6 < len; i6++) { const path22 = paths[i6]; Object.keys(routes).forEach((m6) => { if (method === METHOD_NAME_ALL || method === m6) { routes[m6][path22] ||= [ ...findMiddleware(middleware[m6], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || [] ]; routes[m6][path22].push([handler, paramCount - len + i6 + 1]); } }); } } match(method, path3) { clearWildcardRegExpCache(); const matchers = __privateMethod(this, _RegExpRouter_instances, buildAllMatchers_fn).call(this); this.match = (method2, path22) => { const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; const staticMatch = matcher[2][path22]; if (staticMatch) { return staticMatch; } const match2 = path22.match(matcher[0]); if (!match2) { return [[], emptyParam]; } const index6 = match2.indexOf("", 1); return [matcher[1][index6], match2]; }; return this.match(method, path3); } }, _middleware = new WeakMap(), _routes = new WeakMap(), _RegExpRouter_instances = new WeakSet(), buildAllMatchers_fn = function() { const matchers = /* @__PURE__ */ Object.create(null); Object.keys(__privateGet(this, _routes)).concat(Object.keys(__privateGet(this, _middleware))).forEach((method) => { matchers[method] ||= __privateMethod(this, _RegExpRouter_instances, buildMatcher_fn).call(this, method); }); __privateSet(this, _middleware, __privateSet(this, _routes, void 0)); return matchers; }, buildMatcher_fn = function(method) { const routes = []; let hasOwnRoute = method === METHOD_NAME_ALL; [__privateGet(this, _middleware), __privateGet(this, _routes)].forEach((r6) => { const ownRoute = r6[method] ? Object.keys(r6[method]).map((path3) => [path3, r6[method][path3]]) : []; if (ownRoute.length !== 0) { hasOwnRoute ||= true; routes.push(...ownRoute); } else if (method !== METHOD_NAME_ALL) { routes.push( ...Object.keys(r6[METHOD_NAME_ALL]).map((path3) => [path3, r6[METHOD_NAME_ALL][path3]]) ); } }); if (!hasOwnRoute) { return null; } else { return buildMatcherFromPreprocessedRoutes(routes); } }, _a7); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js var init_reg_exp_router = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js"() { "use strict"; init_router2(); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js var _routers, _routes2, _a8, SmartRouter; var init_router3 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js"() { "use strict"; init_router(); SmartRouter = (_a8 = class { constructor(init2) { __publicField(this, "name", "SmartRouter"); __privateAdd(this, _routers, []); __privateAdd(this, _routes2, []); __privateSet(this, _routers, init2.routers); } add(method, path3, handler) { if (!__privateGet(this, _routes2)) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); } __privateGet(this, _routes2).push([method, path3, handler]); } match(method, path3) { if (!__privateGet(this, _routes2)) { throw new Error("Fatal error"); } const routers = __privateGet(this, _routers); const routes = __privateGet(this, _routes2); const len = routers.length; let i6 = 0; let res; for (; i6 < len; i6++) { const router = routers[i6]; try { for (let i22 = 0, len2 = routes.length; i22 < len2; i22++) { router.add(...routes[i22]); } res = router.match(method, path3); } catch (e6) { if (e6 instanceof UnsupportedPathError) { continue; } throw e6; } this.match = router.match.bind(router); __privateSet(this, _routers, [router]); __privateSet(this, _routes2, void 0); break; } if (i6 === len) { throw new Error("Fatal error"); } this.name = `SmartRouter + ${this.activeRouter.name}`; return res; } get activeRouter() { if (__privateGet(this, _routes2) || __privateGet(this, _routers).length !== 1) { throw new Error("No active router has been determined yet."); } return __privateGet(this, _routers)[0]; } }, _routers = new WeakMap(), _routes2 = new WeakMap(), _a8); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js var init_smart_router = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js"() { "use strict"; init_router3(); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js var emptyParams, _methods, _children2, _patterns, _order, _params, _Node_instances, getHandlerSets_fn, _a9, Node2; var init_node2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js"() { "use strict"; init_router(); init_url(); emptyParams = /* @__PURE__ */ Object.create(null); Node2 = (_a9 = class { constructor(method, handler, children) { __privateAdd(this, _Node_instances); __privateAdd(this, _methods); __privateAdd(this, _children2); __privateAdd(this, _patterns); __privateAdd(this, _order, 0); __privateAdd(this, _params, emptyParams); __privateSet(this, _children2, children || /* @__PURE__ */ Object.create(null)); __privateSet(this, _methods, []); if (method && handler) { const m6 = /* @__PURE__ */ Object.create(null); m6[method] = { handler, possibleKeys: [], score: 0 }; __privateSet(this, _methods, [m6]); } __privateSet(this, _patterns, []); } insert(method, path3, handler) { __privateSet(this, _order, ++__privateWrapper(this, _order)._); let curNode = this; const parts = splitRoutingPath(path3); const possibleKeys = []; for (let i6 = 0, len = parts.length; i6 < len; i6++) { const p5 = parts[i6]; const nextP = parts[i6 + 1]; const pattern = getPattern(p5, nextP); const key = Array.isArray(pattern) ? pattern[0] : p5; if (Object.keys(__privateGet(curNode, _children2)).includes(key)) { curNode = __privateGet(curNode, _children2)[key]; const pattern2 = getPattern(p5, nextP); if (pattern2) { possibleKeys.push(pattern2[1]); } continue; } __privateGet(curNode, _children2)[key] = new Node2(); if (pattern) { __privateGet(curNode, _patterns).push(pattern); possibleKeys.push(pattern[1]); } curNode = __privateGet(curNode, _children2)[key]; } const m6 = /* @__PURE__ */ Object.create(null); const handlerSet = { handler, possibleKeys: possibleKeys.filter((v6, i6, a5) => a5.indexOf(v6) === i6), score: __privateGet(this, _order) }; m6[method] = handlerSet; __privateGet(curNode, _methods).push(m6); return curNode; } search(method, path3) { const handlerSets = []; __privateSet(this, _params, emptyParams); const curNode = this; let curNodes = [curNode]; const parts = splitPath(path3); const curNodesQueue = []; for (let i6 = 0, len = parts.length; i6 < len; i6++) { const part = parts[i6]; const isLast = i6 === len - 1; const tempNodes = []; for (let j5 = 0, len2 = curNodes.length; j5 < len2; j5++) { const node = curNodes[j5]; const nextNode = __privateGet(node, _children2)[part]; if (nextNode) { __privateSet(nextNode, _params, __privateGet(node, _params)); if (isLast) { if (__privateGet(nextNode, _children2)["*"]) { handlerSets.push( ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(nextNode, _children2)["*"], method, __privateGet(node, _params)) ); } handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, nextNode, method, __privateGet(node, _params))); } else { tempNodes.push(nextNode); } } for (let k5 = 0, len3 = __privateGet(node, _patterns).length; k5 < len3; k5++) { const pattern = __privateGet(node, _patterns)[k5]; const params = __privateGet(node, _params) === emptyParams ? {} : { ...__privateGet(node, _params) }; if (pattern === "*") { const astNode = __privateGet(node, _children2)["*"]; if (astNode) { handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, astNode, method, __privateGet(node, _params))); __privateSet(astNode, _params, params); tempNodes.push(astNode); } continue; } if (part === "") { continue; } const [key, name, matcher] = pattern; const child = __privateGet(node, _children2)[key]; const restPathString = parts.slice(i6).join("/"); if (matcher instanceof RegExp) { const m6 = matcher.exec(restPathString); if (m6) { params[name] = m6[0]; handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, __privateGet(node, _params), params)); if (Object.keys(__privateGet(child, _children2)).length) { __privateSet(child, _params, params); const componentCount = m6[0].match(/\//)?.length ?? 0; const targetCurNodes = curNodesQueue[componentCount] ||= []; targetCurNodes.push(child); } continue; } } if (matcher === true || matcher.test(part)) { params[name] = part; if (isLast) { handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, params, __privateGet(node, _params))); if (__privateGet(child, _children2)["*"]) { handlerSets.push( ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(child, _children2)["*"], method, params, __privateGet(node, _params)) ); } } else { __privateSet(child, _params, params); tempNodes.push(child); } } } } curNodes = tempNodes.concat(curNodesQueue.shift() ?? []); } if (handlerSets.length > 1) { handlerSets.sort((a5, b5) => { return a5.score - b5.score; }); } return [handlerSets.map(({ handler, params }) => [handler, params])]; } }, _methods = new WeakMap(), _children2 = new WeakMap(), _patterns = new WeakMap(), _order = new WeakMap(), _params = new WeakMap(), _Node_instances = new WeakSet(), getHandlerSets_fn = function(node, method, nodeParams, params) { const handlerSets = []; for (let i6 = 0, len = __privateGet(node, _methods).length; i6 < len; i6++) { const m6 = __privateGet(node, _methods)[i6]; const handlerSet = m6[method] || m6[METHOD_NAME_ALL]; const processedSet = {}; if (handlerSet !== void 0) { handlerSet.params = /* @__PURE__ */ Object.create(null); handlerSets.push(handlerSet); if (nodeParams !== emptyParams || params && params !== emptyParams) { for (let i22 = 0, len2 = handlerSet.possibleKeys.length; i22 < len2; i22++) { const key = handlerSet.possibleKeys[i22]; const processed = processedSet[handlerSet.score]; handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; processedSet[handlerSet.score] = true; } } } } return handlerSets; }, _a9); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js var _node, _a10, TrieRouter; var init_router4 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js"() { "use strict"; init_url(); init_node2(); TrieRouter = (_a10 = class { constructor() { __publicField(this, "name", "TrieRouter"); __privateAdd(this, _node); __privateSet(this, _node, new Node2()); } add(method, path3, handler) { const results = checkOptionalParameter(path3); if (results) { for (let i6 = 0, len = results.length; i6 < len; i6++) { __privateGet(this, _node).insert(method, results[i6], handler); } return; } __privateGet(this, _node).insert(method, path3, handler); } match(method, path3) { return __privateGet(this, _node).search(method, path3); } }, _node = new WeakMap(), _a10); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js var init_trie_router = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js"() { "use strict"; init_router4(); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js var Hono2; var init_hono = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js"() { "use strict"; init_hono_base(); init_reg_exp_router(); init_smart_router(); init_trie_router(); Hono2 = class extends Hono { constructor(options = {}) { super(options); this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] }); } }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js var init_dist2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js"() { "use strict"; init_hono(); } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js var COMPRESSIBLE_CONTENT_TYPE_REGEX; var init_compress = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js"() { "use strict"; COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js var ENCODING_TYPES, cacheControlNoTransformRegExp, compress, shouldCompress, shouldTransform; var init_compress2 = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js"() { "use strict"; init_compress(); ENCODING_TYPES = ["gzip", "deflate"]; cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i; compress = (options) => { const threshold = options?.threshold ?? 1024; return async function compress2(ctx, next) { await next(); const contentLength = ctx.res.headers.get("Content-Length"); if (ctx.res.headers.has("Content-Encoding") || ctx.res.headers.has("Transfer-Encoding") || ctx.req.method === "HEAD" || contentLength && Number(contentLength) < threshold || !shouldCompress(ctx.res) || !shouldTransform(ctx.res)) { return; } const accepted = ctx.req.header("Accept-Encoding"); const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2)); if (!encoding || !ctx.res.body) { return; } const stream = new CompressionStream(encoding); ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res); ctx.res.headers.delete("Content-Length"); ctx.res.headers.set("Content-Encoding", encoding); }; }; shouldCompress = (res) => { const type = res.headers.get("Content-Type"); return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type); }; shouldTransform = (res) => { const cacheControl = res.headers.get("Cache-Control"); return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl); }; } }); // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js var cors; var init_cors = __esm({ "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js"() { "use strict"; cors = (options) => { const defaults2 = { origin: "*", allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"], allowHeaders: [], exposeHeaders: [] }; const opts = { ...defaults2, ...options }; const findAllowOrigin = ((optsOrigin) => { if (typeof optsOrigin === "string") { if (optsOrigin === "*") { return () => optsOrigin; } else { return (origin) => optsOrigin === origin ? origin : null; } } else if (typeof optsOrigin === "function") { return optsOrigin; } else { return (origin) => optsOrigin.includes(origin) ? origin : null; } })(opts.origin); return async function cors2(c5, next) { function set(key, value) { c5.res.headers.set(key, value); } const allowOrigin = findAllowOrigin(c5.req.header("origin") || "", c5); if (allowOrigin) { set("Access-Control-Allow-Origin", allowOrigin); } if (opts.origin !== "*") { const existingVary = c5.req.header("Vary"); if (existingVary) { set("Vary", existingVary); } else { set("Vary", "Origin"); } } if (opts.credentials) { set("Access-Control-Allow-Credentials", "true"); } if (opts.exposeHeaders?.length) { set("Access-Control-Expose-Headers", opts.exposeHeaders.join(",")); } if (c5.req.method === "OPTIONS") { if (opts.maxAge != null) { set("Access-Control-Max-Age", opts.maxAge.toString()); } if (opts.allowMethods?.length) { set("Access-Control-Allow-Methods", opts.allowMethods.join(",")); } let headers = opts.allowHeaders; if (!headers?.length) { const requestHeaders = c5.req.header("Access-Control-Request-Headers"); if (requestHeaders) { headers = requestHeaders.split(/\s*,\s*/); } } if (headers?.length) { set("Access-Control-Allow-Headers", headers.join(",")); c5.res.headers.append("Vary", "Access-Control-Request-Headers"); } c5.res.headers.delete("Content-Length"); c5.res.headers.delete("Content-Type"); return new Response(null, { headers: c5.res.headers, status: 204, statusText: "No Content" }); } await next(); }; }; } }); // ../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js function dataUriToBuffer(uri) { if (!/^data:/i.test(uri)) { throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } uri = uri.replace(/\r?\n/g, ""); const firstComma = uri.indexOf(","); if (firstComma === -1 || firstComma <= 4) { throw new TypeError("malformed data: URI"); } const meta = uri.substring(5, firstComma).split(";"); let charset = ""; let base64 = false; const type = meta[0] || "text/plain"; let typeFull = type; for (let i6 = 1; i6 < meta.length; i6++) { if (meta[i6] === "base64") { base64 = true; } else if (meta[i6]) { typeFull += `;${meta[i6]}`; if (meta[i6].indexOf("charset=") === 0) { charset = meta[i6].substring(8); } } } if (!meta[0] && !charset.length) { typeFull += ";charset=US-ASCII"; charset = "US-ASCII"; } const encoding = base64 ? "base64" : "ascii"; const data = unescape(uri.substring(firstComma + 1)); const buffer = Buffer.from(data, encoding); buffer.type = type; buffer.typeFull = typeFull; buffer.charset = charset; return buffer; } var dist_default; var init_dist3 = __esm({ "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() { "use strict"; dist_default = dataUriToBuffer; } }); // ../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js var require_ponyfill_es2018 = __commonJS({ "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); })(exports2, function(exports3) { "use strict"; function noop2() { return void 0; } function typeIsObject(x5) { return typeof x5 === "object" && x5 !== null || typeof x5 === "function"; } const rethrowAssertionErrorRejection = noop2; function setFunctionName(fn, name) { try { Object.defineProperty(fn, "name", { value: name, configurable: true }); } catch (_a16) { } } const originalPromise = Promise; const originalPromiseThen = Promise.prototype.then; const originalPromiseReject = Promise.reject.bind(originalPromise); function newPromise(executor) { return new originalPromise(executor); } function promiseResolvedWith(value) { return newPromise((resolve) => resolve(value)); } function promiseRejectedWith(reason) { return originalPromiseReject(reason); } function PerformPromiseThen(promise, onFulfilled, onRejected) { return originalPromiseThen.call(promise, onFulfilled, onRejected); } function uponPromise(promise, onFulfilled, onRejected) { PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); } function uponFulfillment(promise, onFulfilled) { uponPromise(promise, onFulfilled); } function uponRejection(promise, onRejected) { uponPromise(promise, void 0, onRejected); } function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); } function setPromiseIsHandledToTrue(promise) { PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); } let _queueMicrotask = (callback) => { if (typeof queueMicrotask === "function") { _queueMicrotask = queueMicrotask; } else { const resolvedPromise = promiseResolvedWith(void 0); _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb); } return _queueMicrotask(callback); }; function reflectCall(F3, V, args) { if (typeof F3 !== "function") { throw new TypeError("Argument is not a function"); } return Function.prototype.apply.call(F3, V, args); } function promiseCall(F3, V, args) { try { return promiseResolvedWith(reflectCall(F3, V, args)); } catch (value) { return promiseRejectedWith(value); } } const QUEUE_MAX_ARRAY_SIZE = 16384; class SimpleQueue { constructor() { this._cursor = 0; this._size = 0; this._front = { _elements: [], _next: void 0 }; this._back = this._front; this._cursor = 0; this._size = 0; } get length() { return this._size; } // For exception safety, this method is structured in order: // 1. Read state // 2. Calculate required state mutations // 3. Perform state mutations push(element) { const oldBack = this._back; let newBack = oldBack; if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { newBack = { _elements: [], _next: void 0 }; } oldBack._elements.push(element); if (newBack !== oldBack) { this._back = newBack; oldBack._next = newBack; } ++this._size; } // Like push(), shift() follows the read -> calculate -> mutate pattern for // exception safety. shift() { const oldFront = this._front; let newFront = oldFront; const oldCursor = this._cursor; let newCursor = oldCursor + 1; const elements = oldFront._elements; const element = elements[oldCursor]; if (newCursor === QUEUE_MAX_ARRAY_SIZE) { newFront = oldFront._next; newCursor = 0; } --this._size; this._cursor = newCursor; if (oldFront !== newFront) { this._front = newFront; } elements[oldCursor] = void 0; return element; } // The tricky thing about forEach() is that it can be called // re-entrantly. The queue may be mutated inside the callback. It is easy to // see that push() within the callback has no negative effects since the end // of the queue is checked for on every iteration. If shift() is called // repeatedly within the callback then the next iteration may return an // element that has been removed. In this case the callback will be called // with undefined values until we either "catch up" with elements that still // exist or reach the back of the queue. forEach(callback) { let i6 = this._cursor; let node = this._front; let elements = node._elements; while (i6 !== elements.length || node._next !== void 0) { if (i6 === elements.length) { node = node._next; elements = node._elements; i6 = 0; if (elements.length === 0) { break; } } callback(elements[i6]); ++i6; } } // Return the element that would be returned if shift() was called now, // without modifying the queue. peek() { const front = this._front; const cursor = this._cursor; return front._elements[cursor]; } } const AbortSteps = Symbol("[[AbortSteps]]"); const ErrorSteps = Symbol("[[ErrorSteps]]"); const CancelSteps = Symbol("[[CancelSteps]]"); const PullSteps = Symbol("[[PullSteps]]"); const ReleaseSteps = Symbol("[[ReleaseSteps]]"); function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === "readable") { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === "closed") { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); } } function ReadableStreamReaderGenericCancel(reader, reason) { const stream = reader._ownerReadableStream; return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { const stream = reader._ownerReadableStream; if (stream._state === "readable") { defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } stream._readableStreamController[ReleaseSteps](); stream._reader = void 0; reader._ownerReadableStream = void 0; } function readerLockException(name) { return new TypeError("Cannot " + name + " a stream using a released reader"); } function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = newPromise((resolve, reject) => { reader._closedPromise_resolve = resolve; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseReject(reader, reason); } function defaultReaderClosedPromiseInitializeAsResolved(reader) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseResolve(reader); } function defaultReaderClosedPromiseReject(reader, reason) { if (reader._closedPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(reader._closedPromise); reader._closedPromise_reject(reason); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { defaultReaderClosedPromiseInitializeAsRejected(reader, reason); } function defaultReaderClosedPromiseResolve(reader) { if (reader._closedPromise_resolve === void 0) { return; } reader._closedPromise_resolve(void 0); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } const NumberIsFinite = Number.isFinite || function(x5) { return typeof x5 === "number" && isFinite(x5); }; const MathTrunc = Math.trunc || function(v6) { return v6 < 0 ? Math.ceil(v6) : Math.floor(v6); }; function isDictionary(x5) { return typeof x5 === "object" || typeof x5 === "function"; } function assertDictionary(obj, context) { if (obj !== void 0 && !isDictionary(obj)) { throw new TypeError(`${context} is not an object.`); } } function assertFunction(x5, context) { if (typeof x5 !== "function") { throw new TypeError(`${context} is not a function.`); } } function isObject(x5) { return typeof x5 === "object" && x5 !== null || typeof x5 === "function"; } function assertObject(x5, context) { if (!isObject(x5)) { throw new TypeError(`${context} is not an object.`); } } function assertRequiredArgument(x5, position, context) { if (x5 === void 0) { throw new TypeError(`Parameter ${position} is required in '${context}'.`); } } function assertRequiredField(x5, field, context) { if (x5 === void 0) { throw new TypeError(`${field} is required in '${context}'.`); } } function convertUnrestrictedDouble(value) { return Number(value); } function censorNegativeZero(x5) { return x5 === 0 ? 0 : x5; } function integerPart(x5) { return censorNegativeZero(MathTrunc(x5)); } function convertUnsignedLongLongWithEnforceRange(value, context) { const lowerBound = 0; const upperBound = Number.MAX_SAFE_INTEGER; let x5 = Number(value); x5 = censorNegativeZero(x5); if (!NumberIsFinite(x5)) { throw new TypeError(`${context} is not a finite number`); } x5 = integerPart(x5); if (x5 < lowerBound || x5 > upperBound) { throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); } if (!NumberIsFinite(x5) || x5 === 0) { return 0; } return x5; } function assertReadableStream(x5, context) { if (!IsReadableStream(x5)) { throw new TypeError(`${context} is not a ReadableStream.`); } } function AcquireReadableStreamDefaultReader(stream) { return new ReadableStreamDefaultReader(stream); } function ReadableStreamAddReadRequest(stream, readRequest) { stream._reader._readRequests.push(readRequest); } function ReadableStreamFulfillReadRequest(stream, chunk, done) { const reader = stream._reader; const readRequest = reader._readRequests.shift(); if (done) { readRequest._closeSteps(); } else { readRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadRequests(stream) { return stream._reader._readRequests.length; } function ReadableStreamHasDefaultReader(stream) { const reader = stream._reader; if (reader === void 0) { return false; } if (!IsReadableStreamDefaultReader(reader)) { return false; } return true; } class ReadableStreamDefaultReader { constructor(stream) { assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); assertReadableStream(stream, "First parameter"); if (IsReadableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive reading by another reader"); } ReadableStreamReaderGenericInitialize(this, stream); this._readRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("closed")); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = void 0) { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("cancel")); } return ReadableStreamReaderGenericCancel(this, reason); } /** * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. * * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. */ read() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("read")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("read from")); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), _closeSteps: () => resolvePromise({ value: void 0, done: true }), _errorSteps: (e6) => rejectPromise(e6) }; ReadableStreamDefaultReaderRead(this, readRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamDefaultReader(this)) { throw defaultReaderBrandCheckException("releaseLock"); } if (this._ownerReadableStream === void 0) { return; } ReadableStreamDefaultReaderRelease(this); } } Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel"); setFunctionName(ReadableStreamDefaultReader.prototype.read, "read"); setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { value: "ReadableStreamDefaultReader", configurable: true }); } function IsReadableStreamDefaultReader(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_readRequests")) { return false; } return x5 instanceof ReadableStreamDefaultReader; } function ReadableStreamDefaultReaderRead(reader, readRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === "closed") { readRequest._closeSteps(); } else if (stream._state === "errored") { readRequest._errorSteps(stream._storedError); } else { stream._readableStreamController[PullSteps](readRequest); } } function ReadableStreamDefaultReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e6 = new TypeError("Reader was released"); ReadableStreamDefaultReaderErrorReadRequests(reader, e6); } function ReadableStreamDefaultReaderErrorReadRequests(reader, e6) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach((readRequest) => { readRequest._errorSteps(e6); }); } function defaultReaderBrandCheckException(name) { return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); class ReadableStreamAsyncIteratorImpl { constructor(reader, preventCancel) { this._ongoingPromise = void 0; this._isFinished = false; this._reader = reader; this._preventCancel = preventCancel; } next() { const nextSteps = () => this._nextSteps(); this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); return this._ongoingPromise; } return(value) { const returnSteps = () => this._returnSteps(value); return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); } _nextSteps() { if (this._isFinished) { return Promise.resolve({ value: void 0, done: true }); } const reader = this._reader; let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: (chunk) => { this._ongoingPromise = void 0; _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); }, _closeSteps: () => { this._ongoingPromise = void 0; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); resolvePromise({ value: void 0, done: true }); }, _errorSteps: (reason) => { this._ongoingPromise = void 0; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); rejectPromise(reason); } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promise; } _returnSteps(value) { if (this._isFinished) { return Promise.resolve({ value, done: true }); } this._isFinished = true; const reader = this._reader; if (!this._preventCancel) { const result = ReadableStreamReaderGenericCancel(reader, value); ReadableStreamReaderGenericRelease(reader); return transformPromiseWith(result, () => ({ value, done: true })); } ReadableStreamReaderGenericRelease(reader); return promiseResolvedWith({ value, done: true }); } } const ReadableStreamAsyncIteratorPrototype = { next() { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); } return this._asyncIteratorImpl.next(); }, return(value) { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); } return this._asyncIteratorImpl.return(value); } }; Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); function AcquireReadableStreamAsyncIterator(stream, preventCancel) { const reader = AcquireReadableStreamDefaultReader(stream); const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); iterator._asyncIteratorImpl = impl; return iterator; } function IsReadableStreamAsyncIterator(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_asyncIteratorImpl")) { return false; } try { return x5._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; } catch (_a16) { return false; } } function streamAsyncIteratorBrandCheckException(name) { return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); } const NumberIsNaN = Number.isNaN || function(x5) { return x5 !== x5; }; var _a15, _b, _c; function CreateArrayFromList(elements) { return elements.slice(); } function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n5) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n5), destOffset); } let TransferArrayBuffer = (O) => { if (typeof O.transfer === "function") { TransferArrayBuffer = (buffer) => buffer.transfer(); } else if (typeof structuredClone === "function") { TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] }); } else { TransferArrayBuffer = (buffer) => buffer; } return TransferArrayBuffer(O); }; let IsDetachedBuffer = (O) => { if (typeof O.detached === "boolean") { IsDetachedBuffer = (buffer) => buffer.detached; } else { IsDetachedBuffer = (buffer) => buffer.byteLength === 0; } return IsDetachedBuffer(O); }; function ArrayBufferSlice(buffer, begin, end) { if (buffer.slice) { return buffer.slice(begin, end); } const length = end - begin; const slice = new ArrayBuffer(length); CopyDataBlockBytes(slice, 0, buffer, begin, length); return slice; } function GetMethod(receiver, prop) { const func = receiver[prop]; if (func === void 0 || func === null) { return void 0; } if (typeof func !== "function") { throw new TypeError(`${String(prop)} is not a function`); } return func; } function CreateAsyncFromSyncIterator(syncIteratorRecord) { const syncIterable = { [Symbol.iterator]: () => syncIteratorRecord.iterator }; const asyncIterator = async function* () { return yield* syncIterable; }(); const nextMethod = asyncIterator.next; return { iterator: asyncIterator, nextMethod, done: false }; } const SymbolAsyncIterator = (_c = (_a15 = Symbol.asyncIterator) !== null && _a15 !== void 0 ? _a15 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator"; function GetIterator(obj, hint = "sync", method) { if (method === void 0) { if (hint === "async") { method = GetMethod(obj, SymbolAsyncIterator); if (method === void 0) { const syncMethod = GetMethod(obj, Symbol.iterator); const syncIteratorRecord = GetIterator(obj, "sync", syncMethod); return CreateAsyncFromSyncIterator(syncIteratorRecord); } } else { method = GetMethod(obj, Symbol.iterator); } } if (method === void 0) { throw new TypeError("The object is not iterable"); } const iterator = reflectCall(method, obj, []); if (!typeIsObject(iterator)) { throw new TypeError("The iterator method must return an object"); } const nextMethod = iterator.next; return { iterator, nextMethod, done: false }; } function IteratorNext(iteratorRecord) { const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); if (!typeIsObject(result)) { throw new TypeError("The iterator.next() method must return an object"); } return result; } function IteratorComplete(iterResult) { return Boolean(iterResult.done); } function IteratorValue(iterResult) { return iterResult.value; } function IsNonNegativeNumber(v6) { if (typeof v6 !== "number") { return false; } if (NumberIsNaN(v6)) { return false; } if (v6 < 0) { return false; } return true; } function CloneAsUint8Array(O) { const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); return new Uint8Array(buffer); } function DequeueValue(container) { const pair = container._queue.shift(); container._queueTotalSize -= pair.size; if (container._queueTotalSize < 0) { container._queueTotalSize = 0; } return pair.value; } function EnqueueValueWithSize(container, value, size) { if (!IsNonNegativeNumber(size) || size === Infinity) { throw new RangeError("Size must be a finite, non-NaN, non-negative number."); } container._queue.push({ value, size }); container._queueTotalSize += size; } function PeekQueueValue(container) { const pair = container._queue.peek(); return pair.value; } function ResetQueue(container) { container._queue = new SimpleQueue(); container._queueTotalSize = 0; } function isDataViewConstructor(ctor) { return ctor === DataView; } function isDataView(view5) { return isDataViewConstructor(view5.constructor); } function arrayBufferViewElementSize(ctor) { if (isDataViewConstructor(ctor)) { return 1; } return ctor.BYTES_PER_ELEMENT; } class ReadableStreamBYOBRequest { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. */ get view() { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("view"); } return this._view; } respond(bytesWritten) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("respond"); } assertRequiredArgument(bytesWritten, 1, "respond"); bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); if (this._associatedReadableByteStreamController === void 0) { throw new TypeError("This BYOB request has been invalidated"); } if (IsDetachedBuffer(this._view.buffer)) { throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); } ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); } respondWithNewView(view5) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("respondWithNewView"); } assertRequiredArgument(view5, 1, "respondWithNewView"); if (!ArrayBuffer.isView(view5)) { throw new TypeError("You can only respond with array buffer views"); } if (this._associatedReadableByteStreamController === void 0) { throw new TypeError("This BYOB request has been invalidated"); } if (IsDetachedBuffer(view5.buffer)) { throw new TypeError("The given view's buffer has been detached and so cannot be used as a response"); } ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5); } } Object.defineProperties(ReadableStreamBYOBRequest.prototype, { respond: { enumerable: true }, respondWithNewView: { enumerable: true }, view: { enumerable: true } }); setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond"); setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { value: "ReadableStreamBYOBRequest", configurable: true }); } class ReadableByteStreamController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the current BYOB pull request, or `null` if there isn't one. */ get byobRequest() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("byobRequest"); } return ReadableByteStreamControllerGetBYOBRequest(this); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("desiredSize"); } return ReadableByteStreamControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("close"); } if (this._closeRequested) { throw new TypeError("The stream has already been closed; do not close it again!"); } const state2 = this._controlledReadableByteStream._state; if (state2 !== "readable") { throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be closed`); } ReadableByteStreamControllerClose(this); } enqueue(chunk) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("enqueue"); } assertRequiredArgument(chunk, 1, "enqueue"); if (!ArrayBuffer.isView(chunk)) { throw new TypeError("chunk must be an array buffer view"); } if (chunk.byteLength === 0) { throw new TypeError("chunk must have non-zero byteLength"); } if (chunk.buffer.byteLength === 0) { throw new TypeError(`chunk's buffer must have non-zero byteLength`); } if (this._closeRequested) { throw new TypeError("stream is closed or draining"); } const state2 = this._controlledReadableByteStream._state; if (state2 !== "readable") { throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be enqueued to`); } ReadableByteStreamControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e6 = void 0) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("error"); } ReadableByteStreamControllerError(this, e6); } /** @internal */ [CancelSteps](reason) { ReadableByteStreamControllerClearPendingPullIntos(this); ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableByteStreamControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableByteStream; if (this._queueTotalSize > 0) { ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); return; } const autoAllocateChunkSize = this._autoAllocateChunkSize; if (autoAllocateChunkSize !== void 0) { let buffer; try { buffer = new ArrayBuffer(autoAllocateChunkSize); } catch (bufferE) { readRequest._errorSteps(bufferE); return; } const pullIntoDescriptor = { buffer, bufferByteLength: autoAllocateChunkSize, byteOffset: 0, byteLength: autoAllocateChunkSize, bytesFilled: 0, minimumFill: 1, elementSize: 1, viewConstructor: Uint8Array, readerType: "default" }; this._pendingPullIntos.push(pullIntoDescriptor); } ReadableStreamAddReadRequest(stream, readRequest); ReadableByteStreamControllerCallPullIfNeeded(this); } /** @internal */ [ReleaseSteps]() { if (this._pendingPullIntos.length > 0) { const firstPullInto = this._pendingPullIntos.peek(); firstPullInto.readerType = "none"; this._pendingPullIntos = new SimpleQueue(); this._pendingPullIntos.push(firstPullInto); } } } Object.defineProperties(ReadableByteStreamController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, byobRequest: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableByteStreamController.prototype.close, "close"); setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue"); setFunctionName(ReadableByteStreamController.prototype.error, "error"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { value: "ReadableByteStreamController", configurable: true }); } function IsReadableByteStreamController(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableByteStream")) { return false; } return x5 instanceof ReadableByteStreamController; } function IsReadableStreamBYOBRequest(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_associatedReadableByteStreamController")) { return false; } return x5 instanceof ReadableStreamBYOBRequest; } function ReadableByteStreamControllerCallPullIfNeeded(controller) { const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableByteStreamControllerCallPullIfNeeded(controller); } return null; }, (e6) => { ReadableByteStreamControllerError(controller, e6); return null; }); } function ReadableByteStreamControllerClearPendingPullIntos(controller) { ReadableByteStreamControllerInvalidateBYOBRequest(controller); controller._pendingPullIntos = new SimpleQueue(); } function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { let done = false; if (stream._state === "closed") { done = true; } const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); if (pullIntoDescriptor.readerType === "default") { ReadableStreamFulfillReadRequest(stream, filledView, done); } else { ReadableStreamFulfillReadIntoRequest(stream, filledView, done); } } function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { const bytesFilled = pullIntoDescriptor.bytesFilled; const elementSize = pullIntoDescriptor.elementSize; return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); } function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { controller._queue.push({ buffer, byteOffset, byteLength }); controller._queueTotalSize += byteLength; } function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { let clonedChunk; try { clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); } catch (cloneE) { ReadableByteStreamControllerError(controller, cloneE); throw cloneE; } ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); } function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { if (firstDescriptor.bytesFilled > 0) { ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); } ReadableByteStreamControllerShiftPendingPullInto(controller); } function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; let totalBytesToCopyRemaining = maxBytesToCopy; let ready = false; const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; const maxAlignedBytes = maxBytesFilled - remainderBytes; if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; ready = true; } const queue = controller._queue; while (totalBytesToCopyRemaining > 0) { const headOfQueue = queue.peek(); const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); if (headOfQueue.byteLength === bytesToCopy) { queue.shift(); } else { headOfQueue.byteOffset += bytesToCopy; headOfQueue.byteLength -= bytesToCopy; } controller._queueTotalSize -= bytesToCopy; ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); totalBytesToCopyRemaining -= bytesToCopy; } return ready; } function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { pullIntoDescriptor.bytesFilled += size; } function ReadableByteStreamControllerHandleQueueDrain(controller) { if (controller._queueTotalSize === 0 && controller._closeRequested) { ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(controller._controlledReadableByteStream); } else { ReadableByteStreamControllerCallPullIfNeeded(controller); } } function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { if (controller._byobRequest === null) { return; } controller._byobRequest._associatedReadableByteStreamController = void 0; controller._byobRequest._view = null; controller._byobRequest = null; } function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { while (controller._pendingPullIntos.length > 0) { if (controller._queueTotalSize === 0) { return; } const pullIntoDescriptor = controller._pendingPullIntos.peek(); if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); } } } function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { const reader = controller._controlledReadableByteStream._reader; while (reader._readRequests.length > 0) { if (controller._queueTotalSize === 0) { return; } const readRequest = reader._readRequests.shift(); ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); } } function ReadableByteStreamControllerPullInto(controller, view5, min, readIntoRequest) { const stream = controller._controlledReadableByteStream; const ctor = view5.constructor; const elementSize = arrayBufferViewElementSize(ctor); const { byteOffset, byteLength } = view5; const minimumFill = min * elementSize; let buffer; try { buffer = TransferArrayBuffer(view5.buffer); } catch (e6) { readIntoRequest._errorSteps(e6); return; } const pullIntoDescriptor = { buffer, bufferByteLength: buffer.byteLength, byteOffset, byteLength, bytesFilled: 0, minimumFill, elementSize, viewConstructor: ctor, readerType: "byob" }; if (controller._pendingPullIntos.length > 0) { controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(stream, readIntoRequest); return; } if (stream._state === "closed") { const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); readIntoRequest._closeSteps(emptyView); return; } if (controller._queueTotalSize > 0) { if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); ReadableByteStreamControllerHandleQueueDrain(controller); readIntoRequest._chunkSteps(filledView); return; } if (controller._closeRequested) { const e6 = new TypeError("Insufficient bytes to fill elements in the given buffer"); ReadableByteStreamControllerError(controller, e6); readIntoRequest._errorSteps(e6); return; } } controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(stream, readIntoRequest); ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { if (firstDescriptor.readerType === "none") { ReadableByteStreamControllerShiftPendingPullInto(controller); } const stream = controller._controlledReadableByteStream; if (ReadableStreamHasBYOBReader(stream)) { while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); } } } function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); if (pullIntoDescriptor.readerType === "none") { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); return; } if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { return; } ReadableByteStreamControllerShiftPendingPullInto(controller); const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; if (remainderSize > 0) { const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); } pullIntoDescriptor.bytesFilled -= remainderSize; ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); ReadableByteStreamControllerInvalidateBYOBRequest(controller); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); } else { ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerShiftPendingPullInto(controller) { const descriptor = controller._pendingPullIntos.shift(); return descriptor; } function ReadableByteStreamControllerShouldCallPull(controller) { const stream = controller._controlledReadableByteStream; if (stream._state !== "readable") { return false; } if (controller._closeRequested) { return false; } if (!controller._started) { return false; } if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { return true; } const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableByteStreamControllerClearAlgorithms(controller) { controller._pullAlgorithm = void 0; controller._cancelAlgorithm = void 0; } function ReadableByteStreamControllerClose(controller) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== "readable") { return; } if (controller._queueTotalSize > 0) { controller._closeRequested = true; return; } if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { const e6 = new TypeError("Insufficient bytes to fill elements in the given buffer"); ReadableByteStreamControllerError(controller, e6); throw e6; } } ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(stream); } function ReadableByteStreamControllerEnqueue(controller, chunk) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== "readable") { return; } const { buffer, byteOffset, byteLength } = chunk; if (IsDetachedBuffer(buffer)) { throw new TypeError("chunk's buffer is detached and so cannot be enqueued"); } const transferredBuffer = TransferArrayBuffer(buffer); if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (IsDetachedBuffer(firstPendingPullInto.buffer)) { throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk"); } ReadableByteStreamControllerInvalidateBYOBRequest(controller); firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); if (firstPendingPullInto.readerType === "none") { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); } } if (ReadableStreamHasDefaultReader(stream)) { ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); if (ReadableStreamGetNumReadRequests(stream) === 0) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } else { if (controller._pendingPullIntos.length > 0) { ReadableByteStreamControllerShiftPendingPullInto(controller); } const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); ReadableStreamFulfillReadRequest(stream, transferredView, false); } } else if (ReadableStreamHasBYOBReader(stream)) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } else { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerError(controller, e6) { const stream = controller._controlledReadableByteStream; if (stream._state !== "readable") { return; } ReadableByteStreamControllerClearPendingPullIntos(controller); ResetQueue(controller); ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamError(stream, e6); } function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { const entry = controller._queue.shift(); controller._queueTotalSize -= entry.byteLength; ReadableByteStreamControllerHandleQueueDrain(controller); const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); readRequest._chunkSteps(view5); } function ReadableByteStreamControllerGetBYOBRequest(controller) { if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { const firstDescriptor = controller._pendingPullIntos.peek(); const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); SetUpReadableStreamBYOBRequest(byobRequest, controller, view5); controller._byobRequest = byobRequest; } return controller._byobRequest; } function ReadableByteStreamControllerGetDesiredSize(controller) { const state2 = controller._controlledReadableByteStream._state; if (state2 === "errored") { return null; } if (state2 === "closed") { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableByteStreamControllerRespond(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { if (bytesWritten !== 0) { throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); } } else { if (bytesWritten === 0) { throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); } if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { throw new RangeError("bytesWritten out of range"); } } firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } function ReadableByteStreamControllerRespondWithNewView(controller, view5) { const firstDescriptor = controller._pendingPullIntos.peek(); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { if (view5.byteLength !== 0) { throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); } } else { if (view5.byteLength === 0) { throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); } } if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view5.byteOffset) { throw new RangeError("The region specified by view does not match byobRequest"); } if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) { throw new RangeError("The buffer of view has different capacity than byobRequest"); } if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) { throw new RangeError("The region specified by view is larger than byobRequest"); } const viewByteLength = view5.byteLength; firstDescriptor.buffer = TransferArrayBuffer(view5.buffer); ReadableByteStreamControllerRespondInternal(controller, viewByteLength); } function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { controller._controlledReadableByteStream = stream; controller._pullAgain = false; controller._pulling = false; controller._byobRequest = null; controller._queue = controller._queueTotalSize = void 0; ResetQueue(controller); controller._closeRequested = false; controller._started = false; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._autoAllocateChunkSize = autoAllocateChunkSize; controller._pendingPullIntos = new SimpleQueue(); stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableByteStreamControllerCallPullIfNeeded(controller); return null; }, (r6) => { ReadableByteStreamControllerError(controller, r6); return null; }); } function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { const controller = Object.create(ReadableByteStreamController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingByteSource.start !== void 0) { startAlgorithm = () => underlyingByteSource.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingByteSource.pull !== void 0) { pullAlgorithm = () => underlyingByteSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingByteSource.cancel !== void 0) { cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; if (autoAllocateChunkSize === 0) { throw new TypeError("autoAllocateChunkSize must be greater than 0"); } SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); } function SetUpReadableStreamBYOBRequest(request2, controller, view5) { request2._associatedReadableByteStreamController = controller; request2._view = view5; } function byobRequestBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); } function byteStreamControllerBrandCheckException(name) { return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); } function convertReaderOptions(options, context) { assertDictionary(options, context); const mode = options === null || options === void 0 ? void 0 : options.mode; return { mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) }; } function convertReadableStreamReaderMode(mode, context) { mode = `${mode}`; if (mode !== "byob") { throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); } return mode; } function convertByobReadOptions(options, context) { var _a16; assertDictionary(options, context); const min = (_a16 = options === null || options === void 0 ? void 0 : options.min) !== null && _a16 !== void 0 ? _a16 : 1; return { min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) }; } function AcquireReadableStreamBYOBReader(stream) { return new ReadableStreamBYOBReader(stream); } function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { stream._reader._readIntoRequests.push(readIntoRequest); } function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { const reader = stream._reader; const readIntoRequest = reader._readIntoRequests.shift(); if (done) { readIntoRequest._closeSteps(chunk); } else { readIntoRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadIntoRequests(stream) { return stream._reader._readIntoRequests.length; } function ReadableStreamHasBYOBReader(stream) { const reader = stream._reader; if (reader === void 0) { return false; } if (!IsReadableStreamBYOBReader(reader)) { return false; } return true; } class ReadableStreamBYOBReader { constructor(stream) { assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); assertReadableStream(stream, "First parameter"); if (IsReadableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive reading by another reader"); } if (!IsReadableByteStreamController(stream._readableStreamController)) { throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); } ReadableStreamReaderGenericInitialize(this, stream); this._readIntoRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("closed")); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = void 0) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("cancel")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("cancel")); } return ReadableStreamReaderGenericCancel(this, reason); } read(view5, rawOptions = {}) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("read")); } if (!ArrayBuffer.isView(view5)) { return promiseRejectedWith(new TypeError("view must be an array buffer view")); } if (view5.byteLength === 0) { return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); } if (view5.buffer.byteLength === 0) { return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); } if (IsDetachedBuffer(view5.buffer)) { return promiseRejectedWith(new TypeError("view's buffer has been detached")); } let options; try { options = convertByobReadOptions(rawOptions, "options"); } catch (e6) { return promiseRejectedWith(e6); } const min = options.min; if (min === 0) { return promiseRejectedWith(new TypeError("options.min must be greater than 0")); } if (!isDataView(view5)) { if (min > view5.length) { return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length")); } } else if (min > view5.byteLength) { return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("read from")); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readIntoRequest = { _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), _errorSteps: (e6) => rejectPromise(e6) }; ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamBYOBReader(this)) { throw byobReaderBrandCheckException("releaseLock"); } if (this._ownerReadableStream === void 0) { return; } ReadableStreamBYOBReaderRelease(this); } } Object.defineProperties(ReadableStreamBYOBReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel"); setFunctionName(ReadableStreamBYOBReader.prototype.read, "read"); setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { value: "ReadableStreamBYOBReader", configurable: true }); } function IsReadableStreamBYOBReader(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_readIntoRequests")) { return false; } return x5 instanceof ReadableStreamBYOBReader; } function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === "errored") { readIntoRequest._errorSteps(stream._storedError); } else { ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest); } } function ReadableStreamBYOBReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e6 = new TypeError("Reader was released"); ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6); } function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach((readIntoRequest) => { readIntoRequest._errorSteps(e6); }); } function byobReaderBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); } function ExtractHighWaterMark(strategy, defaultHWM) { const { highWaterMark } = strategy; if (highWaterMark === void 0) { return defaultHWM; } if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError("Invalid highWaterMark"); } return highWaterMark; } function ExtractSizeAlgorithm(strategy) { const { size } = strategy; if (!size) { return () => 1; } return size; } function convertQueuingStrategy(init2, context) { assertDictionary(init2, context); const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark; const size = init2 === null || init2 === void 0 ? void 0 : init2.size; return { highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark), size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`) }; } function convertQueuingStrategySize(fn, context) { assertFunction(fn, context); return (chunk) => convertUnrestrictedDouble(fn(chunk)); } function convertUnderlyingSink(original, context) { assertDictionary(original, context); const abort = original === null || original === void 0 ? void 0 : original.abort; const close = original === null || original === void 0 ? void 0 : original.close; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; const write = original === null || original === void 0 ? void 0 : original.write; return { abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), type }; } function convertUnderlyingSinkAbortCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSinkCloseCallback(fn, original, context) { assertFunction(fn, context); return () => promiseCall(fn, original, []); } function convertUnderlyingSinkStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertUnderlyingSinkWriteCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } function assertWritableStream(x5, context) { if (!IsWritableStream(x5)) { throw new TypeError(`${context} is not a WritableStream.`); } } function isAbortSignal2(value) { if (typeof value !== "object" || value === null) { return false; } try { return typeof value.aborted === "boolean"; } catch (_a16) { return false; } } const supportsAbortController = typeof AbortController === "function"; function createAbortController() { if (supportsAbortController) { return new AbortController(); } return void 0; } class WritableStream { constructor(rawUnderlyingSink = {}, rawStrategy = {}) { if (rawUnderlyingSink === void 0) { rawUnderlyingSink = null; } else { assertObject(rawUnderlyingSink, "First parameter"); } const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); InitializeWritableStream(this); const type = underlyingSink.type; if (type !== void 0) { throw new RangeError("Invalid type is specified"); } const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); } /** * Returns whether or not the writable stream is locked to a writer. */ get locked() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2("locked"); } return IsWritableStreamLocked(this); } /** * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort * mechanism of the underlying sink. * * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel * the stream) if the stream is currently locked. */ abort(reason = void 0) { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2("abort")); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); } return WritableStreamAbort(this, reason); } /** * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its * close behavior. During this time any further attempts to write will fail (without erroring the stream). * * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. */ close() { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2("close")); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); } if (WritableStreamCloseQueuedOrInFlight(this)) { return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); } return WritableStreamClose(this); } /** * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream * is locked, no other writer can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to write to a stream * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at * the same time, which would cause the resulting written data to be unpredictable and probably useless. */ getWriter() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2("getWriter"); } return AcquireWritableStreamDefaultWriter(this); } } Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(WritableStream.prototype.abort, "abort"); setFunctionName(WritableStream.prototype.close, "close"); setFunctionName(WritableStream.prototype.getWriter, "getWriter"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { value: "WritableStream", configurable: true }); } function AcquireWritableStreamDefaultWriter(stream) { return new WritableStreamDefaultWriter(stream); } function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(WritableStream.prototype); InitializeWritableStream(stream); const controller = Object.create(WritableStreamDefaultController.prototype); SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function InitializeWritableStream(stream) { stream._state = "writable"; stream._storedError = void 0; stream._writer = void 0; stream._writableStreamController = void 0; stream._writeRequests = new SimpleQueue(); stream._inFlightWriteRequest = void 0; stream._closeRequest = void 0; stream._inFlightCloseRequest = void 0; stream._pendingAbortRequest = void 0; stream._backpressure = false; } function IsWritableStream(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_writableStreamController")) { return false; } return x5 instanceof WritableStream; } function IsWritableStreamLocked(stream) { if (stream._writer === void 0) { return false; } return true; } function WritableStreamAbort(stream, reason) { var _a16; if (stream._state === "closed" || stream._state === "errored") { return promiseResolvedWith(void 0); } stream._writableStreamController._abortReason = reason; (_a16 = stream._writableStreamController._abortController) === null || _a16 === void 0 ? void 0 : _a16.abort(reason); const state2 = stream._state; if (state2 === "closed" || state2 === "errored") { return promiseResolvedWith(void 0); } if (stream._pendingAbortRequest !== void 0) { return stream._pendingAbortRequest._promise; } let wasAlreadyErroring = false; if (state2 === "erroring") { wasAlreadyErroring = true; reason = void 0; } const promise = newPromise((resolve, reject) => { stream._pendingAbortRequest = { _promise: void 0, _resolve: resolve, _reject: reject, _reason: reason, _wasAlreadyErroring: wasAlreadyErroring }; }); stream._pendingAbortRequest._promise = promise; if (!wasAlreadyErroring) { WritableStreamStartErroring(stream, reason); } return promise; } function WritableStreamClose(stream) { const state2 = stream._state; if (state2 === "closed" || state2 === "errored") { return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`)); } const promise = newPromise((resolve, reject) => { const closeRequest = { _resolve: resolve, _reject: reject }; stream._closeRequest = closeRequest; }); const writer = stream._writer; if (writer !== void 0 && stream._backpressure && state2 === "writable") { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } function WritableStreamAddWriteRequest(stream) { const promise = newPromise((resolve, reject) => { const writeRequest = { _resolve: resolve, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream, error2) { const state2 = stream._state; if (state2 === "writable") { WritableStreamStartErroring(stream, error2); return; } WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream, reason) { const controller = stream._writableStreamController; stream._state = "erroring"; stream._storedError = reason; const writer = stream._writer; if (writer !== void 0) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream) { stream._state = "errored"; stream._writableStreamController[ErrorSteps](); const storedError = stream._storedError; stream._writeRequests.forEach((writeRequest) => { writeRequest._reject(storedError); }); stream._writeRequests = new SimpleQueue(); if (stream._pendingAbortRequest === void 0) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = void 0; if (abortRequest._wasAlreadyErroring) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); uponPromise(promise, () => { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }, (reason) => { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }); } function WritableStreamFinishInFlightWrite(stream) { stream._inFlightWriteRequest._resolve(void 0); stream._inFlightWriteRequest = void 0; } function WritableStreamFinishInFlightWriteWithError(stream, error2) { stream._inFlightWriteRequest._reject(error2); stream._inFlightWriteRequest = void 0; WritableStreamDealWithRejection(stream, error2); } function WritableStreamFinishInFlightClose(stream) { stream._inFlightCloseRequest._resolve(void 0); stream._inFlightCloseRequest = void 0; const state2 = stream._state; if (state2 === "erroring") { stream._storedError = void 0; if (stream._pendingAbortRequest !== void 0) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = void 0; } } stream._state = "closed"; const writer = stream._writer; if (writer !== void 0) { defaultWriterClosedPromiseResolve(writer); } } function WritableStreamFinishInFlightCloseWithError(stream, error2) { stream._inFlightCloseRequest._reject(error2); stream._inFlightCloseRequest = void 0; if (stream._pendingAbortRequest !== void 0) { stream._pendingAbortRequest._reject(error2); stream._pendingAbortRequest = void 0; } WritableStreamDealWithRejection(stream, error2); } function WritableStreamCloseQueuedOrInFlight(stream) { if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream) { if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream) { stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = void 0; } function WritableStreamMarkFirstWriteRequestInFlight(stream) { stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { if (stream._closeRequest !== void 0) { stream._closeRequest._reject(stream._storedError); stream._closeRequest = void 0; } const writer = stream._writer; if (writer !== void 0) { defaultWriterClosedPromiseReject(writer, stream._storedError); } } function WritableStreamUpdateBackpressure(stream, backpressure) { const writer = stream._writer; if (writer !== void 0 && backpressure !== stream._backpressure) { if (backpressure) { defaultWriterReadyPromiseReset(writer); } else { defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } class WritableStreamDefaultWriter { constructor(stream) { assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); assertWritableStream(stream, "First parameter"); if (IsWritableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive writing by another writer"); } this._ownerWritableStream = stream; stream._writer = this; const state2 = stream._state; if (state2 === "writable") { if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state2 === "erroring") { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); defaultWriterClosedPromiseInitialize(this); } else if (state2 === "closed") { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { const storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the writer’s lock is released before the stream finishes closing. */ get closed() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("closed")); } return this._closedPromise; } /** * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. * A producer can use this information to determine the right amount of data to write. * * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when * the writer’s lock is released. */ get desiredSize() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException("desiredSize"); } if (this._ownerWritableStream === void 0) { throw defaultWriterLockException("desiredSize"); } return WritableStreamDefaultWriterGetDesiredSize(this); } /** * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips * back to zero or below, the getter will return a new promise that stays pending until the next transition. * * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become * rejected. */ get ready() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("ready")); } return this._readyPromise; } /** * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. */ abort(reason = void 0) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("abort")); } if (this._ownerWritableStream === void 0) { return promiseRejectedWith(defaultWriterLockException("abort")); } return WritableStreamDefaultWriterAbort(this, reason); } /** * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. */ close() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("close")); } const stream = this._ownerWritableStream; if (stream === void 0) { return promiseRejectedWith(defaultWriterLockException("close")); } if (WritableStreamCloseQueuedOrInFlight(stream)) { return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); } return WritableStreamDefaultWriterClose(this); } /** * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from * now on; otherwise, the writer will appear closed. * * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents * other producers from writing in an interleaved manner. */ releaseLock() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException("releaseLock"); } const stream = this._ownerWritableStream; if (stream === void 0) { return; } WritableStreamDefaultWriterRelease(this); } write(chunk = void 0) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("write")); } if (this._ownerWritableStream === void 0) { return promiseRejectedWith(defaultWriterLockException("write to")); } return WritableStreamDefaultWriterWrite(this, chunk); } } Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }); setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort"); setFunctionName(WritableStreamDefaultWriter.prototype.close, "close"); setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock"); setFunctionName(WritableStreamDefaultWriter.prototype.write, "write"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { value: "WritableStreamDefaultWriter", configurable: true }); } function IsWritableStreamDefaultWriter(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_ownerWritableStream")) { return false; } return x5 instanceof WritableStreamDefaultWriter; } function WritableStreamDefaultWriterAbort(writer, reason) { const stream = writer._ownerWritableStream; return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer) { const stream = writer._ownerWritableStream; return WritableStreamClose(stream); } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { const stream = writer._ownerWritableStream; const state2 = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") { return promiseResolvedWith(void 0); } if (state2 === "errored") { return promiseRejectedWith(stream._storedError); } return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) { if (writer._closedPromiseState === "pending") { defaultWriterClosedPromiseReject(writer, error2); } else { defaultWriterClosedPromiseResetToRejected(writer, error2); } } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) { if (writer._readyPromiseState === "pending") { defaultWriterReadyPromiseReject(writer, error2); } else { defaultWriterReadyPromiseResetToRejected(writer, error2); } } function WritableStreamDefaultWriterGetDesiredSize(writer) { const stream = writer._ownerWritableStream; const state2 = stream._state; if (state2 === "errored" || state2 === "erroring") { return null; } if (state2 === "closed") { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer) { const stream = writer._ownerWritableStream; const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = void 0; writer._ownerWritableStream = void 0; } function WritableStreamDefaultWriterWrite(writer, chunk) { const stream = writer._ownerWritableStream; const controller = stream._writableStreamController; const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return promiseRejectedWith(defaultWriterLockException("write to")); } const state2 = stream._state; if (state2 === "errored") { return promiseRejectedWith(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") { return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); } if (state2 === "erroring") { return promiseRejectedWith(stream._storedError); } const promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } const closeSentinel = {}; class WritableStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. * * @deprecated * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. */ get abortReason() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("abortReason"); } return this._abortReason; } /** * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. */ get signal() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("signal"); } if (this._abortController === void 0) { throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); } return this._abortController.signal; } /** * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. * * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the * normal lifecycle of interactions with the underlying sink. */ error(e6 = void 0) { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("error"); } const state2 = this._controlledWritableStream._state; if (state2 !== "writable") { return; } WritableStreamDefaultControllerError(this, e6); } /** @internal */ [AbortSteps](reason) { const result = this._abortAlgorithm(reason); WritableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [ErrorSteps]() { ResetQueue(this); } } Object.defineProperties(WritableStreamDefaultController.prototype, { abortReason: { enumerable: true }, signal: { enumerable: true }, error: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { value: "WritableStreamDefaultController", configurable: true }); } function IsWritableStreamDefaultController(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_controlledWritableStream")) { return false; } return x5 instanceof WritableStreamDefaultController; } function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledWritableStream = stream; stream._writableStreamController = controller; controller._queue = void 0; controller._queueTotalSize = void 0; ResetQueue(controller); controller._abortReason = void 0; controller._abortController = createAbortController(); controller._started = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._writeAlgorithm = writeAlgorithm; controller._closeAlgorithm = closeAlgorithm; controller._abortAlgorithm = abortAlgorithm; const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); const startPromise = promiseResolvedWith(startResult); uponPromise(startPromise, () => { controller._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, (r6) => { controller._started = true; WritableStreamDealWithRejection(stream, r6); return null; }); } function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { const controller = Object.create(WritableStreamDefaultController.prototype); let startAlgorithm; let writeAlgorithm; let closeAlgorithm; let abortAlgorithm; if (underlyingSink.start !== void 0) { startAlgorithm = () => underlyingSink.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingSink.write !== void 0) { writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); } else { writeAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSink.close !== void 0) { closeAlgorithm = () => underlyingSink.close(); } else { closeAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSink.abort !== void 0) { abortAlgorithm = (reason) => underlyingSink.abort(reason); } else { abortAlgorithm = () => promiseResolvedWith(void 0); } SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); } function WritableStreamDefaultControllerClearAlgorithms(controller) { controller._writeAlgorithm = void 0; controller._closeAlgorithm = void 0; controller._abortAlgorithm = void 0; controller._strategySizeAlgorithm = void 0; } function WritableStreamDefaultControllerClose(controller) { EnqueueValueWithSize(controller, closeSentinel, 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { try { return controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller) { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } const stream = controller._controlledWritableStream; if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { const stream = controller._controlledWritableStream; if (!controller._started) { return; } if (stream._inFlightWriteRequest !== void 0) { return; } const state2 = stream._state; if (state2 === "erroring") { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } const value = PeekQueueValue(controller); if (value === closeSentinel) { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, value); } } function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) { if (controller._controlledWritableStream._state === "writable") { WritableStreamDefaultControllerError(controller, error2); } } function WritableStreamDefaultControllerProcessClose(controller) { const stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); const sinkClosePromise = controller._closeAlgorithm(); WritableStreamDefaultControllerClearAlgorithms(controller); uponPromise(sinkClosePromise, () => { WritableStreamFinishInFlightClose(stream); return null; }, (reason) => { WritableStreamFinishInFlightCloseWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerProcessWrite(controller, chunk) { const stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); const sinkWritePromise = controller._writeAlgorithm(chunk); uponPromise(sinkWritePromise, () => { WritableStreamFinishInFlightWrite(stream); const state2 = stream._state; DequeueValue(controller); if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "writable") { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, (reason) => { if (stream._state === "writable") { WritableStreamDefaultControllerClearAlgorithms(controller); } WritableStreamFinishInFlightWriteWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerGetBackpressure(controller) { const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } function WritableStreamDefaultControllerError(controller, error2) { const stream = controller._controlledWritableStream; WritableStreamDefaultControllerClearAlgorithms(controller); WritableStreamStartErroring(stream, error2); } function streamBrandCheckException$2(name) { return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } function defaultControllerBrandCheckException$2(name) { return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } function defaultWriterBrandCheckException(name) { return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } function defaultWriterLockException(name) { return new TypeError("Cannot " + name + " a stream using a released writer"); } function defaultWriterClosedPromiseInitialize(writer) { writer._closedPromise = newPromise((resolve, reject) => { writer._closedPromise_resolve = resolve; writer._closedPromise_reject = reject; writer._closedPromiseState = "pending"; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseReject(writer, reason); } function defaultWriterClosedPromiseInitializeAsResolved(writer) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseResolve(writer); } function defaultWriterClosedPromiseReject(writer, reason) { if (writer._closedPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(writer._closedPromise); writer._closedPromise_reject(reason); writer._closedPromise_resolve = void 0; writer._closedPromise_reject = void 0; writer._closedPromiseState = "rejected"; } function defaultWriterClosedPromiseResetToRejected(writer, reason) { defaultWriterClosedPromiseInitializeAsRejected(writer, reason); } function defaultWriterClosedPromiseResolve(writer) { if (writer._closedPromise_resolve === void 0) { return; } writer._closedPromise_resolve(void 0); writer._closedPromise_resolve = void 0; writer._closedPromise_reject = void 0; writer._closedPromiseState = "resolved"; } function defaultWriterReadyPromiseInitialize(writer) { writer._readyPromise = newPromise((resolve, reject) => { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = "pending"; } function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseReject(writer, reason); } function defaultWriterReadyPromiseInitializeAsResolved(writer) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseResolve(writer); } function defaultWriterReadyPromiseReject(writer, reason) { if (writer._readyPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(writer._readyPromise); writer._readyPromise_reject(reason); writer._readyPromise_resolve = void 0; writer._readyPromise_reject = void 0; writer._readyPromiseState = "rejected"; } function defaultWriterReadyPromiseReset(writer) { defaultWriterReadyPromiseInitialize(writer); } function defaultWriterReadyPromiseResetToRejected(writer, reason) { defaultWriterReadyPromiseInitializeAsRejected(writer, reason); } function defaultWriterReadyPromiseResolve(writer) { if (writer._readyPromise_resolve === void 0) { return; } writer._readyPromise_resolve(void 0); writer._readyPromise_resolve = void 0; writer._readyPromise_reject = void 0; writer._readyPromiseState = "fulfilled"; } function getGlobals() { if (typeof globalThis !== "undefined") { return globalThis; } else if (typeof self !== "undefined") { return self; } else if (typeof global !== "undefined") { return global; } return void 0; } const globals = getGlobals(); function isDOMExceptionConstructor(ctor) { if (!(typeof ctor === "function" || typeof ctor === "object")) { return false; } if (ctor.name !== "DOMException") { return false; } try { new ctor(); return true; } catch (_a16) { return false; } } function getFromGlobal() { const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; return isDOMExceptionConstructor(ctor) ? ctor : void 0; } function createPolyfill() { const ctor = function DOMException3(message, name) { this.message = message || ""; this.name = name || "Error"; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }; setFunctionName(ctor, "DOMException"); ctor.prototype = Object.create(Error.prototype); Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); return ctor; } const DOMException2 = getFromGlobal() || createPolyfill(); function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { const reader = AcquireReadableStreamDefaultReader(source); const writer = AcquireWritableStreamDefaultWriter(dest); source._disturbed = true; let shuttingDown = false; let currentWrite = promiseResolvedWith(void 0); return newPromise((resolve, reject) => { let abortAlgorithm; if (signal !== void 0) { abortAlgorithm = () => { const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError"); const actions = []; if (!preventAbort) { actions.push(() => { if (dest._state === "writable") { return WritableStreamAbort(dest, error2); } return promiseResolvedWith(void 0); }); } if (!preventCancel) { actions.push(() => { if (source._state === "readable") { return ReadableStreamCancel(source, error2); } return promiseResolvedWith(void 0); }); } shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2); }; if (signal.aborted) { abortAlgorithm(); return; } signal.addEventListener("abort", abortAlgorithm); } function pipeLoop() { return newPromise((resolveLoop, rejectLoop) => { function next(done) { if (done) { resolveLoop(); } else { PerformPromiseThen(pipeStep(), next, rejectLoop); } } next(false); }); } function pipeStep() { if (shuttingDown) { return promiseResolvedWith(true); } return PerformPromiseThen(writer._readyPromise, () => { return newPromise((resolveRead, rejectRead) => { ReadableStreamDefaultReaderRead(reader, { _chunkSteps: (chunk) => { currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); resolveRead(false); }, _closeSteps: () => resolveRead(true), _errorSteps: rejectRead }); }); }); } isOrBecomesErrored(source, reader._closedPromise, (storedError) => { if (!preventAbort) { shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); isOrBecomesClosed(source, reader._closedPromise, () => { if (!preventClose) { shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); } else { shutdown(); } return null; }); if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); } else { shutdown(true, destClosed); } } setPromiseIsHandledToTrue(pipeLoop()); function waitForWritesToFinish() { const oldCurrentWrite = currentWrite; return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); } function isOrBecomesErrored(stream, promise, action) { if (stream._state === "errored") { action(stream._storedError); } else { uponRejection(promise, action); } } function isOrBecomesClosed(stream, promise, action) { if (stream._state === "closed") { action(); } else { uponFulfillment(promise, action); } } function shutdownWithAction(action, originalIsError, originalError) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), doTheRest); } else { doTheRest(); } function doTheRest() { uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); return null; } } function shutdown(isError, error2) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2)); } else { finalize(isError, error2); } } function finalize(isError, error2) { WritableStreamDefaultWriterRelease(writer); ReadableStreamReaderGenericRelease(reader); if (signal !== void 0) { signal.removeEventListener("abort", abortAlgorithm); } if (isError) { reject(error2); } else { resolve(void 0); } return null; } }); } class ReadableStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("desiredSize"); } return ReadableStreamDefaultControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("close"); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError("The stream is not in a state that permits close"); } ReadableStreamDefaultControllerClose(this); } enqueue(chunk = void 0) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("enqueue"); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError("The stream is not in a state that permits enqueue"); } return ReadableStreamDefaultControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e6 = void 0) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("error"); } ReadableStreamDefaultControllerError(this, e6); } /** @internal */ [CancelSteps](reason) { ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableStream; if (this._queue.length > 0) { const chunk = DequeueValue(this); if (this._closeRequested && this._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(this); ReadableStreamClose(stream); } else { ReadableStreamDefaultControllerCallPullIfNeeded(this); } readRequest._chunkSteps(chunk); } else { ReadableStreamAddReadRequest(stream, readRequest); ReadableStreamDefaultControllerCallPullIfNeeded(this); } } /** @internal */ [ReleaseSteps]() { } } Object.defineProperties(ReadableStreamDefaultController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableStreamDefaultController.prototype.close, "close"); setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue"); setFunctionName(ReadableStreamDefaultController.prototype.error, "error"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { value: "ReadableStreamDefaultController", configurable: true }); } function IsReadableStreamDefaultController(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableStream")) { return false; } return x5 instanceof ReadableStreamDefaultController; } function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableStreamDefaultControllerCallPullIfNeeded(controller); } return null; }, (e6) => { ReadableStreamDefaultControllerError(controller, e6); return null; }); } function ReadableStreamDefaultControllerShouldCallPull(controller) { const stream = controller._controlledReadableStream; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return false; } if (!controller._started) { return false; } if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableStreamDefaultControllerClearAlgorithms(controller) { controller._pullAlgorithm = void 0; controller._cancelAlgorithm = void 0; controller._strategySizeAlgorithm = void 0; } function ReadableStreamDefaultControllerClose(controller) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; controller._closeRequested = true; if (controller._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamClose(stream); } } function ReadableStreamDefaultControllerEnqueue(controller, chunk) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { ReadableStreamFulfillReadRequest(stream, chunk, false); } else { let chunkSize; try { chunkSize = controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { ReadableStreamDefaultControllerError(controller, chunkSizeE); throw chunkSizeE; } try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { ReadableStreamDefaultControllerError(controller, enqueueE); throw enqueueE; } } ReadableStreamDefaultControllerCallPullIfNeeded(controller); } function ReadableStreamDefaultControllerError(controller, e6) { const stream = controller._controlledReadableStream; if (stream._state !== "readable") { return; } ResetQueue(controller); ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamError(stream, e6); } function ReadableStreamDefaultControllerGetDesiredSize(controller) { const state2 = controller._controlledReadableStream._state; if (state2 === "errored") { return null; } if (state2 === "closed") { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableStreamDefaultControllerHasBackpressure(controller) { if (ReadableStreamDefaultControllerShouldCallPull(controller)) { return false; } return true; } function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { const state2 = controller._controlledReadableStream._state; if (!controller._closeRequested && state2 === "readable") { return true; } return false; } function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledReadableStream = stream; controller._queue = void 0; controller._queueTotalSize = void 0; ResetQueue(controller); controller._started = false; controller._closeRequested = false; controller._pullAgain = false; controller._pulling = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableStreamDefaultControllerCallPullIfNeeded(controller); return null; }, (r6) => { ReadableStreamDefaultControllerError(controller, r6); return null; }); } function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { const controller = Object.create(ReadableStreamDefaultController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingSource.start !== void 0) { startAlgorithm = () => underlyingSource.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingSource.pull !== void 0) { pullAlgorithm = () => underlyingSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSource.cancel !== void 0) { cancelAlgorithm = (reason) => underlyingSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); } function defaultControllerBrandCheckException$1(name) { return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); } function ReadableStreamTee(stream, cloneForBranch2) { if (IsReadableByteStreamController(stream._readableStreamController)) { return ReadableByteStreamTee(stream); } return ReadableStreamDefaultTee(stream); } function ReadableStreamDefaultTee(stream, cloneForBranch2) { const reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgain = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise((resolve) => { resolveCancelPromise = resolve; }); function pullAlgorithm() { if (reading) { readAgain = true; return promiseResolvedWith(void 0); } reading = true; const readRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgain = false; const chunk1 = chunk; const chunk2 = chunk; if (!canceled1) { ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgain) { pullAlgorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableStreamDefaultControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableStreamDefaultControllerClose(branch2._readableStreamController); } if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promiseResolvedWith(void 0); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { } branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); uponRejection(reader._closedPromise, (r6) => { ReadableStreamDefaultControllerError(branch1._readableStreamController, r6); ReadableStreamDefaultControllerError(branch2._readableStreamController, r6); if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } return null; }); return [branch1, branch2]; } function ReadableByteStreamTee(stream) { let reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgainForBranch1 = false; let readAgainForBranch2 = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise((resolve) => { resolveCancelPromise = resolve; }); function forwardReaderError(thisReader) { uponRejection(thisReader._closedPromise, (r6) => { if (thisReader !== reader) { return null; } ReadableByteStreamControllerError(branch1._readableStreamController, r6); ReadableByteStreamControllerError(branch2._readableStreamController, r6); if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } return null; }); } function pullWithDefaultReader() { if (IsReadableStreamBYOBReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamDefaultReader(stream); forwardReaderError(reader); } const readRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const chunk1 = chunk; let chunk2 = chunk; if (!canceled1 && !canceled2) { try { chunk2 = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } } if (!canceled1) { ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableByteStreamControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableByteStreamControllerClose(branch2._readableStreamController); } if (branch1._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); } if (branch2._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); } if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); } function pullWithBYOBReader(view5, forBranch2) { if (IsReadableStreamDefaultReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamBYOBReader(stream); forwardReaderError(reader); } const byobBranch = forBranch2 ? branch2 : branch1; const otherBranch = forBranch2 ? branch1 : branch2; const readIntoRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!otherCanceled) { let clonedChunk; try { clonedChunk = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); } else if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: (chunk) => { reading = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!byobCanceled) { ReadableByteStreamControllerClose(byobBranch._readableStreamController); } if (!otherCanceled) { ReadableByteStreamControllerClose(otherBranch._readableStreamController); } if (chunk !== void 0) { if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); } } if (!byobCanceled || !otherCanceled) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamBYOBReaderRead(reader, view5, 1, readIntoRequest); } function pull1Algorithm() { if (reading) { readAgainForBranch1 = true; return promiseResolvedWith(void 0); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, false); } return promiseResolvedWith(void 0); } function pull2Algorithm() { if (reading) { readAgainForBranch2 = true; return promiseResolvedWith(void 0); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, true); } return promiseResolvedWith(void 0); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { return; } branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); forwardReaderError(reader); return [branch1, branch2]; } function isReadableStreamLike(stream) { return typeIsObject(stream) && typeof stream.getReader !== "undefined"; } function ReadableStreamFrom(source) { if (isReadableStreamLike(source)) { return ReadableStreamFromDefaultReader(source.getReader()); } return ReadableStreamFromIterable(source); } function ReadableStreamFromIterable(asyncIterable) { let stream; const iteratorRecord = GetIterator(asyncIterable, "async"); const startAlgorithm = noop2; function pullAlgorithm() { let nextResult; try { nextResult = IteratorNext(iteratorRecord); } catch (e6) { return promiseRejectedWith(e6); } const nextPromise = promiseResolvedWith(nextResult); return transformPromiseWith(nextPromise, (iterResult) => { if (!typeIsObject(iterResult)) { throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object"); } const done = IteratorComplete(iterResult); if (done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = IteratorValue(iterResult); ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { const iterator = iteratorRecord.iterator; let returnMethod; try { returnMethod = GetMethod(iterator, "return"); } catch (e6) { return promiseRejectedWith(e6); } if (returnMethod === void 0) { return promiseResolvedWith(void 0); } let returnResult; try { returnResult = reflectCall(returnMethod, iterator, [reason]); } catch (e6) { return promiseRejectedWith(e6); } const returnPromise = promiseResolvedWith(returnResult); return transformPromiseWith(returnPromise, (iterResult) => { if (!typeIsObject(iterResult)) { throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object"); } return void 0; }); } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function ReadableStreamFromDefaultReader(reader) { let stream; const startAlgorithm = noop2; function pullAlgorithm() { let readPromise; try { readPromise = reader.read(); } catch (e6) { return promiseRejectedWith(e6); } return transformPromiseWith(readPromise, (readResult) => { if (!typeIsObject(readResult)) { throw new TypeError("The promise returned by the reader.read() method must fulfill with an object"); } if (readResult.done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = readResult.value; ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { try { return promiseResolvedWith(reader.cancel(reason)); } catch (e6) { return promiseRejectedWith(e6); } } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function convertUnderlyingDefaultOrByteSource(source, context) { assertDictionary(source, context); const original = source; const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; const cancel = original === null || original === void 0 ? void 0 : original.cancel; const pull = original === null || original === void 0 ? void 0 : original.pull; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; return { autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`) }; } function convertUnderlyingSourceCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSourcePullCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertUnderlyingSourceStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertReadableStreamType(type, context) { type = `${type}`; if (type !== "bytes") { throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); } return type; } function convertIteratorOptions(options, context) { assertDictionary(options, context); const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; return { preventCancel: Boolean(preventCancel) }; } function convertPipeOptions(options, context) { assertDictionary(options, context); const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; const signal = options === null || options === void 0 ? void 0 : options.signal; if (signal !== void 0) { assertAbortSignal(signal, `${context} has member 'signal' that`); } return { preventAbort: Boolean(preventAbort), preventCancel: Boolean(preventCancel), preventClose: Boolean(preventClose), signal }; } function assertAbortSignal(signal, context) { if (!isAbortSignal2(signal)) { throw new TypeError(`${context} is not an AbortSignal.`); } } function convertReadableWritablePair(pair, context) { assertDictionary(pair, context); const readable = pair === null || pair === void 0 ? void 0 : pair.readable; assertRequiredField(readable, "readable", "ReadableWritablePair"); assertReadableStream(readable, `${context} has member 'readable' that`); const writable = pair === null || pair === void 0 ? void 0 : pair.writable; assertRequiredField(writable, "writable", "ReadableWritablePair"); assertWritableStream(writable, `${context} has member 'writable' that`); return { readable, writable }; } class ReadableStream2 { constructor(rawUnderlyingSource = {}, rawStrategy = {}) { if (rawUnderlyingSource === void 0) { rawUnderlyingSource = null; } else { assertObject(rawUnderlyingSource, "First parameter"); } const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); InitializeReadableStream(this); if (underlyingSource.type === "bytes") { if (strategy.size !== void 0) { throw new RangeError("The strategy for a byte stream cannot have a size function"); } const highWaterMark = ExtractHighWaterMark(strategy, 0); SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); } else { const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); } } /** * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. */ get locked() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("locked"); } return IsReadableStreamLocked(this); } /** * Cancels the stream, signaling a loss of interest in the stream by a consumer. * * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} * method, which might or might not use it. */ cancel(reason = void 0) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1("cancel")); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); } return ReadableStreamCancel(this, reason); } getReader(rawOptions = void 0) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("getReader"); } const options = convertReaderOptions(rawOptions, "First parameter"); if (options.mode === void 0) { return AcquireReadableStreamDefaultReader(this); } return AcquireReadableStreamBYOBReader(this); } pipeThrough(rawTransform, rawOptions = {}) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("pipeThrough"); } assertRequiredArgument(rawTransform, 1, "pipeThrough"); const transform = convertReadableWritablePair(rawTransform, "First parameter"); const options = convertPipeOptions(rawOptions, "Second parameter"); if (IsReadableStreamLocked(this)) { throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); } if (IsWritableStreamLocked(transform.writable)) { throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); } const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); setPromiseIsHandledToTrue(promise); return transform.readable; } pipeTo(destination, rawOptions = {}) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); } if (destination === void 0) { return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); } if (!IsWritableStream(destination)) { return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); } let options; try { options = convertPipeOptions(rawOptions, "Second parameter"); } catch (e6) { return promiseRejectedWith(e6); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); } if (IsWritableStreamLocked(destination)) { return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); } return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); } /** * Tees this readable stream, returning a two-element array containing the two resulting branches as * new {@link ReadableStream} instances. * * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be * propagated to the stream's underlying source. * * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, * this could allow interference between the two branches. */ tee() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("tee"); } const branches = ReadableStreamTee(this); return CreateArrayFromList(branches); } values(rawOptions = void 0) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("values"); } const options = convertIteratorOptions(rawOptions, "First parameter"); return AcquireReadableStreamAsyncIterator(this, options.preventCancel); } [SymbolAsyncIterator](options) { return this.values(options); } /** * Creates a new ReadableStream wrapping the provided iterable or async iterable. * * This can be used to adapt various kinds of objects into a readable stream, * such as an array, an async generator, or a Node.js readable stream. */ static from(asyncIterable) { return ReadableStreamFrom(asyncIterable); } } Object.defineProperties(ReadableStream2, { from: { enumerable: true } }); Object.defineProperties(ReadableStream2.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(ReadableStream2.from, "from"); setFunctionName(ReadableStream2.prototype.cancel, "cancel"); setFunctionName(ReadableStream2.prototype.getReader, "getReader"); setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough"); setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo"); setFunctionName(ReadableStream2.prototype.tee, "tee"); setFunctionName(ReadableStream2.prototype.values, "values"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, { value: "ReadableStream", configurable: true }); } Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, { value: ReadableStream2.prototype.values, writable: true, configurable: true }); function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(ReadableStream2.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableStreamDefaultController.prototype); SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { const stream = Object.create(ReadableStream2.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableByteStreamController.prototype); SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); return stream; } function InitializeReadableStream(stream) { stream._state = "readable"; stream._reader = void 0; stream._storedError = void 0; stream._disturbed = false; } function IsReadableStream(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_readableStreamController")) { return false; } return x5 instanceof ReadableStream2; } function IsReadableStreamLocked(stream) { if (stream._reader === void 0) { return false; } return true; } function ReadableStreamCancel(stream, reason) { stream._disturbed = true; if (stream._state === "closed") { return promiseResolvedWith(void 0); } if (stream._state === "errored") { return promiseRejectedWith(stream._storedError); } ReadableStreamClose(stream); const reader = stream._reader; if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach((readIntoRequest) => { readIntoRequest._closeSteps(void 0); }); } const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); return transformPromiseWith(sourceCancelPromise, noop2); } function ReadableStreamClose(stream) { stream._state = "closed"; const reader = stream._reader; if (reader === void 0) { return; } defaultReaderClosedPromiseResolve(reader); if (IsReadableStreamDefaultReader(reader)) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach((readRequest) => { readRequest._closeSteps(); }); } } function ReadableStreamError(stream, e6) { stream._state = "errored"; stream._storedError = e6; const reader = stream._reader; if (reader === void 0) { return; } defaultReaderClosedPromiseReject(reader, e6); if (IsReadableStreamDefaultReader(reader)) { ReadableStreamDefaultReaderErrorReadRequests(reader, e6); } else { ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6); } } function streamBrandCheckException$1(name) { return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); } function convertQueuingStrategyInit(init2, context) { assertDictionary(init2, context); const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark; assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); return { highWaterMark: convertUnrestrictedDouble(highWaterMark) }; } const byteLengthSizeFunction = (chunk) => { return chunk.byteLength; }; setFunctionName(byteLengthSizeFunction, "size"); class ByteLengthQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); options = convertQueuingStrategyInit(options, "First parameter"); this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException("highWaterMark"); } return this._byteLengthQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by returning the value of its `byteLength` property. */ get size() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException("size"); } return byteLengthSizeFunction; } } Object.defineProperties(ByteLengthQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { value: "ByteLengthQueuingStrategy", configurable: true }); } function byteLengthBrandCheckException(name) { return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); } function IsByteLengthQueuingStrategy(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_byteLengthQueuingStrategyHighWaterMark")) { return false; } return x5 instanceof ByteLengthQueuingStrategy; } const countSizeFunction = () => { return 1; }; setFunctionName(countSizeFunction, "size"); class CountQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, "CountQueuingStrategy"); options = convertQueuingStrategyInit(options, "First parameter"); this._countQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException("highWaterMark"); } return this._countQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by always returning 1. * This ensures that the total queue size is a count of the number of chunks in the queue. */ get size() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException("size"); } return countSizeFunction; } } Object.defineProperties(CountQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { value: "CountQueuingStrategy", configurable: true }); } function countBrandCheckException(name) { return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); } function IsCountQueuingStrategy(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_countQueuingStrategyHighWaterMark")) { return false; } return x5 instanceof CountQueuingStrategy; } function convertTransformer(original, context) { assertDictionary(original, context); const cancel = original === null || original === void 0 ? void 0 : original.cancel; const flush2 = original === null || original === void 0 ? void 0 : original.flush; const readableType = original === null || original === void 0 ? void 0 : original.readableType; const start = original === null || original === void 0 ? void 0 : original.start; const transform = original === null || original === void 0 ? void 0 : original.transform; const writableType = original === null || original === void 0 ? void 0 : original.writableType; return { cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), flush: flush2 === void 0 ? void 0 : convertTransformerFlushCallback(flush2, original, `${context} has member 'flush' that`), readableType, start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), writableType }; } function convertTransformerFlushCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertTransformerStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertTransformerTransformCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } function convertTransformerCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } class TransformStream2 { constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { if (rawTransformer === void 0) { rawTransformer = null; } const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); const transformer = convertTransformer(rawTransformer, "First parameter"); if (transformer.readableType !== void 0) { throw new RangeError("Invalid readableType specified"); } if (transformer.writableType !== void 0) { throw new RangeError("Invalid writableType specified"); } const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); let startPromise_resolve; const startPromise = newPromise((resolve) => { startPromise_resolve = resolve; }); InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); if (transformer.start !== void 0) { startPromise_resolve(transformer.start(this._transformStreamController)); } else { startPromise_resolve(void 0); } } /** * The readable side of the transform stream. */ get readable() { if (!IsTransformStream(this)) { throw streamBrandCheckException("readable"); } return this._readable; } /** * The writable side of the transform stream. */ get writable() { if (!IsTransformStream(this)) { throw streamBrandCheckException("writable"); } return this._writable; } } Object.defineProperties(TransformStream2.prototype, { readable: { enumerable: true }, writable: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, { value: "TransformStream", configurable: true }); } function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { function startAlgorithm() { return startPromise; } function writeAlgorithm(chunk) { return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); } function abortAlgorithm(reason) { return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); } function closeAlgorithm() { return TransformStreamDefaultSinkCloseAlgorithm(stream); } stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); function pullAlgorithm() { return TransformStreamDefaultSourcePullAlgorithm(stream); } function cancelAlgorithm(reason) { return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); } stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); stream._backpressure = void 0; stream._backpressureChangePromise = void 0; stream._backpressureChangePromise_resolve = void 0; TransformStreamSetBackpressure(stream, true); stream._transformStreamController = void 0; } function IsTransformStream(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_transformStreamController")) { return false; } return x5 instanceof TransformStream2; } function TransformStreamError(stream, e6) { ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e6); TransformStreamErrorWritableAndUnblockWrite(stream, e6); } function TransformStreamErrorWritableAndUnblockWrite(stream, e6) { TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e6); TransformStreamUnblockWrite(stream); } function TransformStreamUnblockWrite(stream) { if (stream._backpressure) { TransformStreamSetBackpressure(stream, false); } } function TransformStreamSetBackpressure(stream, backpressure) { if (stream._backpressureChangePromise !== void 0) { stream._backpressureChangePromise_resolve(); } stream._backpressureChangePromise = newPromise((resolve) => { stream._backpressureChangePromise_resolve = resolve; }); stream._backpressure = backpressure; } class TransformStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. */ get desiredSize() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("desiredSize"); } const readableController = this._controlledTransformStream._readable._readableStreamController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } enqueue(chunk = void 0) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("enqueue"); } TransformStreamDefaultControllerEnqueue(this, chunk); } /** * Errors both the readable side and the writable side of the controlled transform stream, making all future * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. */ error(reason = void 0) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("error"); } TransformStreamDefaultControllerError(this, reason); } /** * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the * transformer only needs to consume a portion of the chunks written to the writable side. */ terminate() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("terminate"); } TransformStreamDefaultControllerTerminate(this); } } Object.defineProperties(TransformStreamDefaultController.prototype, { enqueue: { enumerable: true }, error: { enumerable: true }, terminate: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue"); setFunctionName(TransformStreamDefaultController.prototype.error, "error"); setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { value: "TransformStreamDefaultController", configurable: true }); } function IsTransformStreamDefaultController(x5) { if (!typeIsObject(x5)) { return false; } if (!Object.prototype.hasOwnProperty.call(x5, "_controlledTransformStream")) { return false; } return x5 instanceof TransformStreamDefaultController; } function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { controller._controlledTransformStream = stream; stream._transformStreamController = controller; controller._transformAlgorithm = transformAlgorithm; controller._flushAlgorithm = flushAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._finishPromise = void 0; controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { const controller = Object.create(TransformStreamDefaultController.prototype); let transformAlgorithm; let flushAlgorithm; let cancelAlgorithm; if (transformer.transform !== void 0) { transformAlgorithm = (chunk) => transformer.transform(chunk, controller); } else { transformAlgorithm = (chunk) => { try { TransformStreamDefaultControllerEnqueue(controller, chunk); return promiseResolvedWith(void 0); } catch (transformResultE) { return promiseRejectedWith(transformResultE); } }; } if (transformer.flush !== void 0) { flushAlgorithm = () => transformer.flush(controller); } else { flushAlgorithm = () => promiseResolvedWith(void 0); } if (transformer.cancel !== void 0) { cancelAlgorithm = (reason) => transformer.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); } function TransformStreamDefaultControllerClearAlgorithms(controller) { controller._transformAlgorithm = void 0; controller._flushAlgorithm = void 0; controller._cancelAlgorithm = void 0; } function TransformStreamDefaultControllerEnqueue(controller, chunk) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { throw new TypeError("Readable side is not in a state that permits enqueue"); } try { ReadableStreamDefaultControllerEnqueue(readableController, chunk); } catch (e6) { TransformStreamErrorWritableAndUnblockWrite(stream, e6); throw stream._readable._storedError; } const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); if (backpressure !== stream._backpressure) { TransformStreamSetBackpressure(stream, true); } } function TransformStreamDefaultControllerError(controller, e6) { TransformStreamError(controller._controlledTransformStream, e6); } function TransformStreamDefaultControllerPerformTransform(controller, chunk) { const transformPromise = controller._transformAlgorithm(chunk); return transformPromiseWith(transformPromise, void 0, (r6) => { TransformStreamError(controller._controlledTransformStream, r6); throw r6; }); } function TransformStreamDefaultControllerTerminate(controller) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; ReadableStreamDefaultControllerClose(readableController); const error2 = new TypeError("TransformStream terminated"); TransformStreamErrorWritableAndUnblockWrite(stream, error2); } function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { const controller = stream._transformStreamController; if (stream._backpressure) { const backpressureChangePromise = stream._backpressureChangePromise; return transformPromiseWith(backpressureChangePromise, () => { const writable = stream._writable; const state2 = writable._state; if (state2 === "erroring") { throw writable._storedError; } return TransformStreamDefaultControllerPerformTransform(controller, chunk); }); } return TransformStreamDefaultControllerPerformTransform(controller, chunk); } function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const readable = stream._readable; controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (readable._state === "errored") { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerError(readable._readableStreamController, reason); defaultControllerFinishPromiseResolve(controller); } return null; }, (r6) => { ReadableStreamDefaultControllerError(readable._readableStreamController, r6); defaultControllerFinishPromiseReject(controller, r6); return null; }); return controller._finishPromise; } function TransformStreamDefaultSinkCloseAlgorithm(stream) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const readable = stream._readable; controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const flushPromise = controller._flushAlgorithm(); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(flushPromise, () => { if (readable._state === "errored") { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerClose(readable._readableStreamController); defaultControllerFinishPromiseResolve(controller); } return null; }, (r6) => { ReadableStreamDefaultControllerError(readable._readableStreamController, r6); defaultControllerFinishPromiseReject(controller, r6); return null; }); return controller._finishPromise; } function TransformStreamDefaultSourcePullAlgorithm(stream) { TransformStreamSetBackpressure(stream, false); return stream._backpressureChangePromise; } function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const writable = stream._writable; controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (writable._state === "errored") { defaultControllerFinishPromiseReject(controller, writable._storedError); } else { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseResolve(controller); } return null; }, (r6) => { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r6); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseReject(controller, r6); return null; }); return controller._finishPromise; } function defaultControllerBrandCheckException(name) { return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } function defaultControllerFinishPromiseResolve(controller) { if (controller._finishPromise_resolve === void 0) { return; } controller._finishPromise_resolve(); controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function defaultControllerFinishPromiseReject(controller, reason) { if (controller._finishPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(controller._finishPromise); controller._finishPromise_reject(reason); controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function streamBrandCheckException(name) { return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); } exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; exports3.CountQueuingStrategy = CountQueuingStrategy; exports3.ReadableByteStreamController = ReadableByteStreamController; exports3.ReadableStream = ReadableStream2; exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader; exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; exports3.ReadableStreamDefaultController = ReadableStreamDefaultController; exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader; exports3.TransformStream = TransformStream2; exports3.TransformStreamDefaultController = TransformStreamDefaultController; exports3.WritableStream = WritableStream; exports3.WritableStreamDefaultController = WritableStreamDefaultController; exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter; }); } }); // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs var require_streams = __commonJS({ "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() { "use strict"; var POOL_SIZE2 = 65536; if (!globalThis.ReadableStream) { try { const process4 = require("process"); const { emitWarning } = process4; try { process4.emitWarning = () => { }; Object.assign(globalThis, require("stream/web")); process4.emitWarning = emitWarning; } catch (error2) { process4.emitWarning = emitWarning; throw error2; } } catch (error2) { Object.assign(globalThis, require_ponyfill_es2018()); } } try { const { Blob: Blob3 } = require("buffer"); if (Blob3 && !Blob3.prototype.stream) { Blob3.prototype.stream = function name(params) { let position = 0; const blob = this; return new ReadableStream({ type: "bytes", async pull(ctrl) { const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2)); const buffer = await chunk.arrayBuffer(); position += buffer.byteLength; ctrl.enqueue(new Uint8Array(buffer)); if (position === blob.size) { ctrl.close(); } } }); }; } } catch (error2) { } } }); // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js async function* toIterator(parts, clone2 = true) { for (const part of parts) { if ("stream" in part) { yield* ( /** @type {AsyncIterableIterator<Uint8Array>} */ part.stream() ); } else if (ArrayBuffer.isView(part)) { if (clone2) { let position = part.byteOffset; const end = part.byteOffset + part.byteLength; while (position !== end) { const size = Math.min(end - position, POOL_SIZE); const chunk = part.buffer.slice(position, position + size); position += chunk.byteLength; yield new Uint8Array(chunk); } } else { yield part; } } else { let position = 0, b5 = ( /** @type {Blob} */ part ); while (position !== b5.size) { const chunk = b5.slice(position, Math.min(b5.size, position + POOL_SIZE)); const buffer = await chunk.arrayBuffer(); position += buffer.byteLength; yield new Uint8Array(buffer); } } } } var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a11, _Blob, Blob2, fetch_blob_default; var init_fetch_blob = __esm({ "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js"() { "use strict"; import_streams = __toESM(require_streams(), 1); POOL_SIZE = 65536; _Blob = (_a11 = class { /** * The Blob() constructor returns a new Blob object. The content * of the blob consists of the concatenation of the values given * in the parameter array. * * @param {*} blobParts * @param {{ type?: string, endings?: string }} [options] */ constructor(blobParts = [], options = {}) { /** @type {Array.<(Blob|Uint8Array)>} */ __privateAdd(this, _parts, []); __privateAdd(this, _type, ""); __privateAdd(this, _size, 0); __privateAdd(this, _endings, "transparent"); if (typeof blobParts !== "object" || blobParts === null) { throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); } if (typeof blobParts[Symbol.iterator] !== "function") { throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); } if (typeof options !== "object" && typeof options !== "function") { throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); } if (options === null) options = {}; const encoder = new TextEncoder(); for (const element of blobParts) { let part; if (ArrayBuffer.isView(element)) { part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); } else if (element instanceof ArrayBuffer) { part = new Uint8Array(element.slice(0)); } else if (element instanceof _a11) { part = element; } else { part = encoder.encode(`${element}`); } __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size)); __privateGet(this, _parts).push(part); } __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`); const type = options.type === void 0 ? "" : String(options.type); __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : ""); } /** * The Blob interface's size property returns the * size of the Blob in bytes. */ get size() { return __privateGet(this, _size); } /** * The type property of a Blob object returns the MIME type of the file. */ get type() { return __privateGet(this, _type); } /** * The text() method in the Blob interface returns a Promise * that resolves with a string containing the contents of * the blob, interpreted as UTF-8. * * @return {Promise<string>} */ async text() { const decoder = new TextDecoder(); let str = ""; for await (const part of toIterator(__privateGet(this, _parts), false)) { str += decoder.decode(part, { stream: true }); } str += decoder.decode(); return str; } /** * The arrayBuffer() method in the Blob interface returns a * Promise that resolves with the contents of the blob as * binary data contained in an ArrayBuffer. * * @return {Promise<ArrayBuffer>} */ async arrayBuffer() { const data = new Uint8Array(this.size); let offset = 0; for await (const chunk of toIterator(__privateGet(this, _parts), false)) { data.set(chunk, offset); offset += chunk.length; } return data.buffer; } stream() { const it = toIterator(__privateGet(this, _parts), true); return new globalThis.ReadableStream({ // @ts-ignore type: "bytes", async pull(ctrl) { const chunk = await it.next(); chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); }, async cancel() { await it.return(); } }); } /** * The Blob interface's slice() method creates and returns a * new Blob object which contains data from a subset of the * blob on which it's called. * * @param {number} [start] * @param {number} [end] * @param {string} [type] */ slice(start = 0, end = this.size, type = "") { const { size } = this; let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); const span = Math.max(relativeEnd - relativeStart, 0); const parts = __privateGet(this, _parts); const blobParts = []; let added = 0; for (const part of parts) { if (added >= span) { break; } const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; if (relativeStart && size2 <= relativeStart) { relativeStart -= size2; relativeEnd -= size2; } else { let chunk; if (ArrayBuffer.isView(part)) { chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); added += chunk.byteLength; } else { chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); added += chunk.size; } relativeEnd -= size2; blobParts.push(chunk); relativeStart = 0; } } const blob = new _a11([], { type: String(type).toLowerCase() }); __privateSet(blob, _size, span); __privateSet(blob, _parts, blobParts); return blob; } get [Symbol.toStringTag]() { return "Blob"; } static [Symbol.hasInstance](object) { return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); } }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a11); Object.defineProperties(_Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, slice: { enumerable: true } }); Blob2 = _Blob; fetch_blob_default = Blob2; } }); // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js var _lastModified, _name, _a12, _File, File2, file_default; var init_file = __esm({ "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js"() { "use strict"; init_fetch_blob(); _File = (_a12 = class extends fetch_blob_default { /** * @param {*[]} fileBits * @param {string} fileName * @param {{lastModified?: number, type?: string}} options */ // @ts-ignore constructor(fileBits, fileName, options = {}) { if (arguments.length < 2) { throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); } super(fileBits, options); __privateAdd(this, _lastModified, 0); __privateAdd(this, _name, ""); if (options === null) options = {}; const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified); if (!Number.isNaN(lastModified)) { __privateSet(this, _lastModified, lastModified); } __privateSet(this, _name, String(fileName)); } get name() { return __privateGet(this, _name); } get lastModified() { return __privateGet(this, _lastModified); } get [Symbol.toStringTag]() { return "File"; } static [Symbol.hasInstance](object) { return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); } }, _lastModified = new WeakMap(), _name = new WeakMap(), _a12); File2 = _File; file_default = File2; } }); // ../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js function formDataToBlob(F3, B2 = fetch_blob_default) { var b5 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c5 = [], p5 = `--${b5}\r Content-Disposition: form-data; name="`; F3.forEach((v6, n5) => typeof v6 == "string" ? c5.push(p5 + e(n5) + `"\r \r ${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r `) : c5.push(p5 + e(n5) + `"; filename="${e(v6.name, 1)}"\r Content-Type: ${v6.type || "application/octet-stream"}\r \r `, v6, "\r\n")); c5.push(`--${b5}--`); return new B2(c5, { type: "multipart/form-data; boundary=" + b5 }); } var t, i, h, r, m, f, e, x, _d, _a13, FormData; var init_esm_min = __esm({ "../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js"() { "use strict"; init_fetch_blob(); init_file(); ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol); r = Math.random; m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","); f = (a5, b5, c5) => (a5 += "", /^(Blob|File)$/.test(b5 && b5[t]) ? [(c5 = c5 !== void 0 ? c5 + "" : b5[t] == "File" ? b5.name : "blob", a5), b5.name !== c5 || b5[t] == "blob" ? new file_default([b5], c5, b5) : b5] : [a5, b5 + ""]); e = (c5, f7) => (f7 ? c5 : c5.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); x = (n5, a5, e6) => { if (a5.length < e6) { throw new TypeError(`Failed to execute '${n5}' on 'FormData': ${e6} arguments required, but only ${a5.length} present.`); } }; FormData = (_a13 = class { constructor(...a5) { __privateAdd(this, _d, []); if (a5.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); } get [t]() { return "FormData"; } [i]() { return this.entries(); } static [h](o5) { return o5 && typeof o5 === "object" && o5[t] === "FormData" && !m.some((m6) => typeof o5[m6] != "function"); } append(...a5) { x("append", arguments, 2); __privateGet(this, _d).push(f(...a5)); } delete(a5) { x("delete", arguments, 1); a5 += ""; __privateSet(this, _d, __privateGet(this, _d).filter(([b5]) => b5 !== a5)); } get(a5) { x("get", arguments, 1); a5 += ""; for (var b5 = __privateGet(this, _d), l5 = b5.length, c5 = 0; c5 < l5; c5++) if (b5[c5][0] === a5) return b5[c5][1]; return null; } getAll(a5, b5) { x("getAll", arguments, 1); b5 = []; a5 += ""; __privateGet(this, _d).forEach((c5) => c5[0] === a5 && b5.push(c5[1])); return b5; } has(a5) { x("has", arguments, 1); a5 += ""; return __privateGet(this, _d).some((b5) => b5[0] === a5); } forEach(a5, b5) { x("forEach", arguments, 1); for (var [c5, d5] of this) a5.call(b5, d5, c5, this); } set(...a5) { x("set", arguments, 2); var b5 = [], c5 = true; a5 = f(...a5); __privateGet(this, _d).forEach((d5) => { d5[0] === a5[0] ? c5 && (c5 = !b5.push(a5)) : b5.push(d5); }); c5 && b5.push(a5); __privateSet(this, _d, b5); } *entries() { yield* __privateGet(this, _d); } *keys() { for (var [a5] of this) yield a5; } *values() { for (var [, a5] of this) yield a5; } }, _d = new WeakMap(), _a13); } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js var FetchBaseError; var init_base = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js"() { "use strict"; FetchBaseError = class extends Error { constructor(message, type) { super(message); Error.captureStackTrace(this, this.constructor); this.type = type; } get name() { return this.constructor.name; } get [Symbol.toStringTag]() { return this.constructor.name; } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js var FetchError; var init_fetch_error = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js"() { "use strict"; init_base(); FetchError = class extends FetchBaseError { /** * @param {string} message - Error message for human * @param {string} [type] - Error type for machine * @param {SystemError} [systemError] - For Node.js system error */ constructor(message, type, systemError) { super(message, type); if (systemError) { this.code = this.errno = systemError.code; this.erroredSysCall = systemError.syscall; } } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js var NAME, isURLSearchParameters, isBlob, isAbortSignal, isDomainOrSubdomain, isSameProtocol; var init_is = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js"() { "use strict"; NAME = Symbol.toStringTag; isURLSearchParameters = (object) => { return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; }; isBlob = (object) => { return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); }; isAbortSignal = (object) => { return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); }; isDomainOrSubdomain = (destination, original) => { const orig = new URL(original).hostname; const dest = new URL(destination).hostname; return orig === dest || orig.endsWith(`.${dest}`); }; isSameProtocol = (destination, original) => { const orig = new URL(original).protocol; const dest = new URL(destination).protocol; return orig === dest; }; } }); // ../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js var require_node_domexception = __commonJS({ "../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js"(exports2, module2) { "use strict"; if (!globalThis.DOMException) { try { const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer(); port.postMessage(ab, [ab, ab]); } catch (err2) { err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor); } } module2.exports = globalThis.DOMException; } }); // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js var import_node_fs, import_node_path2, import_node_domexception, stat; var init_from = __esm({ "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js"() { "use strict"; import_node_fs = require("fs"); import_node_path2 = require("path"); import_node_domexception = __toESM(require_node_domexception(), 1); init_file(); init_fetch_blob(); ({ stat } = import_node_fs.promises); } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js var multipart_parser_exports = {}; __export(multipart_parser_exports, { toFormData: () => toFormData }); function _fileName(headerValue) { const m6 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); if (!m6) { return; } const match2 = m6[2] || m6[3] || ""; let filename = match2.slice(match2.lastIndexOf("\\") + 1); filename = filename.replace(/%22/g, '"'); filename = filename.replace(/&#(\d{4});/g, (m7, code) => { return String.fromCharCode(code); }); return filename; } async function toFormData(Body2, ct) { if (!/multipart/i.test(ct)) { throw new TypeError("Failed to fetch"); } const m6 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); if (!m6) { throw new TypeError("no or bad content-type header, no multipart boundary"); } const parser = new MultipartParser(m6[1] || m6[2]); let headerField; let headerValue; let entryValue; let entryName; let contentType; let filename; const entryChunks = []; const formData = new FormData(); const onPartData = (ui8a) => { entryValue += decoder.decode(ui8a, { stream: true }); }; const appendToFile = (ui8a) => { entryChunks.push(ui8a); }; const appendFileToFormData = () => { const file = new file_default(entryChunks, filename, { type: contentType }); formData.append(entryName, file); }; const appendEntryToFormData = () => { formData.append(entryName, entryValue); }; const decoder = new TextDecoder("utf-8"); decoder.decode(); parser.onPartBegin = function() { parser.onPartData = onPartData; parser.onPartEnd = appendEntryToFormData; headerField = ""; headerValue = ""; entryValue = ""; entryName = ""; contentType = ""; filename = null; entryChunks.length = 0; }; parser.onHeaderField = function(ui8a) { headerField += decoder.decode(ui8a, { stream: true }); }; parser.onHeaderValue = function(ui8a) { headerValue += decoder.decode(ui8a, { stream: true }); }; parser.onHeaderEnd = function() { headerValue += decoder.decode(); headerField = headerField.toLowerCase(); if (headerField === "content-disposition") { const m7 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); if (m7) { entryName = m7[2] || m7[3] || ""; } filename = _fileName(headerValue); if (filename) { parser.onPartData = appendToFile; parser.onPartEnd = appendFileToFormData; } } else if (headerField === "content-type") { contentType = headerValue; } headerValue = ""; headerField = ""; }; for await (const chunk of Body2) { parser.write(chunk); } parser.end(); return formData; } var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser; var init_multipart_parser = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"() { "use strict"; init_from(); init_esm_min(); s = 0; S = { START_BOUNDARY: s++, HEADER_FIELD_START: s++, HEADER_FIELD: s++, HEADER_VALUE_START: s++, HEADER_VALUE: s++, HEADER_VALUE_ALMOST_DONE: s++, HEADERS_ALMOST_DONE: s++, PART_DATA_START: s++, PART_DATA: s++, END: s++ }; f2 = 1; F = { PART_BOUNDARY: f2, LAST_BOUNDARY: f2 *= 2 }; LF = 10; CR = 13; SPACE = 32; HYPHEN = 45; COLON = 58; A = 97; Z = 122; lower = (c5) => c5 | 32; noop = () => { }; MultipartParser = class { /** * @param {string} boundary */ constructor(boundary) { this.index = 0; this.flags = 0; this.onHeaderEnd = noop; this.onHeaderField = noop; this.onHeadersEnd = noop; this.onHeaderValue = noop; this.onPartBegin = noop; this.onPartData = noop; this.onPartEnd = noop; this.boundaryChars = {}; boundary = "\r\n--" + boundary; const ui8a = new Uint8Array(boundary.length); for (let i6 = 0; i6 < boundary.length; i6++) { ui8a[i6] = boundary.charCodeAt(i6); this.boundaryChars[ui8a[i6]] = true; } this.boundary = ui8a; this.lookbehind = new Uint8Array(this.boundary.length + 8); this.state = S.START_BOUNDARY; } /** * @param {Uint8Array} data */ write(data) { let i6 = 0; const length_ = data.length; let previousIndex = this.index; let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this; const boundaryLength = this.boundary.length; const boundaryEnd = boundaryLength - 1; const bufferLength = data.length; let c5; let cl; const mark = (name) => { this[name + "Mark"] = i6; }; const clear = (name) => { delete this[name + "Mark"]; }; const callback = (callbackSymbol, start, end, ui8a) => { if (start === void 0 || start !== end) { this[callbackSymbol](ui8a && ui8a.subarray(start, end)); } }; const dataCallback = (name, clear2) => { const markSymbol = name + "Mark"; if (!(markSymbol in this)) { return; } if (clear2) { callback(name, this[markSymbol], i6, data); delete this[markSymbol]; } else { callback(name, this[markSymbol], data.length, data); this[markSymbol] = 0; } }; for (i6 = 0; i6 < length_; i6++) { c5 = data[i6]; switch (state2) { case S.START_BOUNDARY: if (index6 === boundary.length - 2) { if (c5 === HYPHEN) { flags |= F.LAST_BOUNDARY; } else if (c5 !== CR) { return; } index6++; break; } else if (index6 - 1 === boundary.length - 2) { if (flags & F.LAST_BOUNDARY && c5 === HYPHEN) { state2 = S.END; flags = 0; } else if (!(flags & F.LAST_BOUNDARY) && c5 === LF) { index6 = 0; callback("onPartBegin"); state2 = S.HEADER_FIELD_START; } else { return; } break; } if (c5 !== boundary[index6 + 2]) { index6 = -2; } if (c5 === boundary[index6 + 2]) { index6++; } break; case S.HEADER_FIELD_START: state2 = S.HEADER_FIELD; mark("onHeaderField"); index6 = 0; // falls through case S.HEADER_FIELD: if (c5 === CR) { clear("onHeaderField"); state2 = S.HEADERS_ALMOST_DONE; break; } index6++; if (c5 === HYPHEN) { break; } if (c5 === COLON) { if (index6 === 1) { return; } dataCallback("onHeaderField", true); state2 = S.HEADER_VALUE_START; break; } cl = lower(c5); if (cl < A || cl > Z) { return; } break; case S.HEADER_VALUE_START: if (c5 === SPACE) { break; } mark("onHeaderValue"); state2 = S.HEADER_VALUE; // falls through case S.HEADER_VALUE: if (c5 === CR) { dataCallback("onHeaderValue", true); callback("onHeaderEnd"); state2 = S.HEADER_VALUE_ALMOST_DONE; } break; case S.HEADER_VALUE_ALMOST_DONE: if (c5 !== LF) { return; } state2 = S.HEADER_FIELD_START; break; case S.HEADERS_ALMOST_DONE: if (c5 !== LF) { return; } callback("onHeadersEnd"); state2 = S.PART_DATA_START; break; case S.PART_DATA_START: state2 = S.PART_DATA; mark("onPartData"); // falls through case S.PART_DATA: previousIndex = index6; if (index6 === 0) { i6 += boundaryEnd; while (i6 < bufferLength && !(data[i6] in boundaryChars)) { i6 += boundaryLength; } i6 -= boundaryEnd; c5 = data[i6]; } if (index6 < boundary.length) { if (boundary[index6] === c5) { if (index6 === 0) { dataCallback("onPartData", true); } index6++; } else { index6 = 0; } } else if (index6 === boundary.length) { index6++; if (c5 === CR) { flags |= F.PART_BOUNDARY; } else if (c5 === HYPHEN) { flags |= F.LAST_BOUNDARY; } else { index6 = 0; } } else if (index6 - 1 === boundary.length) { if (flags & F.PART_BOUNDARY) { index6 = 0; if (c5 === LF) { flags &= ~F.PART_BOUNDARY; callback("onPartEnd"); callback("onPartBegin"); state2 = S.HEADER_FIELD_START; break; } } else if (flags & F.LAST_BOUNDARY) { if (c5 === HYPHEN) { callback("onPartEnd"); state2 = S.END; flags = 0; } else { index6 = 0; } } else { index6 = 0; } } if (index6 > 0) { lookbehind[index6 - 1] = c5; } else if (previousIndex > 0) { const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); callback("onPartData", 0, previousIndex, _lookbehind); previousIndex = 0; mark("onPartData"); i6--; } break; case S.END: break; default: throw new Error(`Unexpected state entered: ${state2}`); } } dataCallback("onHeaderField"); dataCallback("onHeaderValue"); dataCallback("onPartData"); this.index = index6; this.state = state2; this.flags = flags; } end() { if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { this.onPartEnd(); } else if (this.state !== S.END) { throw new Error("MultipartParser.end(): stream ended unexpectedly"); } } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js async function consumeBody(data) { if (data[INTERNALS].disturbed) { throw new TypeError(`body used already for: ${data.url}`); } data[INTERNALS].disturbed = true; if (data[INTERNALS].error) { throw data[INTERNALS].error; } const { body } = data; if (body === null) { return import_node_buffer.Buffer.alloc(0); } if (!(body instanceof import_node_stream.default)) { return import_node_buffer.Buffer.alloc(0); } const accum = []; let accumBytes = 0; try { for await (const chunk of body) { if (data.size > 0 && accumBytes + chunk.length > data.size) { const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); body.destroy(error2); throw error2; } accumBytes += chunk.length; accum.push(chunk); } } catch (error2) { const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2); throw error_; } if (body.readableEnded === true || body._readableState.ended === true) { try { if (accum.every((c5) => typeof c5 === "string")) { return import_node_buffer.Buffer.from(accum.join("")); } return import_node_buffer.Buffer.concat(accum, accumBytes); } catch (error2) { throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2); } } else { throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); } } var import_node_stream, import_node_util, import_node_buffer, pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream; var init_body2 = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() { "use strict"; import_node_stream = __toESM(require("stream"), 1); import_node_util = require("util"); import_node_buffer = require("buffer"); init_fetch_blob(); init_esm_min(); init_fetch_error(); init_base(); init_is(); pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline); INTERNALS = Symbol("Body internals"); Body = class { constructor(body, { size = 0 } = {}) { let boundary = null; if (body === null) { body = null; } else if (isURLSearchParameters(body)) { body = import_node_buffer.Buffer.from(body.toString()); } else if (isBlob(body)) { } else if (import_node_buffer.Buffer.isBuffer(body)) { } else if (import_node_util.types.isAnyArrayBuffer(body)) { body = import_node_buffer.Buffer.from(body); } else if (ArrayBuffer.isView(body)) { body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof import_node_stream.default) { } else if (body instanceof FormData) { body = formDataToBlob(body); boundary = body.type.split("=")[1]; } else { body = import_node_buffer.Buffer.from(String(body)); } let stream = body; if (import_node_buffer.Buffer.isBuffer(body)) { stream = import_node_stream.default.Readable.from(body); } else if (isBlob(body)) { stream = import_node_stream.default.Readable.from(body.stream()); } this[INTERNALS] = { body, stream, boundary, disturbed: false, error: null }; this.size = size; if (body instanceof import_node_stream.default) { body.on("error", (error_) => { const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); this[INTERNALS].error = error2; }); } } get body() { return this[INTERNALS].stream; } get bodyUsed() { return this[INTERNALS].disturbed; } /** * Decode response as ArrayBuffer * * @return Promise */ async arrayBuffer() { const { buffer, byteOffset, byteLength } = await consumeBody(this); return buffer.slice(byteOffset, byteOffset + byteLength); } async formData() { const ct = this.headers.get("content-type"); if (ct.startsWith("application/x-www-form-urlencoded")) { const formData = new FormData(); const parameters = new URLSearchParams(await this.text()); for (const [name, value] of parameters) { formData.append(name, value); } return formData; } const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); return toFormData2(this.body, ct); } /** * Return raw response as Blob * * @return Promise */ async blob() { const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; const buf = await this.arrayBuffer(); return new fetch_blob_default([buf], { type: ct }); } /** * Decode response as json * * @return Promise */ async json() { const text = await this.text(); return JSON.parse(text); } /** * Decode response as text * * @return Promise */ async text() { const buffer = await consumeBody(this); return new TextDecoder().decode(buffer); } /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody(this); } }; Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true }, data: { get: (0, import_node_util.deprecate)( () => { }, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)" ) } }); clone = (instance, highWaterMark) => { let p1; let p22; let { body } = instance[INTERNALS]; if (instance.bodyUsed) { throw new Error("cannot clone body after it is used"); } if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { p1 = new import_node_stream.PassThrough({ highWaterMark }); p22 = new import_node_stream.PassThrough({ highWaterMark }); body.pipe(p1); body.pipe(p22); instance[INTERNALS].stream = p1; body = p22; } return body; }; getNonSpecFormDataBoundary = (0, import_node_util.deprecate)( (body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167" ); extractContentType = (body, request2) => { if (body === null) { return null; } if (typeof body === "string") { return "text/plain;charset=UTF-8"; } if (isURLSearchParameters(body)) { return "application/x-www-form-urlencoded;charset=UTF-8"; } if (isBlob(body)) { return body.type || null; } if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { return null; } if (body instanceof FormData) { return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`; } if (body && typeof body.getBoundary === "function") { return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; } if (body instanceof import_node_stream.default) { return null; } return "text/plain;charset=UTF-8"; }; getTotalBytes = (request2) => { const { body } = request2[INTERNALS]; if (body === null) { return 0; } if (isBlob(body)) { return body.size; } if (import_node_buffer.Buffer.isBuffer(body)) { return body.length; } if (body && typeof body.getLengthSync === "function") { return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; } return null; }; writeToStream = async (dest, { body }) => { if (body === null) { dest.end(); } else { await pipeline(body, dest); } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js function fromRawHeaders(headers = []) { return new Headers2( headers.reduce((result, value, index6, array2) => { if (index6 % 2 === 0) { result.push(array2.slice(index6, index6 + 2)); } return result; }, []).filter(([name, value]) => { try { validateHeaderName(name); validateHeaderValue(name, String(value)); return true; } catch { return false; } }) ); } var import_node_util2, import_node_http, validateHeaderName, validateHeaderValue, Headers2; var init_headers = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() { "use strict"; import_node_util2 = require("util"); import_node_http = __toESM(require("http"), 1); validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => { if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { const error2 = new TypeError(`Header name must be a valid HTTP token [${name}]`); Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); throw error2; } }; validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => { if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { const error2 = new TypeError(`Invalid character in header content ["${name}"]`); Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" }); throw error2; } }; Headers2 = class _Headers extends URLSearchParams { /** * Headers class * * @constructor * @param {HeadersInit} [init] - Response headers */ constructor(init2) { let result = []; if (init2 instanceof _Headers) { const raw2 = init2.raw(); for (const [name, values] of Object.entries(raw2)) { result.push(...values.map((value) => [name, value])); } } else if (init2 == null) { } else if (typeof init2 === "object" && !import_node_util2.types.isBoxedPrimitive(init2)) { const method = init2[Symbol.iterator]; if (method == null) { result.push(...Object.entries(init2)); } else { if (typeof method !== "function") { throw new TypeError("Header pairs must be iterable"); } result = [...init2].map((pair) => { if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) { throw new TypeError("Each header pair must be an iterable object"); } return [...pair]; }).map((pair) => { if (pair.length !== 2) { throw new TypeError("Each header pair must be a name/value tuple"); } return [...pair]; }); } } else { throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)"); } result = result.length > 0 ? result.map(([name, value]) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return [String(name).toLowerCase(), String(value)]; }) : void 0; super(result); return new Proxy(this, { get(target, p5, receiver) { switch (p5) { case "append": case "set": return (name, value) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return URLSearchParams.prototype[p5].call( target, String(name).toLowerCase(), String(value) ); }; case "delete": case "has": case "getAll": return (name) => { validateHeaderName(name); return URLSearchParams.prototype[p5].call( target, String(name).toLowerCase() ); }; case "keys": return () => { target.sort(); return new Set(URLSearchParams.prototype.keys.call(target)).keys(); }; default: return Reflect.get(target, p5, receiver); } } }); } get [Symbol.toStringTag]() { return this.constructor.name; } toString() { return Object.prototype.toString.call(this); } get(name) { const values = this.getAll(name); if (values.length === 0) { return null; } let value = values.join(", "); if (/^content-encoding$/i.test(name)) { value = value.toLowerCase(); } return value; } forEach(callback, thisArg = void 0) { for (const name of this.keys()) { Reflect.apply(callback, thisArg, [this.get(name), name, this]); } } *values() { for (const name of this.keys()) { yield this.get(name); } } /** * @type {() => IterableIterator<[string, string]>} */ *entries() { for (const name of this.keys()) { yield [name, this.get(name)]; } } [Symbol.iterator]() { return this.entries(); } /** * Node-fetch non-spec method * returning all headers and their values as array * @returns {Record<string, string[]>} */ raw() { return [...this.keys()].reduce((result, key) => { result[key] = this.getAll(key); return result; }, {}); } /** * For better console.log(headers) and also to convert Headers into Node.js Request compatible format */ [Symbol.for("nodejs.util.inspect.custom")]() { return [...this.keys()].reduce((result, key) => { const values = this.getAll(key); if (key === "host") { result[key] = values[0]; } else { result[key] = values.length > 1 ? values : values[0]; } return result; }, {}); } }; Object.defineProperties( Headers2.prototype, ["get", "entries", "forEach", "values"].reduce((result, property) => { result[property] = { enumerable: true }; return result; }, {}) ); } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js var redirectStatus, isRedirect; var init_is_redirect = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js"() { "use strict"; redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); isRedirect = (code) => { return redirectStatus.has(code); }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js var INTERNALS2, Response3; var init_response = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() { "use strict"; init_headers(); init_body2(); init_is_redirect(); INTERNALS2 = Symbol("Response internals"); Response3 = class _Response extends Body { constructor(body = null, options = {}) { super(body, options); const status = options.status != null ? options.status : 200; const headers = new Headers2(options.headers); if (body !== null && !headers.has("Content-Type")) { const contentType = extractContentType(body, this); if (contentType) { headers.append("Content-Type", contentType); } } this[INTERNALS2] = { type: "default", url: options.url, status, statusText: options.statusText || "", headers, counter: options.counter, highWaterMark: options.highWaterMark }; } get type() { return this[INTERNALS2].type; } get url() { return this[INTERNALS2].url || ""; } get status() { return this[INTERNALS2].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; } get redirected() { return this[INTERNALS2].counter > 0; } get statusText() { return this[INTERNALS2].statusText; } get headers() { return this[INTERNALS2].headers; } get highWaterMark() { return this[INTERNALS2].highWaterMark; } /** * Clone this response * * @return Response */ clone() { return new _Response(clone(this, this.highWaterMark), { type: this.type, url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected, size: this.size, highWaterMark: this.highWaterMark }); } /** * @param {string} url The URL that the new response is to originate from. * @param {number} status An optional status code for the response (e.g., 302.) * @returns {Response} A Response object. */ static redirect(url, status = 302) { if (!isRedirect(status)) { throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); } return new _Response(null, { headers: { location: new URL(url).toString() }, status }); } static error() { const response = new _Response(null, { status: 0, statusText: "" }); response[INTERNALS2].type = "error"; return response; } static json(data = void 0, init2 = {}) { const body = JSON.stringify(data); if (body === void 0) { throw new TypeError("data is not JSON serializable"); } const headers = new Headers2(init2 && init2.headers); if (!headers.has("content-type")) { headers.set("content-type", "application/json"); } return new _Response(body, { ...init2, headers }); } get [Symbol.toStringTag]() { return "Response"; } }; Object.defineProperties(Response3.prototype, { type: { enumerable: true }, url: { enumerable: true }, status: { enumerable: true }, ok: { enumerable: true }, redirected: { enumerable: true }, statusText: { enumerable: true }, headers: { enumerable: true }, clone: { enumerable: true } }); } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js var getSearch; var init_get_search = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js"() { "use strict"; getSearch = (parsedURL) => { if (parsedURL.search) { return parsedURL.search; } const lastOffset = parsedURL.href.length - 1; const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js function stripURLForUseAsAReferrer(url, originOnly = false) { if (url == null) { return "no-referrer"; } url = new URL(url); if (/^(about|blob|data):$/.test(url.protocol)) { return "no-referrer"; } url.username = ""; url.password = ""; url.hash = ""; if (originOnly) { url.pathname = ""; url.search = ""; } return url; } function validateReferrerPolicy(referrerPolicy) { if (!ReferrerPolicy.has(referrerPolicy)) { throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); } return referrerPolicy; } function isOriginPotentiallyTrustworthy(url) { if (/^(http|ws)s:$/.test(url.protocol)) { return true; } const hostIp = url.host.replace(/(^\[)|(]$)/g, ""); const hostIPVersion = (0, import_node_net.isIP)(hostIp); if (hostIPVersion === 4 && /^127\./.test(hostIp)) { return true; } if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { return true; } if (url.host === "localhost" || url.host.endsWith(".localhost")) { return false; } if (url.protocol === "file:") { return true; } return false; } function isUrlPotentiallyTrustworthy(url) { if (/^about:(blank|srcdoc)$/.test(url)) { return true; } if (url.protocol === "data:") { return true; } if (/^(blob|filesystem):$/.test(url.protocol)) { return true; } return isOriginPotentiallyTrustworthy(url); } function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) { if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") { return null; } const policy5 = request2.referrerPolicy; if (request2.referrer === "about:client") { return "no-referrer"; } const referrerSource = request2.referrer; let referrerURL = stripURLForUseAsAReferrer(referrerSource); let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin; } if (referrerURLCallback) { referrerURL = referrerURLCallback(referrerURL); } if (referrerOriginCallback) { referrerOrigin = referrerOriginCallback(referrerOrigin); } const currentURL = new URL(request2.url); switch (policy5) { case "no-referrer": return "no-referrer"; case "origin": return referrerOrigin; case "unsafe-url": return referrerURL; case "strict-origin": if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerOrigin.toString(); case "strict-origin-when-cross-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerOrigin; case "same-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } return "no-referrer"; case "origin-when-cross-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } return referrerOrigin; case "no-referrer-when-downgrade": if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerURL; default: throw new TypeError(`Invalid referrerPolicy: ${policy5}`); } } function parseReferrerPolicyFromHeader(headers) { const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); let policy5 = ""; for (const token of policyTokens) { if (token && ReferrerPolicy.has(token)) { policy5 = token; } } return policy5; } var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY; var init_referrer = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() { "use strict"; import_node_net = require("net"); ReferrerPolicy = /* @__PURE__ */ new Set([ "", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url" ]); DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js var import_node_url, import_node_util3, INTERNALS3, isRequest, doBadDataWarn, Request3, getNodeRequestOptions; var init_request2 = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() { "use strict"; import_node_url = require("url"); import_node_util3 = require("util"); init_headers(); init_body2(); init_is(); init_get_search(); init_referrer(); INTERNALS3 = Symbol("Request internals"); isRequest = (object) => { return typeof object === "object" && typeof object[INTERNALS3] === "object"; }; doBadDataWarn = (0, import_node_util3.deprecate)( () => { }, ".data is not a valid RequestInit property, use .body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (request)" ); Request3 = class _Request extends Body { constructor(input, init2 = {}) { let parsedURL; if (isRequest(input)) { parsedURL = new URL(input.url); } else { parsedURL = new URL(input); input = {}; } if (parsedURL.username !== "" || parsedURL.password !== "") { throw new TypeError(`${parsedURL} is an url with embedded credentials.`); } let method = init2.method || input.method || "GET"; if (/^(delete|get|head|options|post|put)$/i.test(method)) { method = method.toUpperCase(); } if (!isRequest(init2) && "data" in init2) { doBadDataWarn(); } if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { throw new TypeError("Request with GET/HEAD method cannot have body"); } const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null; super(inputBody, { size: init2.size || input.size || 0 }); const headers = new Headers2(init2.headers || input.headers || {}); if (inputBody !== null && !headers.has("Content-Type")) { const contentType = extractContentType(inputBody, this); if (contentType) { headers.set("Content-Type", contentType); } } let signal = isRequest(input) ? input.signal : null; if ("signal" in init2) { signal = init2.signal; } if (signal != null && !isAbortSignal(signal)) { throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); } let referrer = init2.referrer == null ? input.referrer : init2.referrer; if (referrer === "") { referrer = "no-referrer"; } else if (referrer) { const parsedReferrer = new URL(referrer); referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; } else { referrer = void 0; } this[INTERNALS3] = { method, redirect: init2.redirect || input.redirect || "follow", headers, parsedURL, signal, referrer }; this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow; this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress; this.counter = init2.counter || input.counter || 0; this.agent = init2.agent || input.agent; this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384; this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false; this.referrerPolicy = init2.referrerPolicy || input.referrerPolicy || ""; } /** @returns {string} */ get method() { return this[INTERNALS3].method; } /** @returns {string} */ get url() { return (0, import_node_url.format)(this[INTERNALS3].parsedURL); } /** @returns {Headers} */ get headers() { return this[INTERNALS3].headers; } get redirect() { return this[INTERNALS3].redirect; } /** @returns {AbortSignal} */ get signal() { return this[INTERNALS3].signal; } // https://fetch.spec.whatwg.org/#dom-request-referrer get referrer() { if (this[INTERNALS3].referrer === "no-referrer") { return ""; } if (this[INTERNALS3].referrer === "client") { return "about:client"; } if (this[INTERNALS3].referrer) { return this[INTERNALS3].referrer.toString(); } return void 0; } get referrerPolicy() { return this[INTERNALS3].referrerPolicy; } set referrerPolicy(referrerPolicy) { this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); } /** * Clone this request * * @return Request */ clone() { return new _Request(this); } get [Symbol.toStringTag]() { return "Request"; } }; Object.defineProperties(Request3.prototype, { method: { enumerable: true }, url: { enumerable: true }, headers: { enumerable: true }, redirect: { enumerable: true }, clone: { enumerable: true }, signal: { enumerable: true }, referrer: { enumerable: true }, referrerPolicy: { enumerable: true } }); getNodeRequestOptions = (request2) => { const { parsedURL } = request2[INTERNALS3]; const headers = new Headers2(request2[INTERNALS3].headers); if (!headers.has("Accept")) { headers.set("Accept", "*/*"); } let contentLengthValue = null; if (request2.body === null && /^(post|put)$/i.test(request2.method)) { contentLengthValue = "0"; } if (request2.body !== null) { const totalBytes = getTotalBytes(request2); if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set("Content-Length", contentLengthValue); } if (request2.referrerPolicy === "") { request2.referrerPolicy = DEFAULT_REFERRER_POLICY; } if (request2.referrer && request2.referrer !== "no-referrer") { request2[INTERNALS3].referrer = determineRequestsReferrer(request2); } else { request2[INTERNALS3].referrer = "no-referrer"; } if (request2[INTERNALS3].referrer instanceof URL) { headers.set("Referer", request2.referrer); } if (!headers.has("User-Agent")) { headers.set("User-Agent", "node-fetch"); } if (request2.compress && !headers.has("Accept-Encoding")) { headers.set("Accept-Encoding", "gzip, deflate, br"); } let { agent } = request2; if (typeof agent === "function") { agent = agent(parsedURL); } const search = getSearch(parsedURL); const options = { // Overwrite search to retain trailing ? (issue #776) path: parsedURL.pathname + search, // The following options are not expressed in the URL method: request2.method, headers: headers[Symbol.for("nodejs.util.inspect.custom")](), insecureHTTPParser: request2.insecureHTTPParser, agent }; return { /** @type {URL} */ parsedURL, options }; }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js var AbortError; var init_abort_error = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js"() { "use strict"; init_base(); AbortError = class extends FetchBaseError { constructor(message, type = "aborted") { super(message, type); } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js async function fetch2(url, options_) { return new Promise((resolve, reject) => { const request2 = new Request3(url, options_); const { parsedURL, options } = getNodeRequestOptions(request2); if (!supportedSchemas.has(parsedURL.protocol)) { throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); } if (parsedURL.protocol === "data:") { const data = dist_default(request2.url); const response2 = new Response3(data, { headers: { "Content-Type": data.typeFull } }); resolve(response2); return; } const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request; const { signal } = request2; let response = null; const abort = () => { const error2 = new AbortError("The operation was aborted."); reject(error2); if (request2.body && request2.body instanceof import_node_stream2.default.Readable) { request2.body.destroy(error2); } if (!response || !response.body) { return; } response.body.emit("error", error2); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = () => { abort(); finalize(); }; const request_ = send(parsedURL.toString(), options); if (signal) { signal.addEventListener("abort", abortAndFinalize); } const finalize = () => { request_.abort(); if (signal) { signal.removeEventListener("abort", abortAndFinalize); } }; request_.on("error", (error2) => { reject(new FetchError(`request to ${request2.url} failed, reason: ${error2.message}`, "system", error2)); finalize(); }); fixResponseChunkedTransferBadEnding(request_, (error2) => { if (response && response.body) { response.body.destroy(error2); } }); if (process.version < "v14") { request_.on("socket", (s6) => { let endedWithEventsCount; s6.prependListener("end", () => { endedWithEventsCount = s6._eventsCount; }); s6.prependListener("close", (hadError) => { if (response && endedWithEventsCount < s6._eventsCount && !hadError) { const error2 = new Error("Premature close"); error2.code = "ERR_STREAM_PREMATURE_CLOSE"; response.body.emit("error", error2); } }); }); } request_.on("response", (response_) => { request_.setTimeout(0); const headers = fromRawHeaders(response_.rawHeaders); if (isRedirect(response_.statusCode)) { const location = headers.get("Location"); let locationURL = null; try { locationURL = location === null ? null : new URL(location, request2.url); } catch { if (request2.redirect !== "manual") { reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); finalize(); return; } } switch (request2.redirect) { case "error": reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect")); finalize(); return; case "manual": break; case "follow": { if (locationURL === null) { break; } if (request2.counter >= request2.follow) { reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect")); finalize(); return; } const requestOptions = { headers: new Headers2(request2.headers), follow: request2.follow, counter: request2.counter + 1, agent: request2.agent, compress: request2.compress, method: request2.method, body: clone(request2), signal: request2.signal, size: request2.size, referrer: request2.referrer, referrerPolicy: request2.referrerPolicy }; if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) { for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { requestOptions.headers.delete(name); } } if (response_.statusCode !== 303 && request2.body && options_.body instanceof import_node_stream2.default.Readable) { reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); finalize(); return; } if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") { requestOptions.method = "GET"; requestOptions.body = void 0; requestOptions.headers.delete("content-length"); } const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); if (responseReferrerPolicy) { requestOptions.referrerPolicy = responseReferrerPolicy; } resolve(fetch2(new Request3(locationURL, requestOptions))); finalize(); return; } default: return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`)); } } if (signal) { response_.once("end", () => { signal.removeEventListener("abort", abortAndFinalize); }); } let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => { if (error2) { reject(error2); } }); if (process.version < "v12.10") { response_.on("aborted", abortAndFinalize); } const responseOptions = { url: request2.url, status: response_.statusCode, statusText: response_.statusMessage, headers, size: request2.size, counter: request2.counter, highWaterMark: request2.highWaterMark }; const codings = headers.get("Content-Encoding"); if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { response = new Response3(body, responseOptions); resolve(response); return; } const zlibOptions = { flush: import_node_zlib.default.Z_SYNC_FLUSH, finishFlush: import_node_zlib.default.Z_SYNC_FLUSH }; if (codings === "gzip" || codings === "x-gzip") { body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error2) => { if (error2) { reject(error2); } }); response = new Response3(body, responseOptions); resolve(response); return; } if (codings === "deflate" || codings === "x-deflate") { const raw2 = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => { if (error2) { reject(error2); } }); raw2.once("data", (chunk) => { if ((chunk[0] & 15) === 8) { body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error2) => { if (error2) { reject(error2); } }); } else { body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error2) => { if (error2) { reject(error2); } }); } response = new Response3(body, responseOptions); resolve(response); }); raw2.once("end", () => { if (!response) { response = new Response3(body, responseOptions); resolve(response); } }); return; } if (codings === "br") { body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error2) => { if (error2) { reject(error2); } }); response = new Response3(body, responseOptions); resolve(response); return; } response = new Response3(body, responseOptions); resolve(response); }); writeToStream(request_, request2).catch(reject); }); } function fixResponseChunkedTransferBadEnding(request2, errorCallback) { const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n"); let isChunkedTransfer = false; let properLastChunkReceived = false; let previousChunk; request2.on("response", (response) => { const { headers } = response; isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; }); request2.on("socket", (socket) => { const onSocketClose = () => { if (isChunkedTransfer && !properLastChunkReceived) { const error2 = new Error("Premature close"); error2.code = "ERR_STREAM_PREMATURE_CLOSE"; errorCallback(error2); } }; const onData = (buf) => { properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; if (!properLastChunkReceived && previousChunk) { properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; } previousChunk = buf; }; socket.prependListener("close", onSocketClose); socket.on("data", onData); request2.on("close", () => { socket.removeListener("close", onSocketClose); socket.removeListener("data", onData); }); }); } var import_node_http2, import_node_https, import_node_zlib, import_node_stream2, import_node_buffer2, supportedSchemas; var init_src = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() { "use strict"; import_node_http2 = __toESM(require("http"), 1); import_node_https = __toESM(require("https"), 1); import_node_zlib = __toESM(require("zlib"), 1); import_node_stream2 = __toESM(require("stream"), 1); import_node_buffer2 = require("buffer"); init_dist3(); init_body2(); init_response(); init_headers(); init_request2(); init_fetch_error(); init_abort_error(); init_is_redirect(); init_esm_min(); init_is(); init_referrer(); init_from(); supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]); } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/constants.js var require_constants = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/constants.js"(exports2, module2) { "use strict"; var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; var hasBlob = typeof Blob !== "undefined"; if (hasBlob) BINARY_TYPES.push("blob"); module2.exports = { BINARY_TYPES, EMPTY_BUFFER: Buffer.alloc(0), GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", hasBlob, kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), kListener: Symbol("kListener"), kStatusCode: Symbol("status-code"), kWebSocket: Symbol("websocket"), NOOP: () => { } }; } }); // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js var require_node_gyp_build = __commonJS({ "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) { "use strict"; var fs5 = require("fs"); var path3 = require("path"); var os3 = require("os"); var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require; var vars = process.config && process.config.variables || {}; var prebuildsOnly = !!process.env.PREBUILDS_ONLY; var abi = process.versions.modules; var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; var arch = process.env.npm_config_arch || os3.arch(); var platform2 = process.env.npm_config_platform || os3.platform(); var libc = process.env.LIBC || (isAlpine(platform2) ? "musl" : "glibc"); var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; var uv = (process.versions.uv || "").split(".")[0]; module2.exports = load; function load(dir) { return runtimeRequire(load.resolve(dir)); } load.resolve = load.path = function(dir) { dir = path3.resolve(dir || "."); try { var name = runtimeRequire(path3.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_"); if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"]; } catch (err2) { } if (!prebuildsOnly) { var release2 = getFirst(path3.join(dir, "build/Release"), matchBuild); if (release2) return release2; var debug = getFirst(path3.join(dir, "build/Debug"), matchBuild); if (debug) return debug; } var prebuild = resolve(dir); if (prebuild) return prebuild; var nearby = resolve(path3.dirname(process.execPath)); if (nearby) return nearby; var target = [ "platform=" + platform2, "arch=" + arch, "runtime=" + runtime, "abi=" + abi, "uv=" + uv, armv ? "armv=" + armv : "", "libc=" + libc, "node=" + process.versions.node, process.versions.electron ? "electron=" + process.versions.electron : "", typeof __webpack_require__ === "function" ? "webpack=true" : "" // eslint-disable-line ].filter(Boolean).join(" "); throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n"); function resolve(dir2) { var tuples = readdirSync(path3.join(dir2, "prebuilds")).map(parseTuple); var tuple = tuples.filter(matchTuple(platform2, arch)).sort(compareTuples)[0]; if (!tuple) return; var prebuilds = path3.join(dir2, "prebuilds", tuple.name); var parsed = readdirSync(prebuilds).map(parseTags); var candidates = parsed.filter(matchTags(runtime, abi)); var winner = candidates.sort(compareTags(runtime))[0]; if (winner) return path3.join(prebuilds, winner.file); } }; function readdirSync(dir) { try { return fs5.readdirSync(dir); } catch (err2) { return []; } } function getFirst(dir, filter2) { var files = readdirSync(dir).filter(filter2); return files[0] && path3.join(dir, files[0]); } function matchBuild(name) { return /\.node$/.test(name); } function parseTuple(name) { var arr = name.split("-"); if (arr.length !== 2) return; var platform3 = arr[0]; var architectures = arr[1].split("+"); if (!platform3) return; if (!architectures.length) return; if (!architectures.every(Boolean)) return; return { name, platform: platform3, architectures }; } function matchTuple(platform3, arch2) { return function(tuple) { if (tuple == null) return false; if (tuple.platform !== platform3) return false; return tuple.architectures.includes(arch2); }; } function compareTuples(a5, b5) { return a5.architectures.length - b5.architectures.length; } function parseTags(file) { var arr = file.split("."); var extension = arr.pop(); var tags = { file, specificity: 0 }; if (extension !== "node") return; for (var i6 = 0; i6 < arr.length; i6++) { var tag = arr[i6]; if (tag === "node" || tag === "electron" || tag === "node-webkit") { tags.runtime = tag; } else if (tag === "napi") { tags.napi = true; } else if (tag.slice(0, 3) === "abi") { tags.abi = tag.slice(3); } else if (tag.slice(0, 2) === "uv") { tags.uv = tag.slice(2); } else if (tag.slice(0, 4) === "armv") { tags.armv = tag.slice(4); } else if (tag === "glibc" || tag === "musl") { tags.libc = tag; } else { continue; } tags.specificity++; } return tags; } function matchTags(runtime2, abi2) { return function(tags) { if (tags == null) return false; if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false; if (tags.abi && tags.abi !== abi2 && !tags.napi) return false; if (tags.uv && tags.uv !== uv) return false; if (tags.armv && tags.armv !== armv) return false; if (tags.libc && tags.libc !== libc) return false; return true; }; } function runtimeAgnostic(tags) { return tags.runtime === "node" && tags.napi; } function compareTags(runtime2) { return function(a5, b5) { if (a5.runtime !== b5.runtime) { return a5.runtime === runtime2 ? -1 : 1; } else if (a5.abi !== b5.abi) { return a5.abi ? -1 : 1; } else if (a5.specificity !== b5.specificity) { return a5.specificity > b5.specificity ? -1 : 1; } else { return 0; } }; } function isNwjs() { return !!(process.versions && process.versions.nw); } function isElectron() { if (process.versions && process.versions.electron) return true; if (process.env.ELECTRON_RUN_AS_NODE) return true; return typeof window !== "undefined" && window.process && window.process.type === "renderer"; } function isAlpine(platform3) { return platform3 === "linux" && fs5.existsSync("/etc/alpine-release"); } load.parseTags = parseTags; load.matchTags = matchTags; load.compareTags = compareTags; load.parseTuple = parseTuple; load.matchTuple = matchTuple; load.compareTuples = compareTuples; } }); // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js var require_node_gyp_build2 = __commonJS({ "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports2, module2) { "use strict"; var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require; if (typeof runtimeRequire.addon === "function") { module2.exports = runtimeRequire.addon.bind(runtimeRequire); } else { module2.exports = require_node_gyp_build(); } } }); // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js var require_fallback = __commonJS({ "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js"(exports2, module2) { "use strict"; var mask = (source, mask2, output, offset, length) => { for (var i6 = 0; i6 < length; i6++) { output[offset + i6] = source[i6] ^ mask2[i6 & 3]; } }; var unmask = (buffer, mask2) => { const length = buffer.length; for (var i6 = 0; i6 < length; i6++) { buffer[i6] ^= mask2[i6 & 3]; } }; module2.exports = { mask, unmask }; } }); // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js var require_bufferutil = __commonJS({ "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js"(exports2, module2) { "use strict"; try { module2.exports = require_node_gyp_build2()(__dirname); } catch (e6) { module2.exports = require_fallback(); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/buffer-util.js var require_buffer_util = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/buffer-util.js"(exports2, module2) { "use strict"; var { EMPTY_BUFFER } = require_constants(); var FastBuffer = Buffer[Symbol.species]; function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i6 = 0; i6 < list.length; i6++) { const buf = list[i6]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) { return new FastBuffer(target.buffer, target.byteOffset, offset); } return target; } function _mask(source, mask, output, offset, length) { for (let i6 = 0; i6 < length; i6++) { output[offset + i6] = source[i6] ^ mask[i6 & 3]; } } function _unmask(buffer, mask) { for (let i6 = 0; i6 < buffer.length; i6++) { buffer[i6] ^= mask[i6 & 3]; } } function toArrayBuffer(buf) { if (buf.length === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); } function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = new FastBuffer(data); } else if (ArrayBuffer.isView(data)) { buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } module2.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; if (!process.env.WS_NO_BUFFER_UTIL) { try { const bufferUtil = require_bufferutil(); module2.exports.mask = function(source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bufferUtil.mask(source, mask, output, offset, length); }; module2.exports.unmask = function(buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bufferUtil.unmask(buffer, mask); }; } catch (e6) { } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/limiter.js var require_limiter = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/limiter.js"(exports2, module2) { "use strict"; var kDone = Symbol("kDone"); var kRun = Symbol("kRun"); var Limiter = class { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } }; module2.exports = Limiter; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/permessage-deflate.js var require_permessage_deflate = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) { "use strict"; var zlib2 = require("zlib"); var bufferUtil = require_buffer_util(); var Limiter = require_limiter(); var { kStatusCode } = require_constants(); var FastBuffer = Buffer[Symbol.species]; var TRAILER = Buffer.from([0, 0, 255, 255]); var kPerMessageDeflate = Symbol("permessage-deflate"); var kTotalLength = Symbol("total-length"); var kCallback = Symbol("callback"); var kBuffers = Symbol("buffers"); var kError = Symbol("error"); var zlibLimiter; var PerMessageDeflate = class { /** * Creates a PerMessageDeflate instance. * * @param {Object} [options] Configuration options * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * for, or request, a custom client window size * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * acknowledge disabling of client context takeover * @param {Number} [options.concurrencyLimit=10] The number of concurrent * calls to zlib * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the * use of a custom server window size * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * disabling of server context takeover * @param {Number} [options.threshold=1024] Size (in bytes) below which * messages should not be compressed if context takeover is disabled * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * deflate * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * inflate * @param {Boolean} [isServer=false] Create the instance in either server or * client mode * @param {Number} [maxPayload=0] The maximum allowed message length */ constructor(options, isServer, maxPayload) { this._maxPayload = maxPayload | 0; this._options = options || {}; this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; this._isServer = !!isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return "permessage-deflate"; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( "The deflate stream was closed while data was being processed" ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { return false; } return true; }); if (!accepted) { throw new Error("None of the extension offers can be accepted"); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === "number") { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === "number") { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === "number") { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === "client_max_window_bits") { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === "server_max_window_bits") { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err2, result) => { done(); callback(err2, result); }); }); } /** * Compress data. Concurrency limited. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err2, result) => { done(); callback(err2, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? "client" : "server"; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib2.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on("error", inflateOnError); this._inflate.on("data", inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err2 = this._inflate[kError]; if (err2) { this._inflate.close(); this._inflate = null; callback(err2); return; } const data2 = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (this._inflate._readableState.endEmitted) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.reset(); } } callback(null, data2); }); } /** * Compress data. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? "server" : "client"; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib2.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; this._deflate.on("data", deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => { if (!this._deflate) { return; } let data2 = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) { data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); } this._deflate[kCallback] = null; this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.reset(); } callback(null, data2); }); } }; module2.exports = PerMessageDeflate; function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError("Max payload size exceeded"); this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; this[kError][kStatusCode] = 1009; this.removeListener("data", inflateOnData); this.reset(); } function inflateOnError(err2) { this[kPerMessageDeflate]._inflate = null; if (this[kError]) { this[kCallback](this[kError]); return; } err2[kStatusCode] = 1007; this[kCallback](err2); } } }); // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js var require_fallback2 = __commonJS({ "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports2, module2) { "use strict"; function isValidUTF8(buf) { const len = buf.length; let i6 = 0; while (i6 < len) { if ((buf[i6] & 128) === 0) { i6++; } else if ((buf[i6] & 224) === 192) { if (i6 + 1 === len || (buf[i6 + 1] & 192) !== 128 || (buf[i6] & 254) === 192) { return false; } i6 += 2; } else if ((buf[i6] & 240) === 224) { if (i6 + 2 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || buf[i6] === 224 && (buf[i6 + 1] & 224) === 128 || // overlong buf[i6] === 237 && (buf[i6 + 1] & 224) === 160) { return false; } i6 += 3; } else if ((buf[i6] & 248) === 240) { if (i6 + 3 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || (buf[i6 + 3] & 192) !== 128 || buf[i6] === 240 && (buf[i6 + 1] & 240) === 128 || // overlong buf[i6] === 244 && buf[i6 + 1] > 143 || buf[i6] > 244) { return false; } i6 += 4; } else { return false; } } return true; } module2.exports = isValidUTF8; } }); // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js var require_utf_8_validate = __commonJS({ "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js"(exports2, module2) { "use strict"; try { module2.exports = require_node_gyp_build2()(__dirname); } catch (e6) { module2.exports = require_fallback2(); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/validation.js var require_validation = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/validation.js"(exports2, module2) { "use strict"; var { isUtf8 } = require("buffer"); var { hasBlob } = require_constants(); var tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; function isValidStatusCode(code) { return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; } function _isValidUTF8(buf) { const len = buf.length; let i6 = 0; while (i6 < len) { if ((buf[i6] & 128) === 0) { i6++; } else if ((buf[i6] & 224) === 192) { if (i6 + 1 === len || (buf[i6 + 1] & 192) !== 128 || (buf[i6] & 254) === 192) { return false; } i6 += 2; } else if ((buf[i6] & 240) === 224) { if (i6 + 2 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || buf[i6] === 224 && (buf[i6 + 1] & 224) === 128 || // Overlong buf[i6] === 237 && (buf[i6 + 1] & 224) === 160) { return false; } i6 += 3; } else if ((buf[i6] & 248) === 240) { if (i6 + 3 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || (buf[i6 + 3] & 192) !== 128 || buf[i6] === 240 && (buf[i6 + 1] & 240) === 128 || // Overlong buf[i6] === 244 && buf[i6 + 1] > 143 || buf[i6] > 244) { return false; } i6 += 4; } else { return false; } } return true; } function isBlob3(value) { return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); } module2.exports = { isBlob: isBlob3, isValidStatusCode, isValidUTF8: _isValidUTF8, tokenChars }; if (isUtf8) { module2.exports.isValidUTF8 = function(buf) { return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); }; } else if (!process.env.WS_NO_UTF_8_VALIDATE) { try { const isValidUTF8 = require_utf_8_validate(); module2.exports.isValidUTF8 = function(buf) { return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); }; } catch (e6) { } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/receiver.js var require_receiver = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/receiver.js"(exports2, module2) { "use strict"; var { Writable: Writable2 } = require("stream"); var PerMessageDeflate = require_permessage_deflate(); var { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants(); var { concat, toArrayBuffer, unmask } = require_buffer_util(); var { isValidStatusCode, isValidUTF8 } = require_validation(); var FastBuffer = Buffer[Symbol.species]; var GET_INFO = 0; var GET_PAYLOAD_LENGTH_16 = 1; var GET_PAYLOAD_LENGTH_64 = 2; var GET_MASK = 3; var GET_DATA = 4; var INFLATING = 5; var DEFER_EVENT = 6; var Receiver2 = class extends Writable2 { /** * Creates a Receiver instance. * * @param {Object} [options] Options object * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {String} [options.binaryType=nodebuffer] The type for binary data * @param {Object} [options.extensions] An object containing the negotiated * extensions * @param {Boolean} [options.isServer=false] Specifies whether to operate in * client or server mode * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages */ constructor(options = {}) { super(); this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; this._binaryType = options.binaryType || BINARY_TYPES[0]; this._extensions = options.extensions || {}; this._isServer = !!options.isServer; this._maxPayload = options.maxPayload | 0; this._skipUTF8Validation = !!options.skipUTF8Validation; this[kWebSocket] = void 0; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = void 0; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._errored = false; this._loop = false; this._state = GET_INFO; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 8 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n5) { this._bufferedBytes -= n5; if (n5 === this._buffers[0].length) return this._buffers.shift(); if (n5 < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n5, buf.length - n5 ); return new FastBuffer(buf.buffer, buf.byteOffset, n5); } const dst = Buffer.allocUnsafe(n5); do { const buf = this._buffers[0]; const offset = dst.length - n5; if (n5 >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n5), offset); this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n5, buf.length - n5 ); } n5 -= buf.length; } while (n5 > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { this._loop = true; do { switch (this._state) { case GET_INFO: this.getInfo(cb); break; case GET_PAYLOAD_LENGTH_16: this.getPayloadLength16(cb); break; case GET_PAYLOAD_LENGTH_64: this.getPayloadLength64(cb); break; case GET_MASK: this.getMask(); break; case GET_DATA: this.getData(cb); break; case INFLATING: case DEFER_EVENT: this._loop = false; return; } } while (this._loop); if (!this._errored) cb(); } /** * Reads the first two bytes of a frame. * * @param {Function} cb Callback * @private */ getInfo(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 48) !== 0) { const error2 = this.createError( RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3" ); cb(error2); return; } const compressed = (buf[0] & 64) === 64; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } this._fin = (buf[0] & 128) === 128; this._opcode = buf[0] & 15; this._payloadLength = buf[1] & 127; if (this._opcode === 0) { if (compressed) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } if (!this._fragmented) { const error2 = this.createError( RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } this._opcode = this._fragmented; } else if (this._opcode === 1 || this._opcode === 2) { if (this._fragmented) { const error2 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } this._compressed = compressed; } else if (this._opcode > 7 && this._opcode < 11) { if (!this._fin) { const error2 = this.createError( RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN" ); cb(error2); return; } if (compressed) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { const error2 = this.createError( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" ); cb(error2); return; } } else { const error2 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 128) === 128; if (this._isServer) { if (!this._masked) { const error2 = this.createError( RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK" ); cb(error2); return; } } else if (this._masked) { const error2 = this.createError( RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK" ); cb(error2); return; } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else this.haveLength(cb); } /** * Gets extended payload length (7+16). * * @param {Function} cb Callback * @private */ getPayloadLength16(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); this.haveLength(cb); } /** * Gets extended payload length (7+64). * * @param {Function} cb Callback * @private */ getPayloadLength64(cb) { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); if (num > Math.pow(2, 53 - 32) - 1) { const error2 = this.createError( RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" ); cb(error2); return; } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); this.haveLength(cb); } /** * Payload length has been read. * * @param {Function} cb Callback * @private */ haveLength(cb) { if (this._payloadLength && this._opcode < 8) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { const error2 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error2); return; } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { unmask(data, this._mask); } } if (this._opcode > 7) { this.controlMessage(data, cb); return; } if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { this._messageLength = this._totalPayloadLength; this._fragments.push(data); } this.dataMessage(cb); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err2, buf) => { if (err2) return cb(err2); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { const error2 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error2); return; } this._fragments.push(buf); } this.dataMessage(cb); if (this._state === GET_INFO) this.startLoop(cb); }); } /** * Handles a data message. * * @param {Function} cb Callback * @private */ dataMessage(cb) { if (!this._fin) { this._state = GET_INFO; return; } const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === "nodebuffer") { data = concat(fragments, messageLength); } else if (this._binaryType === "arraybuffer") { data = toArrayBuffer(concat(fragments, messageLength)); } else if (this._binaryType === "blob") { data = new Blob(fragments); } else { data = fragments; } if (this._allowSynchronousEvents) { this.emit("message", data, true); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", data, true); this._state = GET_INFO; this.startLoop(cb); }); } } else { const buf = concat(fragments, messageLength); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error2 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error2); return; } if (this._state === INFLATING || this._allowSynchronousEvents) { this.emit("message", buf, false); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", buf, false); this._state = GET_INFO; this.startLoop(cb); }); } } } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data, cb) { if (this._opcode === 8) { if (data.length === 0) { this._loop = false; this.emit("conclude", 1005, EMPTY_BUFFER); this.end(); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { const error2 = this.createError( RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE" ); cb(error2); return; } const buf = new FastBuffer( data.buffer, data.byteOffset + 2, data.length - 2 ); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error2 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error2); return; } this._loop = false; this.emit("conclude", code, buf); this.end(); } this._state = GET_INFO; return; } if (this._allowSynchronousEvents) { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; this.startLoop(cb); }); } } /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ createError(ErrorCtor, message, prefix2, statusCode, errorCode) { this._loop = false; this._errored = true; const err2 = new ErrorCtor( prefix2 ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err2, this.createError); err2.code = errorCode; err2[kStatusCode] = statusCode; return err2; } }; module2.exports = Receiver2; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/sender.js var require_sender = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/sender.js"(exports2, module2) { "use strict"; var { Duplex } = require("stream"); var { randomFillSync } = require("crypto"); var PerMessageDeflate = require_permessage_deflate(); var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants(); var { isBlob: isBlob3, isValidStatusCode } = require_validation(); var { mask: applyMask, toBuffer } = require_buffer_util(); var kByteLength = Symbol("kByteLength"); var maskBuffer = Buffer.alloc(4); var RANDOM_POOL_SIZE = 8 * 1024; var randomPool; var randomPoolPointer = RANDOM_POOL_SIZE; var DEFAULT = 0; var DEFLATING = 1; var GET_BLOB_DATA = 2; var Sender2 = class _Sender { /** * Creates a Sender instance. * * @param {Duplex} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions * @param {Function} [generateMask] The function used to generate the masking * key */ constructor(socket, extensions, generateMask) { this._extensions = extensions || {}; if (generateMask) { this._generateMask = generateMask; this._maskBuffer = Buffer.alloc(4); } this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._queue = []; this._state = DEFAULT; this.onerror = NOOP; this[kWebSocket] = void 0; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {(Buffer|String)} data The data to frame * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {(Buffer|String)[]} The framed data * @public */ static frame(data, options) { let mask; let merge2 = false; let offset = 2; let skipMasking = false; if (options.mask) { mask = options.maskBuffer || maskBuffer; if (options.generateMask) { options.generateMask(mask); } else { if (randomPoolPointer === RANDOM_POOL_SIZE) { if (randomPool === void 0) { randomPool = Buffer.alloc(RANDOM_POOL_SIZE); } randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); randomPoolPointer = 0; } mask[0] = randomPool[randomPoolPointer++]; mask[1] = randomPool[randomPoolPointer++]; mask[2] = randomPool[randomPoolPointer++]; mask[3] = randomPool[randomPoolPointer++]; } skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; offset = 6; } let dataLength; if (typeof data === "string") { if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { dataLength = options[kByteLength]; } else { data = Buffer.from(data); dataLength = data.length; } } else { dataLength = data.length; merge2 = options.mask && options.readOnly && !skipMasking; } let payloadLength = dataLength; if (dataLength >= 65536) { offset += 8; payloadLength = 127; } else if (dataLength > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset); target[0] = options.fin ? options.opcode | 128 : options.opcode; if (options.rsv1) target[0] |= 64; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(dataLength, 2); } else if (payloadLength === 127) { target[2] = target[3] = 0; target.writeUIntBE(dataLength, 4, 6); } if (!options.mask) return [target, data]; target[1] |= 128; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (skipMasking) return [target, data]; if (merge2) { applyMask(data, mask, target, offset, dataLength); return [target]; } applyMask(data, mask, data, 0, dataLength); return [target, data]; } /** * Sends a close message to the other peer. * * @param {Number} [code] The status code component of the body * @param {(String|Buffer)} [data] The message component of the body * @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Function} [cb] Callback * @public */ close(code, data, mask, cb) { let buf; if (code === void 0) { buf = EMPTY_BUFFER; } else if (typeof code !== "number" || !isValidStatusCode(code)) { throw new TypeError("First argument must be a valid error code number"); } else if (data === void 0 || !data.length) { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError("The message must not be greater than 123 bytes"); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); if (typeof data === "string") { buf.write(data, 2); } else { buf.set(data, 2); } } const options = { [kByteLength]: buf.length, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 8, readOnly: false, rsv1: false }; if (this._state !== DEFAULT) { this.enqueue([this.dispatch, buf, false, options, cb]); } else { this.sendFrame(_Sender.frame(buf, options), cb); } } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 9, readOnly, rsv1: false }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 10, readOnly, rsv1: false }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { rsv1 = byteLength >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; const opts = { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1 }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, this._compress, opts, cb]); } else { this.getBlobData(data, this._compress, opts, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, this._compress, opts, cb]); } else { this.dispatch(data, this._compress, opts, cb); } } /** * Gets the contents of a blob as binary data. * * @param {Blob} blob The blob * @param {Boolean} [compress=false] Specifies whether or not to compress * the data * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ getBlobData(blob, compress2, options, cb) { this._bufferedBytes += options[kByteLength]; this._state = GET_BLOB_DATA; blob.arrayBuffer().then((arrayBuffer) => { if (this._socket.destroyed) { const err2 = new Error( "The socket was closed while the blob was being read" ); process.nextTick(callCallbacks, this, err2, cb); return; } this._bufferedBytes -= options[kByteLength]; const data = toBuffer(arrayBuffer); if (!compress2) { this._state = DEFAULT; this.sendFrame(_Sender.frame(data, options), cb); this.dequeue(); } else { this.dispatch(data, compress2, options, cb); } }).catch((err2) => { process.nextTick(onError, this, err2, cb); }); } /** * Dispatches a message. * * @param {(Buffer|String)} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress2, options, cb) { if (!compress2) { this.sendFrame(_Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += options[kByteLength]; this._state = DEFLATING; perMessageDeflate.compress(data, options.fin, (_3, buf) => { if (this._socket.destroyed) { const err2 = new Error( "The socket was closed while data was being compressed" ); callCallbacks(this, err2, cb); return; } this._bufferedBytes -= options[kByteLength]; this._state = DEFAULT; options.readOnly = false; this.sendFrame(_Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (this._state === DEFAULT && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[3][kByteLength]; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[3][kByteLength]; this._queue.push(params); } /** * Sends a frame. * * @param {(Buffer | String)[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } }; module2.exports = Sender2; function callCallbacks(sender, err2, cb) { if (typeof cb === "function") cb(err2); for (let i6 = 0; i6 < sender._queue.length; i6++) { const params = sender._queue[i6]; const callback = params[params.length - 1]; if (typeof callback === "function") callback(err2); } } function onError(sender, err2, cb) { callCallbacks(sender, err2, cb); sender.onerror(err2); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/event-target.js var require_event_target = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/event-target.js"(exports2, module2) { "use strict"; var { kForOnEventAttribute, kListener } = require_constants(); var kCode = Symbol("kCode"); var kData = Symbol("kData"); var kError = Symbol("kError"); var kMessage = Symbol("kMessage"); var kReason = Symbol("kReason"); var kTarget = Symbol("kTarget"); var kType = Symbol("kType"); var kWasClean = Symbol("kWasClean"); var Event = class { /** * Create a new `Event`. * * @param {String} type The name of the event * @throws {TypeError} If the `type` argument is not specified */ constructor(type) { this[kTarget] = null; this[kType] = type; } /** * @type {*} */ get target() { return this[kTarget]; } /** * @type {String} */ get type() { return this[kType]; } }; Object.defineProperty(Event.prototype, "target", { enumerable: true }); Object.defineProperty(Event.prototype, "type", { enumerable: true }); var CloseEvent = class extends Event { /** * Create a new `CloseEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {Number} [options.code=0] The status code explaining why the * connection was closed * @param {String} [options.reason=''] A human-readable string explaining why * the connection was closed * @param {Boolean} [options.wasClean=false] Indicates whether or not the * connection was cleanly closed */ constructor(type, options = {}) { super(type); this[kCode] = options.code === void 0 ? 0 : options.code; this[kReason] = options.reason === void 0 ? "" : options.reason; this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; } /** * @type {Number} */ get code() { return this[kCode]; } /** * @type {String} */ get reason() { return this[kReason]; } /** * @type {Boolean} */ get wasClean() { return this[kWasClean]; } }; Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); var ErrorEvent = class extends Event { /** * Create a new `ErrorEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.error=null] The error that generated this event * @param {String} [options.message=''] The error message */ constructor(type, options = {}) { super(type); this[kError] = options.error === void 0 ? null : options.error; this[kMessage] = options.message === void 0 ? "" : options.message; } /** * @type {*} */ get error() { return this[kError]; } /** * @type {String} */ get message() { return this[kMessage]; } }; Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); var MessageEvent = class extends Event { /** * Create a new `MessageEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.data=null] The message content */ constructor(type, options = {}) { super(type); this[kData] = options.data === void 0 ? null : options.data; } /** * @type {*} */ get data() { return this[kData]; } }; Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); var EventTarget = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {(Function|Object)} handler The listener to add * @param {Object} [options] An options object specifies characteristics about * the event listener * @param {Boolean} [options.once=false] A `Boolean` indicating that the * listener should be invoked at most once after being added. If `true`, * the listener would be automatically removed when invoked. * @public */ addEventListener(type, handler, options = {}) { for (const listener of this.listeners(type)) { if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { return; } } let wrapper; if (type === "message") { wrapper = function onMessage(data, isBinary) { const event = new MessageEvent("message", { data: isBinary ? data : data.toString() }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "close") { wrapper = function onClose(code, message) { const event = new CloseEvent("close", { code, reason: message.toString(), wasClean: this._closeFrameReceived && this._closeFrameSent }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "error") { wrapper = function onError(error2) { const event = new ErrorEvent("error", { error: error2, message: error2.message }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "open") { wrapper = function onOpen() { const event = new Event("open"); event[kTarget] = this; callListener(handler, this, event); }; } else { return; } wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; wrapper[kListener] = handler; if (options.once) { this.once(type, wrapper); } else { this.on(type, wrapper); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {(Function|Object)} handler The listener to remove * @public */ removeEventListener(type, handler) { for (const listener of this.listeners(type)) { if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { this.removeListener(type, listener); break; } } } }; module2.exports = { CloseEvent, ErrorEvent, Event, EventTarget, MessageEvent }; function callListener(listener, thisArg, event) { if (typeof listener === "object" && listener.handleEvent) { listener.handleEvent.call(listener, event); } else { listener.call(thisArg, event); } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/extension.js var require_extension = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/extension.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function push(dest, name, elem) { if (dest[name] === void 0) dest[name] = [elem]; else dest[name].push(elem); } function parse4(header) { const offers = /* @__PURE__ */ Object.create(null); let params = /* @__PURE__ */ Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let code = -1; let end = -1; let i6 = 0; for (; i6 < header.length; i6++) { code = header.charCodeAt(i6); if (extensionName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i6; } else if (i6 !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i6; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i6}`); } if (end === -1) end = i6; const name = header.slice(start, end); if (code === 44) { push(offers, name, params); params = /* @__PURE__ */ Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i6}`); } } else if (paramName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i6; } else if (code === 32 || code === 9) { if (end === -1 && start !== -1) end = i6; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i6}`); } if (end === -1) end = i6; push(params, header.slice(start, end), true); if (code === 44) { push(offers, extensionName, params); params = /* @__PURE__ */ Object.create(null); extensionName = void 0; } start = end = -1; } else if (code === 61 && start !== -1 && end === -1) { paramName = header.slice(start, i6); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i6}`); } } else { if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i6}`); } if (start === -1) start = i6; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i6; } else if (code === 34 && start !== -1) { inQuotes = false; end = i6; } else if (code === 92) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i6}`); } } else if (code === 34 && header.charCodeAt(i6 - 1) === 61) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i6; } else if (start !== -1 && (code === 32 || code === 9)) { if (end === -1) end = i6; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i6}`); } if (end === -1) end = i6; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ""); mustUnescape = false; } push(params, paramName, value); if (code === 44) { push(offers, extensionName, params); params = /* @__PURE__ */ Object.create(null); extensionName = void 0; } paramName = void 0; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i6}`); } } } if (start === -1 || inQuotes || code === 32 || code === 9) { throw new SyntaxError("Unexpected end of input"); } if (end === -1) end = i6; const token = header.slice(start, end); if (extensionName === void 0) { push(offers, token, params); } else { if (paramName === void 0) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, "")); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } function format(extensions) { return Object.keys(extensions).map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations.map((params) => { return [extension].concat( Object.keys(params).map((k5) => { let values = params[k5]; if (!Array.isArray(values)) values = [values]; return values.map((v6) => v6 === true ? k5 : `${k5}=${v6}`).join("; "); }) ).join("; "); }).join(", "); }).join(", "); } module2.exports = { format, parse: parse4 }; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket.js var require_websocket = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var https2 = require("https"); var http3 = require("http"); var net = require("net"); var tls = require("tls"); var { randomBytes, createHash: createHash4 } = require("crypto"); var { Duplex, Readable: Readable6 } = require("stream"); var { URL: URL2 } = require("url"); var PerMessageDeflate = require_permessage_deflate(); var Receiver2 = require_receiver(); var Sender2 = require_sender(); var { isBlob: isBlob3 } = require_validation(); var { BINARY_TYPES, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants(); var { EventTarget: { addEventListener: addEventListener2, removeEventListener } } = require_event_target(); var { format, parse: parse4 } = require_extension(); var { toBuffer } = require_buffer_util(); var closeTimeout = 30 * 1e3; var kAborted = Symbol("kAborted"); var protocolVersions = [8, 13]; var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; var WebSocket2 = class _WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = EMPTY_BUFFER; this._closeTimer = null; this._errorEmitted = false; this._extensions = {}; this._paused = false; this._protocol = ""; this._readyState = _WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (protocols === void 0) { protocols = []; } else if (!Array.isArray(protocols)) { if (typeof protocols === "object" && protocols !== null) { options = protocols; protocols = []; } else { protocols = [protocols]; } } initAsClient(this, address, protocols, options); } else { this._autoPong = options.autoPong; this._isServer = true; } } /** * For historical reasons, the custom "nodebuffer" type is used by the default * instead of "blob". * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Boolean} */ get isPaused() { return this._paused; } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return null; } /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Object} options Options object * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.maxPayload=0] The maximum allowed message size * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ setSocket(socket, head, options) { const receiver = new Receiver2({ allowSynchronousEvents: options.allowSynchronousEvents, binaryType: this.binaryType, extensions: this._extensions, isServer: this._isServer, maxPayload: options.maxPayload, skipUTF8Validation: options.skipUTF8Validation }); const sender = new Sender2(socket, this._extensions, options.generateMask); this._receiver = receiver; this._sender = sender; this._socket = socket; receiver[kWebSocket] = this; sender[kWebSocket] = this; socket[kWebSocket] = this; receiver.on("conclude", receiverOnConclude); receiver.on("drain", receiverOnDrain); receiver.on("error", receiverOnError); receiver.on("message", receiverOnMessage); receiver.on("ping", receiverOnPing); receiver.on("pong", receiverOnPong); sender.onerror = senderOnError; if (socket.setTimeout) socket.setTimeout(0); if (socket.setNoDelay) socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on("close", socketOnClose); socket.on("data", socketOnData); socket.on("end", socketOnEnd); socket.on("error", socketOnError); this._readyState = _WebSocket.OPEN; this.emit("open"); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this.readyState === _WebSocket.CLOSING) { if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { this._socket.end(); } return; } this._readyState = _WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err2) => { if (err2) return; this._closeFrameSent = true; if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { this._socket.end(); } }); setCloseTimer(this); } /** * Pause the socket. * * @public */ pause() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof options === "function") { cb = options; options = {}; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== "string", mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this._socket) { this._readyState = _WebSocket.CLOSING; this._socket.destroy(); } } }; Object.defineProperty(WebSocket2, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2.prototype, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2.prototype, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2.prototype, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); Object.defineProperty(WebSocket2.prototype, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); [ "binaryType", "bufferedAmount", "extensions", "isPaused", "protocol", "readyState", "url" ].forEach((property) => { Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); }); ["open", "error", "close", "message"].forEach((method) => { Object.defineProperty(WebSocket2.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== "function") return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket2.prototype.addEventListener = addEventListener2; WebSocket2.prototype.removeEventListener = removeEventListener; module2.exports = WebSocket2; function initAsClient(websocket, address, protocols, options) { const opts = { allowSynchronousEvents: true, autoPong: true, protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, socketPath: void 0, hostname: void 0, protocol: void 0, timeout: void 0, method: "GET", host: void 0, path: void 0, port: void 0 }; websocket._autoPong = opts.autoPong; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` ); } let parsedUrl; if (address instanceof URL2) { parsedUrl = address; } else { try { parsedUrl = new URL2(address); } catch (e6) { throw new SyntaxError(`Invalid URL: ${address}`); } } if (parsedUrl.protocol === "http:") { parsedUrl.protocol = "ws:"; } else if (parsedUrl.protocol === "https:") { parsedUrl.protocol = "wss:"; } websocket._url = parsedUrl.href; const isSecure = parsedUrl.protocol === "wss:"; const isIpcUrl = parsedUrl.protocol === "ws+unix:"; let invalidUrlMessage; if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = "The URL contains a fragment identifier"; } if (invalidUrlMessage) { const err2 = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err2; } else { emitErrorAndClose(websocket, err2); return; } } const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString("base64"); const request2 = isSecure ? https2.request : http3.request; const protocolSet = /* @__PURE__ */ new Set(); let perMessageDeflate; opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { ...opts.headers, "Sec-WebSocket-Version": opts.protocolVersion, "Sec-WebSocket-Key": key, Connection: "Upgrade", Upgrade: "websocket" }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols.length) { for (const protocol of protocols) { if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { throw new SyntaxError( "An invalid or duplicated subprotocol was specified" ); } protocolSet.add(protocol); } opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers["Sec-WebSocket-Origin"] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isIpcUrl) { const parts = opts.path.split(":"); opts.socketPath = parts[0]; opts.path = parts[1]; } let req; if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalIpc = isIpcUrl; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; options = { ...options, headers: {} }; if (headers) { for (const [key2, value] of Object.entries(headers)) { options.headers[key2.toLowerCase()] = value; } } } else if (websocket.listenerCount("redirect") === 0) { const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || websocket._originalSecure && !isSecure) { delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = void 0; } } if (opts.auth && !options.headers.authorization) { options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); } req = websocket._req = request2(opts); if (websocket._redirects) { websocket.emit("redirect", websocket.url, req); } } else { req = websocket._req = request2(opts); } if (opts.timeout) { req.on("timeout", () => { abortHandshake(websocket, req, "Opening handshake has timed out"); }); } req.on("error", (err2) => { if (req === null || req[kAborted]) return; req = websocket._req = null; emitErrorAndClose(websocket, err2); }); req.on("response", (res) => { const location = res.headers.location; const statusCode = res.statusCode; if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, "Maximum redirects exceeded"); return; } req.abort(); let addr; try { addr = new URL2(location, address); } catch (e6) { const err2 = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err2); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit("unexpected-response", req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on("upgrade", (res, socket, head) => { websocket.emit("upgrade", res); if (websocket.readyState !== WebSocket2.CONNECTING) return; req = websocket._req = null; const upgrade = res.headers.upgrade; if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { abortHandshake(websocket, socket, "Invalid Upgrade header"); return; } const digest = createHash4("sha1").update(key + GUID).digest("base64"); if (res.headers["sec-websocket-accept"] !== digest) { abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); return; } const serverProt = res.headers["sec-websocket-protocol"]; let protError; if (serverProt !== void 0) { if (!protocolSet.size) { protError = "Server sent a subprotocol but none was requested"; } else if (!protocolSet.has(serverProt)) { protError = "Server sent an invalid subprotocol"; } } else if (protocolSet.size) { protError = "Server sent no subprotocol"; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; if (secWebSocketExtensions !== void 0) { if (!perMessageDeflate) { const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; abortHandshake(websocket, socket, message); return; } let extensions; try { extensions = parse4(secWebSocketExtensions); } catch (err2) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { const message = "Server indicated an extension that was not requested"; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err2) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { allowSynchronousEvents: opts.allowSynchronousEvents, generateMask: opts.generateMask, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } } function emitErrorAndClose(websocket, err2) { websocket._readyState = WebSocket2.CLOSING; websocket._errorEmitted = true; websocket.emit("error", err2); websocket.emitClose(); } function netConnect(options) { options.path = options.socketPath; return net.connect(options); } function tlsConnect(options) { options.path = void 0; if (!options.servername && options.servername !== "") { options.servername = net.isIP(options.host) ? "" : options.host; } return tls.connect(options); } function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket2.CLOSING; const err2 = new Error(message); Error.captureStackTrace(err2, abortHandshake); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err2); } else { stream.destroy(err2); stream.once("error", websocket.emit.bind(websocket, "error")); stream.once("close", websocket.emitClose.bind(websocket)); } } function sendAfterClose(websocket, data, cb) { if (data) { const length = isBlob3(data) ? data.size : toBuffer(data).length; if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err2 = new Error( `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` ); process.nextTick(cb, err2); } } function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket] === void 0) return; websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } function receiverOnDrain() { const websocket = this[kWebSocket]; if (!websocket.isPaused) websocket._socket.resume(); } function receiverOnError(err2) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== void 0) { websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); websocket.close(err2[kStatusCode]); } if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit("error", err2); } } function receiverOnFinish() { this[kWebSocket].emitClose(); } function receiverOnMessage(data, isBinary) { this[kWebSocket].emit("message", data, isBinary); } function receiverOnPing(data) { const websocket = this[kWebSocket]; if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); websocket.emit("ping", data); } function receiverOnPong(data) { this[kWebSocket].emit("pong", data); } function resume(stream) { stream.resume(); } function senderOnError(err2) { const websocket = this[kWebSocket]; if (websocket.readyState === WebSocket2.CLOSED) return; if (websocket.readyState === WebSocket2.OPEN) { websocket._readyState = WebSocket2.CLOSING; setCloseTimer(websocket); } this._socket.end(); if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit("error", err2); } } function setCloseTimer(websocket) { websocket._closeTimer = setTimeout( websocket._socket.destroy.bind(websocket._socket), closeTimeout ); } function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener("close", socketOnClose); this.removeListener("data", socketOnData); this.removeListener("end", socketOnEnd); websocket._readyState = WebSocket2.CLOSING; let chunk; if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = void 0; clearTimeout(websocket._closeTimer); if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { websocket.emitClose(); } else { websocket._receiver.on("error", receiverOnFinish); websocket._receiver.on("finish", receiverOnFinish); } } function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket2.CLOSING; websocket._receiver.end(); this.end(); } function socketOnError() { const websocket = this[kWebSocket]; this.removeListener("error", socketOnError); this.on("error", NOOP); if (websocket) { websocket._readyState = WebSocket2.CLOSING; this.destroy(); } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/stream.js var require_stream = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/stream.js"(exports2, module2) { "use strict"; var WebSocket2 = require_websocket(); var { Duplex } = require("stream"); function emitClose(stream) { stream.emit("close"); } function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } function duplexOnError(err2) { this.removeListener("error", duplexOnError); this.destroy(); if (this.listenerCount("error") === 0) { this.emit("error", err2); } } function createWebSocketStream2(ws, options) { let terminateOnDestroy = true; const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on("message", function message(msg, isBinary) { const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; if (!duplex.push(data)) ws.pause(); }); ws.once("error", function error2(err2) { if (duplex.destroyed) return; terminateOnDestroy = false; duplex.destroy(err2); }); ws.once("close", function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function(err2, callback) { if (ws.readyState === ws.CLOSED) { callback(err2); process.nextTick(emitClose, duplex); return; } let called = false; ws.once("error", function error2(err3) { called = true; callback(err3); }); ws.once("close", function close() { if (!called) callback(err2); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws.terminate(); }; duplex._final = function(callback) { if (ws.readyState === ws.CONNECTING) { ws.once("open", function open() { duplex._final(callback); }); return; } if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once("finish", function finish() { callback(); }); ws.close(); } }; duplex._read = function() { if (ws.isPaused) ws.resume(); }; duplex._write = function(chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once("open", function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on("end", duplexOnEnd); duplex.on("error", duplexOnError); return duplex; } module2.exports = createWebSocketStream2; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/subprotocol.js var require_subprotocol = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/subprotocol.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function parse4(header) { const protocols = /* @__PURE__ */ new Set(); let start = -1; let end = -1; let i6 = 0; for (i6; i6 < header.length; i6++) { const code = header.charCodeAt(i6); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i6; } else if (i6 !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i6; } else if (code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i6}`); } if (end === -1) end = i6; const protocol2 = header.slice(start, end); if (protocols.has(protocol2)) { throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); } protocols.add(protocol2); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i6}`); } } if (start === -1 || end !== -1) { throw new SyntaxError("Unexpected end of input"); } const protocol = header.slice(start, i6); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } module2.exports = { parse: parse4 }; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket-server.js var require_websocket_server = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket-server.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var http3 = require("http"); var { Duplex } = require("stream"); var { createHash: createHash4 } = require("crypto"); var extension = require_extension(); var PerMessageDeflate = require_permessage_deflate(); var subprotocol = require_subprotocol(); var WebSocket2 = require_websocket(); var { GUID, kWebSocket } = require_constants(); var keyRegex = /^[+/0-9A-Za-z]{22}==$/; var RUNNING = 0; var CLOSING = 1; var CLOSED = 2; var WebSocketServer2 = class extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` * class to use. It must be the `WebSocket` class or class that extends it * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { allowSynchronousEvents: true, autoPong: true, maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, WebSocket: WebSocket2, ...options }; if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options must be specified' ); } if (options.port != null) { this._server = http3.createServer((req, res) => { const body = http3.STATUS_CODES[426]; res.writeHead(426, { "Content-Length": body.length, "Content-Type": "text/plain" }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, "connection"); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, "listening"), error: this.emit.bind(this, "error"), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) { this.clients = /* @__PURE__ */ new Set(); this._shouldEmitClose = false; } this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Stop the server from accepting new connections and emit the `'close'` event * when all existing connections are closed. * * @param {Function} [cb] A one-time listener for the `'close'` event * @public */ close(cb) { if (this._state === CLOSED) { if (cb) { this.once("close", () => { cb(new Error("The server is not running")); }); } process.nextTick(emitClose, this); return; } if (cb) this.once("close", cb); if (this._state === CLOSING) return; this._state = CLOSING; if (this.options.noServer || this.options.server) { if (this._server) { this._removeListeners(); this._removeListeners = this._server = null; } if (this.clients) { if (!this.clients.size) { process.nextTick(emitClose, this); } else { this._shouldEmitClose = true; } } else { process.nextTick(emitClose, this); } } else { const server = this._server; this._removeListeners(); this._removeListeners = this._server = null; server.close(() => { emitClose(this); }); } } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index6 = req.url.indexOf("?"); const pathname = index6 !== -1 ? req.url.slice(0, index6) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on("error", socketOnError); const key = req.headers["sec-websocket-key"]; const upgrade = req.headers.upgrade; const version = +req.headers["sec-websocket-version"]; if (req.method !== "GET") { const message = "Invalid HTTP method"; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { const message = "Invalid Upgrade header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (key === void 0 || !keyRegex.test(key)) { const message = "Missing or invalid Sec-WebSocket-Key header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (version !== 8 && version !== 13) { const message = "Missing or invalid Sec-WebSocket-Version header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (!this.shouldHandle(req)) { abortHandshake(socket, 400); return; } const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; let protocols = /* @__PURE__ */ new Set(); if (secWebSocketProtocol !== void 0) { try { protocols = subprotocol.parse(secWebSocketProtocol); } catch (err2) { const message = "Invalid Sec-WebSocket-Protocol header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; const extensions = {}; if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = extension.parse(secWebSocketExtensions); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err2) { const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } if (this.options.verifyClient) { const info2 = { origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info2, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade( extensions, key, protocols, req, socket, head, cb ); }); return; } if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401); } this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(extensions, key, protocols, req, socket, head, cb) { if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash4("sha1").update(key + GUID).digest("base64"); const headers = [ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", `Sec-WebSocket-Accept: ${digest}` ]; const ws = new this.options.WebSocket(null, void 0, this.options); if (protocols.size) { const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } this.emit("headers", headers, req); socket.write(headers.concat("\r\n").join("\r\n")); socket.removeListener("error", socketOnError); ws.setSocket(socket, head, { allowSynchronousEvents: this.options.allowSynchronousEvents, maxPayload: this.options.maxPayload, skipUTF8Validation: this.options.skipUTF8Validation }); if (this.clients) { this.clients.add(ws); ws.on("close", () => { this.clients.delete(ws); if (this._shouldEmitClose && !this.clients.size) { process.nextTick(emitClose, this); } }); } cb(ws, req); } }; module2.exports = WebSocketServer2; function addListeners(server, map2) { for (const event of Object.keys(map2)) server.on(event, map2[event]); return function removeListeners() { for (const event of Object.keys(map2)) { server.removeListener(event, map2[event]); } }; } function emitClose(server) { server._state = CLOSED; server.emit("close"); } function socketOnError() { this.destroy(); } function abortHandshake(socket, code, message, headers) { message = message || http3.STATUS_CODES[code]; headers = { Connection: "close", "Content-Type": "text/html", "Content-Length": Buffer.byteLength(message), ...headers }; socket.once("finish", socket.destroy); socket.end( `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r ` + Object.keys(headers).map((h6) => `${h6}: ${headers[h6]}`).join("\r\n") + "\r\n\r\n" + message ); } function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { if (server.listenerCount("wsClientError")) { const err2 = new Error(message); Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError); server.emit("wsClientError", err2, socket, req); } else { abortHandshake(socket, code, message); } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs var import_stream2, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default; var init_wrapper = __esm({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs"() { "use strict"; import_stream2 = __toESM(require_stream(), 1); import_receiver = __toESM(require_receiver(), 1); import_sender = __toESM(require_sender(), 1); import_websocket = __toESM(require_websocket(), 1); import_websocket_server = __toESM(require_websocket_server(), 1); wrapper_default = import_websocket.default; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js var require_constants2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports2, module2) { "use strict"; var SEMVER_SPEC_VERSION = "2.0.0"; var MAX_LENGTH = 256; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; var MAX_SAFE_COMPONENT_LENGTH = 16; var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; var RELEASE_TYPES = [ "major", "premajor", "minor", "preminor", "patch", "prepatch", "prerelease" ]; module2.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 1, FLAG_LOOSE: 2 }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js var require_debug = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports2, module2) { "use strict"; var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { }; module2.exports = debug; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js var require_re = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports2, module2) { "use strict"; var { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = require_constants2(); var debug = require_debug(); exports2 = module2.exports = {}; var re = exports2.re = []; var safeRe = exports2.safeRe = []; var src = exports2.src = []; var safeSrc = exports2.safeSrc = []; var t6 = exports2.t = {}; var R = 0; var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; var safeRegexReplacements = [ ["\\s", 1], ["\\d", MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] ]; var makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); } return value; }; var createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value); const index6 = R++; debug(name, index6, value); t6[name] = index6; src[index6] = value; safeSrc[index6] = safe; re[index6] = new RegExp(value, isGlobal ? "g" : void 0); safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0); }; createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); createToken("MAINVERSION", `(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})`); createToken("MAINVERSIONLOOSE", `(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASEIDENTIFIER", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIER]})`); createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASE", `(?:-(${src[t6.PRERELEASEIDENTIFIER]}(?:\\.${src[t6.PRERELEASEIDENTIFIER]})*))`); createToken("PRERELEASELOOSE", `(?:-?(${src[t6.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t6.PRERELEASEIDENTIFIERLOOSE]})*))`); createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); createToken("BUILD", `(?:\\+(${src[t6.BUILDIDENTIFIER]}(?:\\.${src[t6.BUILDIDENTIFIER]})*))`); createToken("FULLPLAIN", `v?${src[t6.MAINVERSION]}${src[t6.PRERELEASE]}?${src[t6.BUILD]}?`); createToken("FULL", `^${src[t6.FULLPLAIN]}$`); createToken("LOOSEPLAIN", `[v=\\s]*${src[t6.MAINVERSIONLOOSE]}${src[t6.PRERELEASELOOSE]}?${src[t6.BUILD]}?`); createToken("LOOSE", `^${src[t6.LOOSEPLAIN]}$`); createToken("GTLT", "((?:<|>)?=?)"); createToken("XRANGEIDENTIFIERLOOSE", `${src[t6.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); createToken("XRANGEIDENTIFIER", `${src[t6.NUMERICIDENTIFIER]}|x|X|\\*`); createToken("XRANGEPLAIN", `[v=\\s]*(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:${src[t6.PRERELEASE]})?${src[t6.BUILD]}?)?)?`); createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:${src[t6.PRERELEASELOOSE]})?${src[t6.BUILD]}?)?)?`); createToken("XRANGE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAIN]}$`); createToken("XRANGELOOSE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAINLOOSE]}$`); createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); createToken("COERCE", `${src[t6.COERCEPLAIN]}(?:$|[^\\d])`); createToken("COERCEFULL", src[t6.COERCEPLAIN] + `(?:${src[t6.PRERELEASE]})?(?:${src[t6.BUILD]})?(?:$|[^\\d])`); createToken("COERCERTL", src[t6.COERCE], true); createToken("COERCERTLFULL", src[t6.COERCEFULL], true); createToken("LONETILDE", "(?:~>?)"); createToken("TILDETRIM", `(\\s*)${src[t6.LONETILDE]}\\s+`, true); exports2.tildeTrimReplace = "$1~"; createToken("TILDE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAIN]}$`); createToken("TILDELOOSE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAINLOOSE]}$`); createToken("LONECARET", "(?:\\^)"); createToken("CARETTRIM", `(\\s*)${src[t6.LONECARET]}\\s+`, true); exports2.caretTrimReplace = "$1^"; createToken("CARET", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAIN]}$`); createToken("CARETLOOSE", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAINLOOSE]}$`); createToken("COMPARATORLOOSE", `^${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]})$|^$`); createToken("COMPARATOR", `^${src[t6.GTLT]}\\s*(${src[t6.FULLPLAIN]})$|^$`); createToken("COMPARATORTRIM", `(\\s*)${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]}|${src[t6.XRANGEPLAIN]})`, true); exports2.comparatorTrimReplace = "$1$2$3"; createToken("HYPHENRANGE", `^\\s*(${src[t6.XRANGEPLAIN]})\\s+-\\s+(${src[t6.XRANGEPLAIN]})\\s*$`); createToken("HYPHENRANGELOOSE", `^\\s*(${src[t6.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t6.XRANGEPLAINLOOSE]})\\s*$`); createToken("STAR", "(<|>)?=?\\s*\\*"); createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js var require_parse_options = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports2, module2) { "use strict"; var looseOption = Object.freeze({ loose: true }); var emptyOpts = Object.freeze({}); var parseOptions = (options) => { if (!options) { return emptyOpts; } if (typeof options !== "object") { return looseOption; } return options; }; module2.exports = parseOptions; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js var require_identifiers = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports2, module2) { "use strict"; var numeric = /^[0-9]+$/; var compareIdentifiers = (a5, b5) => { const anum = numeric.test(a5); const bnum = numeric.test(b5); if (anum && bnum) { a5 = +a5; b5 = +b5; } return a5 === b5 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a5 < b5 ? -1 : 1; }; var rcompareIdentifiers = (a5, b5) => compareIdentifiers(b5, a5); module2.exports = { compareIdentifiers, rcompareIdentifiers }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js var require_semver = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports2, module2) { "use strict"; var debug = require_debug(); var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants2(); var { safeRe: re, t: t6 } = require_re(); var parseOptions = require_parse_options(); var { compareIdentifiers } = require_identifiers(); var SemVer = class _SemVer { constructor(version, options) { options = parseOptions(options); if (version instanceof _SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== "string") { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ); } debug("SemVer", version, options); this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; const m6 = version.trim().match(options.loose ? re[t6.LOOSE] : re[t6.FULL]); if (!m6) { throw new TypeError(`Invalid Version: ${version}`); } this.raw = version; this.major = +m6[1]; this.minor = +m6[2]; this.patch = +m6[3]; if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError("Invalid major version"); } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError("Invalid minor version"); } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError("Invalid patch version"); } if (!m6[4]) { this.prerelease = []; } else { this.prerelease = m6[4].split(".").map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER) { return num; } } return id; }); } this.build = m6[5] ? m6[5].split(".") : []; this.format(); } format() { this.version = `${this.major}.${this.minor}.${this.patch}`; if (this.prerelease.length) { this.version += `-${this.prerelease.join(".")}`; } return this.version; } toString() { return this.version; } compare(other) { debug("SemVer.compare", this.version, this.options, other); if (!(other instanceof _SemVer)) { if (typeof other === "string" && other === this.version) { return 0; } other = new _SemVer(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof _SemVer)) { other = new _SemVer(other, this.options); } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); } comparePre(other) { if (!(other instanceof _SemVer)) { other = new _SemVer(other, this.options); } if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i6 = 0; do { const a5 = this.prerelease[i6]; const b5 = other.prerelease[i6]; debug("prerelease compare", i6, a5, b5); if (a5 === void 0 && b5 === void 0) { return 0; } else if (b5 === void 0) { return 1; } else if (a5 === void 0) { return -1; } else if (a5 === b5) { continue; } else { return compareIdentifiers(a5, b5); } } while (++i6); } compareBuild(other) { if (!(other instanceof _SemVer)) { other = new _SemVer(other, this.options); } let i6 = 0; do { const a5 = this.build[i6]; const b5 = other.build[i6]; debug("build compare", i6, a5, b5); if (a5 === void 0 && b5 === void 0) { return 0; } else if (b5 === void 0) { return 1; } else if (a5 === void 0) { return -1; } else if (a5 === b5) { continue; } else { return compareIdentifiers(a5, b5); } } while (++i6); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release2, identifier, identifierBase) { if (release2.startsWith("pre")) { if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } if (identifier) { const match2 = `-${identifier}`.match(this.options.loose ? re[t6.PRERELEASELOOSE] : re[t6.PRERELEASE]); if (!match2 || match2[1] !== identifier) { throw new Error(`invalid identifier: ${identifier}`); } } } switch (release2) { case "premajor": this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc("pre", identifier, identifierBase); break; case "preminor": this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc("pre", identifier, identifierBase); break; case "prepatch": this.prerelease.length = 0; this.inc("patch", identifier, identifierBase); this.inc("pre", identifier, identifierBase); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case "prerelease": if (this.prerelease.length === 0) { this.inc("patch", identifier, identifierBase); } this.inc("pre", identifier, identifierBase); break; case "release": if (this.prerelease.length === 0) { throw new Error(`version ${this.raw} is not a prerelease`); } this.prerelease.length = 0; break; case "major": if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case "minor": if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case "patch": if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case "pre": { const base = Number(identifierBase) ? 1 : 0; if (this.prerelease.length === 0) { this.prerelease = [base]; } else { let i6 = this.prerelease.length; while (--i6 >= 0) { if (typeof this.prerelease[i6] === "number") { this.prerelease[i6]++; i6 = -2; } } if (i6 === -1) { if (identifier === this.prerelease.join(".") && identifierBase === false) { throw new Error("invalid increment argument: identifier already exists"); } this.prerelease.push(base); } } if (identifier) { let prerelease = [identifier, base]; if (identifierBase === false) { prerelease = [identifier]; } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease; } } else { this.prerelease = prerelease; } } break; } default: throw new Error(`invalid increment argument: ${release2}`); } this.raw = this.format(); if (this.build.length) { this.raw += `+${this.build.join(".")}`; } return this; } }; module2.exports = SemVer; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js var require_parse = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var parse4 = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version; } try { return new SemVer(version, options); } catch (er) { if (!throwErrors) { return null; } throw er; } }; module2.exports = parse4; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js var require_valid = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports2, module2) { "use strict"; var parse4 = require_parse(); var valid = (version, options) => { const v6 = parse4(version, options); return v6 ? v6.version : null; }; module2.exports = valid; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js var require_clean = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js"(exports2, module2) { "use strict"; var parse4 = require_parse(); var clean = (version, options) => { const s6 = parse4(version.trim().replace(/^[=v]+/, ""), options); return s6 ? s6.version : null; }; module2.exports = clean; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js var require_inc = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var inc = (version, release2, options, identifier, identifierBase) => { if (typeof options === "string") { identifierBase = identifier; identifier = options; options = void 0; } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release2, identifier, identifierBase).version; } catch (er) { return null; } }; module2.exports = inc; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js var require_diff = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js"(exports2, module2) { "use strict"; var parse4 = require_parse(); var diff2 = (version1, version2) => { const v1 = parse4(version1, null, true); const v22 = parse4(version2, null, true); const comparison = v1.compare(v22); if (comparison === 0) { return null; } const v1Higher = comparison > 0; const highVersion = v1Higher ? v1 : v22; const lowVersion = v1Higher ? v22 : v1; const highHasPre = !!highVersion.prerelease.length; const lowHasPre = !!lowVersion.prerelease.length; if (lowHasPre && !highHasPre) { if (!lowVersion.patch && !lowVersion.minor) { return "major"; } if (lowVersion.compareMain(highVersion) === 0) { if (lowVersion.minor && !lowVersion.patch) { return "minor"; } return "patch"; } } const prefix2 = highHasPre ? "pre" : ""; if (v1.major !== v22.major) { return prefix2 + "major"; } if (v1.minor !== v22.minor) { return prefix2 + "minor"; } if (v1.patch !== v22.patch) { return prefix2 + "patch"; } return "prerelease"; }; module2.exports = diff2; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js var require_major = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var major = (a5, loose) => new SemVer(a5, loose).major; module2.exports = major; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js var require_minor = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var minor = (a5, loose) => new SemVer(a5, loose).minor; module2.exports = minor; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js var require_patch = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var patch = (a5, loose) => new SemVer(a5, loose).patch; module2.exports = patch; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js var require_prerelease = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js"(exports2, module2) { "use strict"; var parse4 = require_parse(); var prerelease = (version, options) => { const parsed = parse4(version, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; }; module2.exports = prerelease; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js var require_compare = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var compare = (a5, b5, loose) => new SemVer(a5, loose).compare(new SemVer(b5, loose)); module2.exports = compare; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js var require_rcompare = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js"(exports2, module2) { "use strict"; var compare = require_compare(); var rcompare = (a5, b5, loose) => compare(b5, a5, loose); module2.exports = rcompare; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js var require_compare_loose = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js"(exports2, module2) { "use strict"; var compare = require_compare(); var compareLoose = (a5, b5) => compare(a5, b5, true); module2.exports = compareLoose; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js var require_compare_build = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var compareBuild = (a5, b5, loose) => { const versionA = new SemVer(a5, loose); const versionB = new SemVer(b5, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB); }; module2.exports = compareBuild; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js var require_sort = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js"(exports2, module2) { "use strict"; var compareBuild = require_compare_build(); var sort = (list, loose) => list.sort((a5, b5) => compareBuild(a5, b5, loose)); module2.exports = sort; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js var require_rsort = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js"(exports2, module2) { "use strict"; var compareBuild = require_compare_build(); var rsort = (list, loose) => list.sort((a5, b5) => compareBuild(b5, a5, loose)); module2.exports = rsort; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js var require_gt = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js"(exports2, module2) { "use strict"; var compare = require_compare(); var gt = (a5, b5, loose) => compare(a5, b5, loose) > 0; module2.exports = gt; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js var require_lt = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js"(exports2, module2) { "use strict"; var compare = require_compare(); var lt = (a5, b5, loose) => compare(a5, b5, loose) < 0; module2.exports = lt; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js var require_eq = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js"(exports2, module2) { "use strict"; var compare = require_compare(); var eq = (a5, b5, loose) => compare(a5, b5, loose) === 0; module2.exports = eq; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js var require_neq = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js"(exports2, module2) { "use strict"; var compare = require_compare(); var neq = (a5, b5, loose) => compare(a5, b5, loose) !== 0; module2.exports = neq; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js var require_gte = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js"(exports2, module2) { "use strict"; var compare = require_compare(); var gte = (a5, b5, loose) => compare(a5, b5, loose) >= 0; module2.exports = gte; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js var require_lte = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js"(exports2, module2) { "use strict"; var compare = require_compare(); var lte = (a5, b5, loose) => compare(a5, b5, loose) <= 0; module2.exports = lte; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js var require_cmp = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js"(exports2, module2) { "use strict"; var eq = require_eq(); var neq = require_neq(); var gt = require_gt(); var gte = require_gte(); var lt = require_lt(); var lte = require_lte(); var cmp = (a5, op, b5, loose) => { switch (op) { case "===": if (typeof a5 === "object") { a5 = a5.version; } if (typeof b5 === "object") { b5 = b5.version; } return a5 === b5; case "!==": if (typeof a5 === "object") { a5 = a5.version; } if (typeof b5 === "object") { b5 = b5.version; } return a5 !== b5; case "": case "=": case "==": return eq(a5, b5, loose); case "!=": return neq(a5, b5, loose); case ">": return gt(a5, b5, loose); case ">=": return gte(a5, b5, loose); case "<": return lt(a5, b5, loose); case "<=": return lte(a5, b5, loose); default: throw new TypeError(`Invalid operator: ${op}`); } }; module2.exports = cmp; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js var require_coerce = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var parse4 = require_parse(); var { safeRe: re, t: t6 } = require_re(); var coerce2 = (version, options) => { if (version instanceof SemVer) { return version; } if (typeof version === "number") { version = String(version); } if (typeof version !== "string") { return null; } options = options || {}; let match2 = null; if (!options.rtl) { match2 = version.match(options.includePrerelease ? re[t6.COERCEFULL] : re[t6.COERCE]); } else { const coerceRtlRegex = options.includePrerelease ? re[t6.COERCERTLFULL] : re[t6.COERCERTL]; let next; while ((next = coerceRtlRegex.exec(version)) && (!match2 || match2.index + match2[0].length !== version.length)) { if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) { match2 = next; } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; } coerceRtlRegex.lastIndex = -1; } if (match2 === null) { return null; } const major = match2[2]; const minor = match2[3] || "0"; const patch = match2[4] || "0"; const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : ""; const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : ""; return parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options); }; module2.exports = coerce2; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js var require_lrucache = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js"(exports2, module2) { "use strict"; var LRUCache = class { constructor() { this.max = 1e3; this.map = /* @__PURE__ */ new Map(); } get(key) { const value = this.map.get(key); if (value === void 0) { return void 0; } else { this.map.delete(key); this.map.set(key, value); return value; } } delete(key) { return this.map.delete(key); } set(key, value) { const deleted = this.delete(key); if (!deleted && value !== void 0) { if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value; this.delete(firstKey); } this.map.set(key, value); } return this; } }; module2.exports = LRUCache; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js var require_range = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js"(exports2, module2) { "use strict"; var SPACE_CHARACTERS = /\s+/g; var Range = class _Range { constructor(range, options) { options = parseOptions(options); if (range instanceof _Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range; } else { return new _Range(range.raw, options); } } if (range instanceof Comparator) { this.raw = range.value; this.set = [[range]]; this.formatted = void 0; return this; } this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; this.raw = range.trim().replace(SPACE_CHARACTERS, " "); this.set = this.raw.split("||").map((r6) => this.parseRange(r6.trim())).filter((c5) => c5.length); if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`); } if (this.set.length > 1) { const first = this.set[0]; this.set = this.set.filter((c5) => !isNullSet(c5[0])); if (this.set.length === 0) { this.set = [first]; } else if (this.set.length > 1) { for (const c5 of this.set) { if (c5.length === 1 && isAny(c5[0])) { this.set = [c5]; break; } } } } this.formatted = void 0; } get range() { if (this.formatted === void 0) { this.formatted = ""; for (let i6 = 0; i6 < this.set.length; i6++) { if (i6 > 0) { this.formatted += "||"; } const comps = this.set[i6]; for (let k5 = 0; k5 < comps.length; k5++) { if (k5 > 0) { this.formatted += " "; } this.formatted += comps[k5].toString().trim(); } } } return this.formatted; } format() { return this.range; } toString() { return this.range; } parseRange(range) { const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); const memoKey = memoOpts + ":" + range; const cached = cache5.get(memoKey); if (cached) { return cached; } const loose = this.options.loose; const hr = loose ? re[t6.HYPHENRANGELOOSE] : re[t6.HYPHENRANGE]; range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); debug("hyphen replace", range); range = range.replace(re[t6.COMPARATORTRIM], comparatorTrimReplace); debug("comparator trim", range); range = range.replace(re[t6.TILDETRIM], tildeTrimReplace); debug("tilde trim", range); range = range.replace(re[t6.CARETTRIM], caretTrimReplace); debug("caret trim", range); let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); if (loose) { rangeList = rangeList.filter((comp) => { debug("loose invalid filter", comp, this.options); return !!comp.match(re[t6.COMPARATORLOOSE]); }); } debug("range list", rangeList); const rangeMap = /* @__PURE__ */ new Map(); const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); for (const comp of comparators) { if (isNullSet(comp)) { return [comp]; } rangeMap.set(comp.value, comp); } if (rangeMap.size > 1 && rangeMap.has("")) { rangeMap.delete(""); } const result = [...rangeMap.values()]; cache5.set(memoKey, result); return result; } intersects(range, options) { if (!(range instanceof _Range)) { throw new TypeError("a Range is required"); } return this.set.some((thisComparators) => { return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options); }); }); }); }); } // if ANY of the sets match ALL of its comparators, then pass test(version) { if (!version) { return false; } if (typeof version === "string") { try { version = new SemVer(version, this.options); } catch (er) { return false; } } for (let i6 = 0; i6 < this.set.length; i6++) { if (testSet(this.set[i6], version, this.options)) { return true; } } return false; } }; module2.exports = Range; var LRU = require_lrucache(); var cache5 = new LRU(); var parseOptions = require_parse_options(); var Comparator = require_comparator(); var debug = require_debug(); var SemVer = require_semver(); var { safeRe: re, t: t6, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = require_re(); var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants2(); var isNullSet = (c5) => c5.value === "<0.0.0-0"; var isAny = (c5) => c5.value === ""; var isSatisfiable = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options); }); testComparator = remainingComparators.pop(); } return result; }; var parseComparator = (comp, options) => { debug("comp", comp, options); comp = replaceCarets(comp, options); debug("caret", comp); comp = replaceTildes(comp, options); debug("tildes", comp); comp = replaceXRanges(comp, options); debug("xrange", comp); comp = replaceStars(comp, options); debug("stars", comp); return comp; }; var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; var replaceTildes = (comp, options) => { return comp.trim().split(/\s+/).map((c5) => replaceTilde(c5, options)).join(" "); }; var replaceTilde = (comp, options) => { const r6 = options.loose ? re[t6.TILDELOOSE] : re[t6.TILDE]; return comp.replace(r6, (_3, M, m6, p5, pr) => { debug("tilde", comp, _3, M, m6, p5, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m6)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; } else if (isX(p5)) { ret = `>=${M}.${m6}.0 <${M}.${+m6 + 1}.0-0`; } else if (pr) { debug("replaceTilde pr", pr); ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`; } else { ret = `>=${M}.${m6}.${p5} <${M}.${+m6 + 1}.0-0`; } debug("tilde return", ret); return ret; }); }; var replaceCarets = (comp, options) => { return comp.trim().split(/\s+/).map((c5) => replaceCaret(c5, options)).join(" "); }; var replaceCaret = (comp, options) => { debug("caret", comp, options); const r6 = options.loose ? re[t6.CARETLOOSE] : re[t6.CARET]; const z2 = options.includePrerelease ? "-0" : ""; return comp.replace(r6, (_3, M, m6, p5, pr) => { debug("caret", comp, _3, M, m6, p5, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m6)) { ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`; } else if (isX(p5)) { if (M === "0") { ret = `>=${M}.${m6}.0${z2} <${M}.${+m6 + 1}.0-0`; } else { ret = `>=${M}.${m6}.0${z2} <${+M + 1}.0.0-0`; } } else if (pr) { debug("replaceCaret pr", pr); if (M === "0") { if (m6 === "0") { ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${m6}.${+p5 + 1}-0`; } else { ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`; } } else { ret = `>=${M}.${m6}.${p5}-${pr} <${+M + 1}.0.0-0`; } } else { debug("no pr"); if (M === "0") { if (m6 === "0") { ret = `>=${M}.${m6}.${p5}${z2} <${M}.${m6}.${+p5 + 1}-0`; } else { ret = `>=${M}.${m6}.${p5}${z2} <${M}.${+m6 + 1}.0-0`; } } else { ret = `>=${M}.${m6}.${p5} <${+M + 1}.0.0-0`; } } debug("caret return", ret); return ret; }); }; var replaceXRanges = (comp, options) => { debug("replaceXRanges", comp, options); return comp.split(/\s+/).map((c5) => replaceXRange(c5, options)).join(" "); }; var replaceXRange = (comp, options) => { comp = comp.trim(); const r6 = options.loose ? re[t6.XRANGELOOSE] : re[t6.XRANGE]; return comp.replace(r6, (ret, gtlt, M, m6, p5, pr) => { debug("xRange", comp, ret, gtlt, M, m6, p5, pr); const xM = isX(M); const xm = xM || isX(m6); const xp = xm || isX(p5); const anyX = xp; if (gtlt === "=" && anyX) { gtlt = ""; } pr = options.includePrerelease ? "-0" : ""; if (xM) { if (gtlt === ">" || gtlt === "<") { ret = "<0.0.0-0"; } else { ret = "*"; } } else if (gtlt && anyX) { if (xm) { m6 = 0; } p5 = 0; if (gtlt === ">") { gtlt = ">="; if (xm) { M = +M + 1; m6 = 0; p5 = 0; } else { m6 = +m6 + 1; p5 = 0; } } else if (gtlt === "<=") { gtlt = "<"; if (xm) { M = +M + 1; } else { m6 = +m6 + 1; } } if (gtlt === "<") { pr = "-0"; } ret = `${gtlt + M}.${m6}.${p5}${pr}`; } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; } else if (xp) { ret = `>=${M}.${m6}.0${pr} <${M}.${+m6 + 1}.0-0`; } debug("xRange return", ret); return ret; }); }; var replaceStars = (comp, options) => { debug("replaceStars", comp, options); return comp.trim().replace(re[t6.STAR], ""); }; var replaceGTE0 = (comp, options) => { debug("replaceGTE0", comp, options); return comp.trim().replace(re[options.includePrerelease ? t6.GTE0PRE : t6.GTE0], ""); }; var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = ""; } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? "-0" : ""}`; } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; } else if (fpr) { from = `>=${from}`; } else { from = `>=${from}${incPr ? "-0" : ""}`; } if (isX(tM)) { to = ""; } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0`; } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0`; } else { to = `<=${to}`; } return `${from} ${to}`.trim(); }; var testSet = (set, version, options) => { for (let i6 = 0; i6 < set.length; i6++) { if (!set[i6].test(version)) { return false; } } if (version.prerelease.length && !options.includePrerelease) { for (let i6 = 0; i6 < set.length; i6++) { debug(set[i6].semver); if (set[i6].semver === Comparator.ANY) { continue; } if (set[i6].semver.prerelease.length > 0) { const allowed = set[i6].semver; if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true; } } } return false; } return true; }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js var require_comparator = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js"(exports2, module2) { "use strict"; var ANY = Symbol("SemVer ANY"); var Comparator = class _Comparator { static get ANY() { return ANY; } constructor(comp, options) { options = parseOptions(options); if (comp instanceof _Comparator) { if (comp.loose === !!options.loose) { return comp; } else { comp = comp.value; } } comp = comp.trim().split(/\s+/).join(" "); debug("comparator", comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); if (this.semver === ANY) { this.value = ""; } else { this.value = this.operator + this.semver.version; } debug("comp", this); } parse(comp) { const r6 = this.options.loose ? re[t6.COMPARATORLOOSE] : re[t6.COMPARATOR]; const m6 = comp.match(r6); if (!m6) { throw new TypeError(`Invalid comparator: ${comp}`); } this.operator = m6[1] !== void 0 ? m6[1] : ""; if (this.operator === "=") { this.operator = ""; } if (!m6[2]) { this.semver = ANY; } else { this.semver = new SemVer(m6[2], this.options.loose); } } toString() { return this.value; } test(version) { debug("Comparator.test", version, this.options.loose); if (this.semver === ANY || version === ANY) { return true; } if (typeof version === "string") { try { version = new SemVer(version, this.options); } catch (er) { return false; } } return cmp(version, this.operator, this.semver, this.options); } intersects(comp, options) { if (!(comp instanceof _Comparator)) { throw new TypeError("a Comparator is required"); } if (this.operator === "") { if (this.value === "") { return true; } return new Range(comp.value, options).test(this.value); } else if (comp.operator === "") { if (comp.value === "") { return true; } return new Range(this.value, options).test(comp.semver); } options = parseOptions(options); if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { return false; } if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { return false; } if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { return true; } if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { return true; } if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { return true; } if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { return true; } if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { return true; } return false; } }; module2.exports = Comparator; var parseOptions = require_parse_options(); var { safeRe: re, t: t6 } = require_re(); var cmp = require_cmp(); var debug = require_debug(); var SemVer = require_semver(); var Range = require_range(); } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js var require_satisfies = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js"(exports2, module2) { "use strict"; var Range = require_range(); var satisfies = (version, range, options) => { try { range = new Range(range, options); } catch (er) { return false; } return range.test(version); }; module2.exports = satisfies; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js var require_to_comparators = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js"(exports2, module2) { "use strict"; var Range = require_range(); var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c5) => c5.value).join(" ").trim().split(" ")); module2.exports = toComparators; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js var require_max_satisfying = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var maxSatisfying = (versions2, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions2.forEach((v6) => { if (rangeObj.test(v6)) { if (!max || maxSV.compare(v6) === -1) { max = v6; maxSV = new SemVer(max, options); } } }); return max; }; module2.exports = maxSatisfying; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js var require_min_satisfying = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var minSatisfying = (versions2, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions2.forEach((v6) => { if (rangeObj.test(v6)) { if (!min || minSV.compare(v6) === 1) { min = v6; minSV = new SemVer(min, options); } } }); return min; }; module2.exports = minSatisfying; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js var require_min_version = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var gt = require_gt(); var minVersion = (range, loose) => { range = new Range(range, loose); let minver = new SemVer("0.0.0"); if (range.test(minver)) { return minver; } minver = new SemVer("0.0.0-0"); if (range.test(minver)) { return minver; } minver = null; for (let i6 = 0; i6 < range.set.length; ++i6) { const comparators = range.set[i6]; let setMin = null; comparators.forEach((comparator) => { const compver = new SemVer(comparator.semver.version); switch (comparator.operator) { case ">": if (compver.prerelease.length === 0) { compver.patch++; } else { compver.prerelease.push(0); } compver.raw = compver.format(); /* fallthrough */ case "": case ">=": if (!setMin || gt(compver, setMin)) { setMin = compver; } break; case "<": case "<=": break; /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`); } }); if (setMin && (!minver || gt(minver, setMin))) { minver = setMin; } } if (minver && range.test(minver)) { return minver; } return null; }; module2.exports = minVersion; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js var require_valid2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js"(exports2, module2) { "use strict"; var Range = require_range(); var validRange = (range, options) => { try { return new Range(range, options).range || "*"; } catch (er) { return null; } }; module2.exports = validRange; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js var require_outside = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Comparator = require_comparator(); var { ANY } = Comparator; var Range = require_range(); var satisfies = require_satisfies(); var gt = require_gt(); var lt = require_lt(); var lte = require_lte(); var gte = require_gte(); var outside = (version, range, hilo, options) => { version = new SemVer(version, options); range = new Range(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case ">": gtfn = gt; ltefn = lte; ltfn = lt; comp = ">"; ecomp = ">="; break; case "<": gtfn = lt; ltefn = gte; ltfn = gt; comp = "<"; ecomp = "<="; break; default: throw new TypeError('Must provide a hilo val of "<" or ">"'); } if (satisfies(version, range, options)) { return false; } for (let i6 = 0; i6 < range.set.length; ++i6) { const comparators = range.set[i6]; let high = null; let low = null; comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator(">=0.0.0"); } high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, options)) { high = comparator; } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator; } }); if (high.operator === comp || high.operator === ecomp) { return false; } if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false; } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false; } } return true; }; module2.exports = outside; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js var require_gtr = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js"(exports2, module2) { "use strict"; var outside = require_outside(); var gtr = (version, range, options) => outside(version, range, ">", options); module2.exports = gtr; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js var require_ltr = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js"(exports2, module2) { "use strict"; var outside = require_outside(); var ltr = (version, range, options) => outside(version, range, "<", options); module2.exports = ltr; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js var require_intersects = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js"(exports2, module2) { "use strict"; var Range = require_range(); var intersects = (r1, r22, options) => { r1 = new Range(r1, options); r22 = new Range(r22, options); return r1.intersects(r22, options); }; module2.exports = intersects; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js var require_simplify = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js"(exports2, module2) { "use strict"; var satisfies = require_satisfies(); var compare = require_compare(); module2.exports = (versions2, range, options) => { const set = []; let first = null; let prev = null; const v6 = versions2.sort((a5, b5) => compare(a5, b5, options)); for (const version of v6) { const included = satisfies(version, range, options); if (included) { prev = version; if (!first) { first = version; } } else { if (prev) { set.push([first, prev]); } prev = null; first = null; } } if (first) { set.push([first, null]); } const ranges = []; for (const [min, max] of set) { if (min === max) { ranges.push(min); } else if (!max && min === v6[0]) { ranges.push("*"); } else if (!max) { ranges.push(`>=${min}`); } else if (min === v6[0]) { ranges.push(`<=${max}`); } else { ranges.push(`${min} - ${max}`); } } const simplified = ranges.join(" || "); const original = typeof range.raw === "string" ? range.raw : String(range); return simplified.length < original.length ? simplified : range; }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js var require_subset = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js"(exports2, module2) { "use strict"; var Range = require_range(); var Comparator = require_comparator(); var { ANY } = Comparator; var satisfies = require_satisfies(); var compare = require_compare(); var subset = (sub, dom, options = {}) => { if (sub === dom) { return true; } sub = new Range(sub, options); dom = new Range(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) { continue OUTER; } } if (sawNonNull) { return false; } } return true; }; var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; var minimumVersion = [new Comparator(">=0.0.0")]; var simpleSubset = (sub, dom, options) => { if (sub === dom) { return true; } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true; } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease; } else { sub = minimumVersion; } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true; } else { dom = minimumVersion; } } const eqSet = /* @__PURE__ */ new Set(); let gt, lt; for (const c5 of sub) { if (c5.operator === ">" || c5.operator === ">=") { gt = higherGT(gt, c5, options); } else if (c5.operator === "<" || c5.operator === "<=") { lt = lowerLT(lt, c5, options); } else { eqSet.add(c5.semver); } } if (eqSet.size > 1) { return null; } let gtltComp; if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options); if (gtltComp > 0) { return null; } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { return null; } } for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null; } if (lt && !satisfies(eq, String(lt), options)) { return null; } for (const c5 of dom) { if (!satisfies(eq, String(c5), options)) { return false; } } return true; } let higher, lower2; let hasDomLT, hasDomGT; let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false; } for (const c5 of dom) { hasDomGT = hasDomGT || c5.operator === ">" || c5.operator === ">="; hasDomLT = hasDomLT || c5.operator === "<" || c5.operator === "<="; if (gt) { if (needDomGTPre) { if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomGTPre.major && c5.semver.minor === needDomGTPre.minor && c5.semver.patch === needDomGTPre.patch) { needDomGTPre = false; } } if (c5.operator === ">" || c5.operator === ">=") { higher = higherGT(gt, c5, options); if (higher === c5 && higher !== gt) { return false; } } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c5), options)) { return false; } } if (lt) { if (needDomLTPre) { if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomLTPre.major && c5.semver.minor === needDomLTPre.minor && c5.semver.patch === needDomLTPre.patch) { needDomLTPre = false; } } if (c5.operator === "<" || c5.operator === "<=") { lower2 = lowerLT(lt, c5, options); if (lower2 === c5 && lower2 !== lt) { return false; } } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c5), options)) { return false; } } if (!c5.operator && (lt || gt) && gtltComp !== 0) { return false; } } if (gt && hasDomLT && !lt && gtltComp !== 0) { return false; } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false; } if (needDomGTPre || needDomLTPre) { return false; } return true; }; var higherGT = (a5, b5, options) => { if (!a5) { return b5; } const comp = compare(a5.semver, b5.semver, options); return comp > 0 ? a5 : comp < 0 ? b5 : b5.operator === ">" && a5.operator === ">=" ? b5 : a5; }; var lowerLT = (a5, b5, options) => { if (!a5) { return b5; } const comp = compare(a5.semver, b5.semver, options); return comp < 0 ? a5 : comp > 0 ? b5 : b5.operator === "<" && a5.operator === "<=" ? b5 : a5; }; module2.exports = subset; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js var require_semver2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js"(exports2, module2) { "use strict"; var internalRe = require_re(); var constants = require_constants2(); var SemVer = require_semver(); var identifiers = require_identifiers(); var parse4 = require_parse(); var valid = require_valid(); var clean = require_clean(); var inc = require_inc(); var diff2 = require_diff(); var major = require_major(); var minor = require_minor(); var patch = require_patch(); var prerelease = require_prerelease(); var compare = require_compare(); var rcompare = require_rcompare(); var compareLoose = require_compare_loose(); var compareBuild = require_compare_build(); var sort = require_sort(); var rsort = require_rsort(); var gt = require_gt(); var lt = require_lt(); var eq = require_eq(); var neq = require_neq(); var gte = require_gte(); var lte = require_lte(); var cmp = require_cmp(); var coerce2 = require_coerce(); var Comparator = require_comparator(); var Range = require_range(); var satisfies = require_satisfies(); var toComparators = require_to_comparators(); var maxSatisfying = require_max_satisfying(); var minSatisfying = require_min_satisfying(); var minVersion = require_min_version(); var validRange = require_valid2(); var outside = require_outside(); var gtr = require_gtr(); var ltr = require_ltr(); var intersects = require_intersects(); var simplifyRange = require_simplify(); var subset = require_subset(); module2.exports = { parse: parse4, valid, clean, inc, diff: diff2, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce: coerce2, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers }; } }); // src/cli/utils.ts var import_semver, checkPackage, assertPackages; var init_utils4 = __esm({ "src/cli/utils.ts"() { "use strict"; import_semver = __toESM(require_semver2()); init_views(); checkPackage = async (it) => { try { require(it); return true; } catch (e6) { return false; } }; assertPackages = async (...pkgs) => { try { for (let i6 = 0; i6 < pkgs.length; i6++) { const it = pkgs[i6]; require(it); } } catch (e6) { err( `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}` ); process.exit(1); } }; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig; var init_httpExtensionConfiguration = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() { "use strict"; getHttpHandlerExtensionConfiguration = (runtimeConfig) => { return { setHttpHandler(handler) { runtimeConfig.httpHandler = handler; }, httpHandler() { return runtimeConfig.httpHandler; }, updateHttpClientConfig(key, value) { runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); }, httpHandlerConfigs() { return runtimeConfig.httpHandler.httpHandlerConfigs(); } }; }; resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { return { httpHandler: httpHandlerExtensionConfiguration.httpHandler() }; }; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js var init_extensions = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() { "use strict"; init_httpExtensionConfiguration(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js var init_abort = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js var HttpAuthLocation; var init_auth = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js"() { "use strict"; (function(HttpAuthLocation2) { HttpAuthLocation2["HEADER"] = "header"; HttpAuthLocation2["QUERY"] = "query"; })(HttpAuthLocation || (HttpAuthLocation = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js var HttpApiKeyAuthLocation; var init_HttpApiKeyAuth = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() { "use strict"; (function(HttpApiKeyAuthLocation2) { HttpApiKeyAuthLocation2["HEADER"] = "header"; HttpApiKeyAuthLocation2["QUERY"] = "query"; })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js var init_HttpAuthScheme = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js var init_HttpAuthSchemeProvider = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js var init_HttpSigner = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js var init_IdentityProviderConfig = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js var init_auth2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js"() { "use strict"; init_auth(); init_HttpApiKeyAuth(); init_HttpAuthScheme(); init_HttpAuthSchemeProvider(); init_HttpSigner(); init_IdentityProviderConfig(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js var init_blob_payload_input_types = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js var init_checksum = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js var init_client = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js var init_command = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js var init_config = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js var init_manager = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js var init_pool = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js var init_connection = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js"() { "use strict"; init_config(); init_manager(); init_pool(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js var init_crypto2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js var init_encode = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js var EndpointURLScheme; var init_endpoint = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js"() { "use strict"; (function(EndpointURLScheme2) { EndpointURLScheme2["HTTP"] = "http"; EndpointURLScheme2["HTTPS"] = "https"; })(EndpointURLScheme || (EndpointURLScheme = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js var init_EndpointRuleObject = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js var init_ErrorRuleObject = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js var init_RuleSetObject = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js var init_shared = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js var init_TreeRuleObject = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js var init_endpoints = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js"() { "use strict"; init_EndpointRuleObject(); init_ErrorRuleObject(); init_RuleSetObject(); init_shared(); init_TreeRuleObject(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js var init_eventStream = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js var AlgorithmId; var init_checksum2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js"() { "use strict"; (function(AlgorithmId2) { AlgorithmId2["MD5"] = "md5"; AlgorithmId2["CRC32"] = "crc32"; AlgorithmId2["CRC32C"] = "crc32c"; AlgorithmId2["SHA1"] = "sha1"; AlgorithmId2["SHA256"] = "sha256"; })(AlgorithmId || (AlgorithmId = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js var init_defaultClientConfiguration = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() { "use strict"; init_checksum2(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js var init_defaultExtensionConfiguration = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js var init_extensions2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js"() { "use strict"; init_defaultClientConfiguration(); init_defaultExtensionConfiguration(); init_checksum2(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js var init_feature_ids = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js var FieldPosition; var init_http = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js"() { "use strict"; (function(FieldPosition2) { FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; })(FieldPosition || (FieldPosition = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js var init_httpHandlerInitialization = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js var init_apiKeyIdentity = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js var init_awsCredentialIdentity = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js var init_identity = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js var init_tokenIdentity = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js var init_identity2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js"() { "use strict"; init_apiKeyIdentity(); init_awsCredentialIdentity(); init_identity(); init_tokenIdentity(); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js var init_logger = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js var SMITHY_CONTEXT_KEY; var init_middleware = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js"() { "use strict"; SMITHY_CONTEXT_KEY = "__smithy_context"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js var init_pagination = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js var IniSectionType; var init_profile = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js"() { "use strict"; (function(IniSectionType2) { IniSectionType2["PROFILE"] = "profile"; IniSectionType2["SSO_SESSION"] = "sso-session"; IniSectionType2["SERVICES"] = "services"; })(IniSectionType || (IniSectionType = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js var init_response2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js var init_retry = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js var init_schema = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js var init_sentinels = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js var init_serde = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js var init_shapes = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js var init_signature = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js var init_stream = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js var init_streaming_blob_common_types = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js var init_streaming_blob_payload_input_types = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js var init_streaming_blob_payload_output_types = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js var RequestHandlerProtocol; var init_transfer = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js"() { "use strict"; (function(RequestHandlerProtocol2) { RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; })(RequestHandlerProtocol || (RequestHandlerProtocol = {})); } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js var init_client_payload_blob_type_narrow = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js var init_mutable = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js var init_no_undefined = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js var init_type_transform = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js var init_uri = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js var init_util2 = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js var init_waiter = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js var init_dist_es = __esm({ "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js"() { "use strict"; init_abort(); init_auth2(); init_blob_payload_input_types(); init_checksum(); init_client(); init_command(); init_connection(); init_crypto2(); init_encode(); init_endpoint(); init_endpoints(); init_eventStream(); init_extensions2(); init_feature_ids(); init_http(); init_httpHandlerInitialization(); init_identity2(); init_logger(); init_middleware(); init_pagination(); init_profile(); init_response2(); init_retry(); init_schema(); init_sentinels(); init_serde(); init_shapes(); init_signature(); init_stream(); init_streaming_blob_common_types(); init_streaming_blob_payload_input_types(); init_streaming_blob_payload_output_types(); init_transfer(); init_client_payload_blob_type_narrow(); init_mutable(); init_no_undefined(); init_type_transform(); init_uri(); init_util2(); init_waiter(); } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js var init_Field = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js"() { "use strict"; init_dist_es(); } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js var init_Fields = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js var init_httpHandler = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js function cloneQuery(query) { return Object.keys(query).reduce((carry, paramName) => { const param = query[paramName]; return { ...carry, [paramName]: Array.isArray(param) ? [...param] : param }; }, {}); } var HttpRequest; var init_httpRequest = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() { "use strict"; HttpRequest = class _HttpRequest { constructor(options) { this.method = options.method || "GET"; this.hostname = options.hostname || "localhost"; this.port = options.port; this.query = options.query || {}; this.headers = options.headers || {}; this.body = options.body; this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; this.username = options.username; this.password = options.password; this.fragment = options.fragment; } static clone(request2) { const cloned = new _HttpRequest({ ...request2, headers: { ...request2.headers } }); if (cloned.query) { cloned.query = cloneQuery(cloned.query); } return cloned; } static isInstance(request2) { if (!request2) { return false; } const req = request2; return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } clone() { return _HttpRequest.clone(this); } }; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js var HttpResponse; var init_httpResponse = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() { "use strict"; HttpResponse = class { constructor(options) { this.statusCode = options.statusCode; this.reason = options.reason; this.headers = options.headers || {}; this.body = options.body; } static isInstance(response) { if (!response) return false; const resp = response; return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js var init_isValidHostname = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js var init_types2 = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js var init_dist_es2 = __esm({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js"() { "use strict"; init_extensions(); init_Field(); init_Fields(); init_httpHandler(); init_httpRequest(); init_httpResponse(); init_isValidHostname(); init_types2(); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js function resolveHostHeaderConfig(input) { return input; } var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin; var init_dist_es3 = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() { "use strict"; init_dist_es2(); hostHeaderMiddleware = (options) => (next) => async (args) => { if (!HttpRequest.isInstance(args.request)) return next(args); const { request: request2 } = args; const { handlerProtocol = "" } = options.requestHandler.metadata || {}; if (handlerProtocol.indexOf("h2") >= 0 && !request2.headers[":authority"]) { delete request2.headers["host"]; request2.headers[":authority"] = request2.hostname + (request2.port ? ":" + request2.port : ""); } else if (!request2.headers["host"]) { let host = request2.hostname; if (request2.port != null) host += `:${request2.port}`; request2.headers["host"] = host; } return next(args); }; hostHeaderMiddlewareOptions = { name: "hostHeaderMiddleware", step: "build", priority: "low", tags: ["HOST"], override: true }; getHostHeaderPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin; var init_loggerMiddleware = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() { "use strict"; loggerMiddleware = () => (next, context) => async (args) => { try { const response = await next(args); const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; const { $metadata, ...outputWithoutMetadata } = response.output; logger2?.info?.({ clientName, commandName, input: inputFilterSensitiveLog(args.input), output: outputFilterSensitiveLog(outputWithoutMetadata), metadata: $metadata }); return response; } catch (error2) { const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; logger2?.error?.({ clientName, commandName, input: inputFilterSensitiveLog(args.input), error: error2, metadata: error2.$metadata }); throw error2; } }; loggerMiddlewareOptions = { name: "loggerMiddleware", tags: ["LOGGER"], step: "initialize", override: true }; getLoggerPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js var init_dist_es4 = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() { "use strict"; init_loggerMiddleware(); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js var TRACE_ID_HEADER_NAME, ENV_LAMBDA_FUNCTION_NAME, ENV_TRACE_ID, recursionDetectionMiddleware, addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin; var init_dist_es5 = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() { "use strict"; init_dist_es2(); TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; recursionDetectionMiddleware = (options) => (next) => async (args) => { const { request: request2 } = args; if (!HttpRequest.isInstance(request2) || options.runtime !== "node") { return next(args); } const traceIdHeader = Object.keys(request2.headers ?? {}).find((h6) => h6.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; if (request2.headers.hasOwnProperty(traceIdHeader)) { return next(args); } const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; const traceId = process.env[ENV_TRACE_ID]; const nonEmptyString = (str) => typeof str === "string" && str.length > 0; if (nonEmptyString(functionName) && nonEmptyString(traceId)) { request2.headers[TRACE_ID_HEADER_NAME] = traceId; } return next({ ...args, request: request2 }); }; addRecursionDetectionMiddlewareOptions = { step: "build", tags: ["RECURSION_DETECTION"], name: "recursionDetectionMiddleware", override: true, priority: "low" }; getRecursionDetectionPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js var init_getSmithyContext = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() { "use strict"; init_dist_es(); } }); // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js var getSmithyContext; var init_getSmithyContext2 = __esm({ "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() { "use strict"; init_dist_es(); getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {}); } }); // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js var normalizeProvider; var init_normalizeProvider = __esm({ "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() { "use strict"; normalizeProvider = (input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }; } }); // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js var init_dist_es6 = __esm({ "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js"() { "use strict"; init_getSmithyContext2(); init_normalizeProvider(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js var resolveAuthOptions; var init_resolveAuthOptions = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() { "use strict"; resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { if (!authSchemePreference || authSchemePreference.length === 0) { return candidateAuthOptions; } const preferredAuthOptions = []; for (const preferredSchemeName of authSchemePreference) { for (const candidateAuthOption of candidateAuthOptions) { const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; if (candidateAuthSchemeName === preferredSchemeName) { preferredAuthOptions.push(candidateAuthOption); } } } for (const candidateAuthOption of candidateAuthOptions) { if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { preferredAuthOptions.push(candidateAuthOption); } } return preferredAuthOptions; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js function convertHttpAuthSchemesToMap(httpAuthSchemes) { const map2 = /* @__PURE__ */ new Map(); for (const scheme of httpAuthSchemes) { map2.set(scheme.schemeId, scheme); } return map2; } var httpAuthSchemeMiddleware; var init_httpAuthSchemeMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() { "use strict"; init_dist_es(); init_dist_es6(); init_resolveAuthOptions(); httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; const resolvedOptions = resolveAuthOptions(options, authSchemePreference); const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); const smithyContext = getSmithyContext(context); const failureReasons = []; for (const option of resolvedOptions) { const scheme = authSchemes.get(option.schemeId); if (!scheme) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); continue; } const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); if (!identityProvider) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); continue; } const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); smithyContext.selectedHttpAuthScheme = { httpAuthOption: option, identity: await identityProvider(option.identityProperties), signer: scheme.signer }; break; } if (!smithyContext.selectedHttpAuthScheme) { throw new Error(failureReasons.join("\n")); } return next(args); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin; var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() { "use strict"; init_httpAuthSchemeMiddleware(); httpAuthSchemeEndpointRuleSetMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: "endpointV2Middleware" }; getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js var deserializerMiddleware, findHeader; var init_deserializerMiddleware = __esm({ "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() { "use strict"; init_dist_es2(); deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { const { response } = await next(args); try { const parsed = await deserializer(response, options); return { response, output: parsed }; } catch (error2) { Object.defineProperty(error2, "$response", { value: response }); if (!("$metadata" in error2)) { const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error2.message += "\n " + hint; } catch (e6) { if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { console.warn(hint); } else { context.logger?.warn?.(hint); } } if (typeof error2.$responseBodyText !== "undefined") { if (error2.$response) { error2.$response.body = error2.$responseBodyText; } } try { if (HttpResponse.isInstance(response)) { const { headers = {} } = response; const headerEntries = Object.entries(headers); error2.$metadata = { httpStatusCode: response.statusCode, requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) }; } } catch (e6) { } } throw error2; } }; findHeader = (pattern, headers) => { return (headers.find(([k5]) => { return k5.match(pattern); }) || [void 0, void 0])[1]; }; } }); // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js var serializerMiddleware; var init_serializerMiddleware = __esm({ "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() { "use strict"; serializerMiddleware = (options, serializer) => (next, context) => async (args) => { const endpointConfig = options; const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; if (!endpoint) { throw new Error("No valid endpoint provider available."); } const request2 = await serializer(args.input, { ...options, endpoint }); return next({ ...args, request: request2 }); }; } }); // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js function getSerdePlugin(config, serializer, deserializer) { return { applyToStack: (commandStack) => { commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); } }; } var deserializerMiddlewareOption, serializerMiddlewareOption; var init_serdePlugin = __esm({ "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() { "use strict"; init_deserializerMiddleware(); init_serializerMiddleware(); deserializerMiddlewareOption = { name: "deserializerMiddleware", step: "deserialize", tags: ["DESERIALIZER"], override: true }; serializerMiddlewareOption = { name: "serializerMiddleware", step: "serialize", tags: ["SERIALIZER"], override: true }; } }); // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js var init_dist_es7 = __esm({ "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js"() { "use strict"; init_deserializerMiddleware(); init_serdePlugin(); init_serializerMiddleware(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js var httpAuthSchemeMiddlewareOptions; var init_getHttpAuthSchemePlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() { "use strict"; init_dist_es7(); init_httpAuthSchemeMiddleware(); httpAuthSchemeMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: serializerMiddlewareOption.name }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js var init_middleware_http_auth_scheme = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() { "use strict"; init_httpAuthSchemeMiddleware(); init_getHttpAuthSchemeEndpointRuleSetPlugin(); init_getHttpAuthSchemePlugin(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware; var init_httpSigningMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() { "use strict"; init_dist_es2(); init_dist_es(); init_dist_es6(); defaultErrorHandler = (signingProperties) => (error2) => { throw error2; }; defaultSuccessHandler = (httpResponse, signingProperties) => { }; httpSigningMiddleware = (config) => (next, context) => async (args) => { if (!HttpRequest.isInstance(args.request)) { return next(args); } const smithyContext = getSmithyContext(context); const scheme = smithyContext.selectedHttpAuthScheme; if (!scheme) { throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; const output = await next({ ...args, request: await signer.sign(args.request, identity, signingProperties) }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); return output; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js var httpSigningMiddlewareOptions, getHttpSigningPlugin; var init_getHttpSigningMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() { "use strict"; init_httpSigningMiddleware(); httpSigningMiddlewareOptions = { step: "finalizeRequest", tags: ["HTTP_SIGNING"], name: "httpSigningMiddleware", aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], override: true, relation: "after", toMiddleware: "retryMiddleware" }; getHttpSigningPlugin = (config) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js var init_middleware_http_signing = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() { "use strict"; init_httpSigningMiddleware(); init_getHttpSigningMiddleware(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js var normalizeProvider2; var init_normalizeProvider2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() { "use strict"; normalizeProvider2 = (input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { return async function* paginateOperation(config, input, ...additionalArguments) { const _input = input; let token = config.startingToken ?? _input[inputTokenName]; let hasNext = true; let page; while (hasNext) { _input[inputTokenName] = token; if (pageSizeTokenName) { _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; } if (config.client instanceof ClientCtor) { page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); } else { throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); } yield page; const prevToken = token; token = get(page, outputTokenName); hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return void 0; }; } var makePagedClientRequest, get; var init_createPaginator = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { "use strict"; makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => { let command = new CommandCtor(input); command = withCommand(command) ?? command; return await client.send(command, ...args); }; get = (fromObject, path3) => { let cursor = fromObject; const pathComponents = path3.split("."); for (const step of pathComponents) { if (!cursor || typeof cursor !== "object") { return void 0; } cursor = cursor[step]; } return cursor; }; } }); // ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js var isArrayBuffer; var init_dist_es8 = __esm({ "../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js"() { "use strict"; isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; } }); // ../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js var import_buffer2, fromArrayBuffer, fromString; var init_dist_es9 = __esm({ "../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js"() { "use strict"; init_dist_es8(); import_buffer2 = require("buffer"); fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { if (!isArrayBuffer(input)) { throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } return import_buffer2.Buffer.from(input, offset, length); }; fromString = (input, encoding) => { if (typeof input !== "string") { throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } return encoding ? import_buffer2.Buffer.from(input, encoding) : import_buffer2.Buffer.from(input); }; } }); // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js var BASE64_REGEX, fromBase64; var init_fromBase64 = __esm({ "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js"() { "use strict"; init_dist_es9(); BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; fromBase64 = (input) => { if (input.length * 3 % 4 !== 0) { throw new TypeError(`Incorrect padding on base64 string.`); } if (!BASE64_REGEX.exec(input)) { throw new TypeError(`Invalid base64 string.`); } const buffer = fromString(input, "base64"); return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; } }); // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js var fromUtf8; var init_fromUtf8 = __esm({ "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"() { "use strict"; init_dist_es9(); fromUtf8 = (input) => { const buf = fromString(input, "utf8"); return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); }; } }); // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js var toUint8Array; var init_toUint8Array = __esm({ "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() { "use strict"; init_fromUtf8(); toUint8Array = (data) => { if (typeof data === "string") { return fromUtf8(data); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); }; } }); // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js var toUtf8; var init_toUtf8 = __esm({ "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js"() { "use strict"; init_dist_es9(); toUtf8 = (input) => { if (typeof input === "string") { return input; } if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); } return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); }; } }); // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js var init_dist_es10 = __esm({ "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js"() { "use strict"; init_fromUtf8(); init_toUint8Array(); init_toUtf8(); } }); // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js var toBase64; var init_toBase64 = __esm({ "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js"() { "use strict"; init_dist_es9(); init_dist_es10(); toBase64 = (_input) => { let input; if (typeof _input === "string") { input = fromUtf8(_input); } else { input = _input; } if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); } return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64"); }; } }); // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js var init_dist_es11 = __esm({ "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js"() { "use strict"; init_fromBase64(); init_toBase64(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js function transformToString(payload, encoding = "utf-8") { if (encoding === "base64") { return toBase64(payload); } return toUtf8(payload); } function transformFromString(str, encoding) { if (encoding === "base64") { return Uint8ArrayBlobAdapter.mutate(fromBase64(str)); } return Uint8ArrayBlobAdapter.mutate(fromUtf8(str)); } var init_transforms = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() { "use strict"; init_dist_es11(); init_dist_es10(); init_Uint8ArrayBlobAdapter(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js var Uint8ArrayBlobAdapter; var init_Uint8ArrayBlobAdapter = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() { "use strict"; init_transforms(); Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { static fromString(source, encoding = "utf-8") { switch (typeof source) { case "string": return transformFromString(source, encoding); default: throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); } } static mutate(source) { Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); return source; } transformToString(encoding = "utf-8") { return transformToString(this, encoding); } }; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js var init_ChecksumStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js"() { "use strict"; init_dist_es11(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js var isReadableStream; var init_stream_type_check = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() { "use strict"; isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js var init_ChecksumStream_browser = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js var init_createChecksumStream_browser = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js"() { "use strict"; init_dist_es11(); init_stream_type_check(); init_ChecksumStream_browser(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js var init_createChecksumStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js"() { "use strict"; init_stream_type_check(); init_ChecksumStream(); init_createChecksumStream_browser(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js var init_ByteArrayCollector = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js var init_createBufferedReadableStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js"() { "use strict"; init_ByteArrayCollector(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js var import_node_stream3; var init_createBufferedReadable = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js"() { "use strict"; import_node_stream3 = require("stream"); init_ByteArrayCollector(); init_createBufferedReadableStream(); init_stream_type_check(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js var init_getAwsChunkedEncodingStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js var init_headStream_browser = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js var init_headStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js"() { "use strict"; init_headStream_browser(); init_stream_type_check(); } }); // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js var escapeUri, hexEncode; var init_escape_uri = __esm({ "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() { "use strict"; escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`; } }); // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js var init_escape_uri_path = __esm({ "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() { "use strict"; init_escape_uri(); } }); // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js var init_dist_es12 = __esm({ "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js"() { "use strict"; init_escape_uri(); init_escape_uri_path(); } }); // ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js function buildQueryString(query) { const parts = []; for (let key of Object.keys(query).sort()) { const value = query[key]; key = escapeUri(key); if (Array.isArray(value)) { for (let i6 = 0, iLen = value.length; i6 < iLen; i6++) { parts.push(`${key}=${escapeUri(value[i6])}`); } } else { let qsEntry = key; if (value || typeof value === "string") { qsEntry += `=${escapeUri(value)}`; } parts.push(qsEntry); } } return parts.join("&"); } var init_dist_es13 = __esm({ "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js"() { "use strict"; init_dist_es12(); } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js var NODEJS_TIMEOUT_ERROR_CODES; var init_constants2 = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js"() { "use strict"; NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js var getTransformedHeaders; var init_get_transformed_headers = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js"() { "use strict"; getTransformedHeaders = (headers) => { const transformedHeaders = {}; for (const name of Object.keys(headers)) { const headerValues = headers[name]; transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } return transformedHeaders; }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js var timing; var init_timing = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js"() { "use strict"; timing = { setTimeout: (cb, ms) => setTimeout(cb, ms), clearTimeout: (timeoutId) => clearTimeout(timeoutId) }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js var DEFER_EVENT_LISTENER_TIME, setConnectionTimeout; var init_set_connection_timeout = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js"() { "use strict"; init_timing(); DEFER_EVENT_LISTENER_TIME = 1e3; setConnectionTimeout = (request2, reject, timeoutInMs = 0) => { if (!timeoutInMs) { return -1; } const registerTimeout = (offset) => { const timeoutId = timing.setTimeout(() => { request2.destroy(); reject(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { name: "TimeoutError" })); }, timeoutInMs - offset); const doWithSocket = (socket) => { if (socket?.connecting) { socket.on("connect", () => { timing.clearTimeout(timeoutId); }); } else { timing.clearTimeout(timeoutId); } }; if (request2.socket) { doWithSocket(request2.socket); } else { request2.on("socket", doWithSocket); } }; if (timeoutInMs < 2e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js var DEFER_EVENT_LISTENER_TIME2, setSocketKeepAlive; var init_set_socket_keep_alive = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js"() { "use strict"; init_timing(); DEFER_EVENT_LISTENER_TIME2 = 3e3; setSocketKeepAlive = (request2, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { if (keepAlive !== true) { return -1; } const registerListener = () => { if (request2.socket) { request2.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); } else { request2.on("socket", (socket) => { socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); }); } }; if (deferTimeMs === 0) { registerListener(); return 0; } return timing.setTimeout(registerListener, deferTimeMs); }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js var DEFER_EVENT_LISTENER_TIME3, setSocketTimeout; var init_set_socket_timeout = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js"() { "use strict"; init_node_http_handler(); init_timing(); DEFER_EVENT_LISTENER_TIME3 = 3e3; setSocketTimeout = (request2, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { const registerTimeout = (offset) => { const timeout = timeoutInMs - offset; const onTimeout = () => { request2.destroy(); reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); }; if (request2.socket) { request2.socket.setTimeout(timeout, onTimeout); request2.on("close", () => request2.socket?.removeListener("timeout", onTimeout)); } else { request2.setTimeout(timeout, onTimeout); } }; if (0 < timeoutInMs && timeoutInMs < 6e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3); }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js async function writeRequestBody(httpRequest2, request2, maxContinueTimeoutMs = MIN_WAIT_TIME) { const headers = request2.headers ?? {}; const expect = headers["Expect"] || headers["expect"]; let timeoutId = -1; let sendBody = true; if (expect === "100-continue") { sendBody = await Promise.race([ new Promise((resolve) => { timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); }), new Promise((resolve) => { httpRequest2.on("continue", () => { timing.clearTimeout(timeoutId); resolve(true); }); httpRequest2.on("response", () => { timing.clearTimeout(timeoutId); resolve(false); }); httpRequest2.on("error", () => { timing.clearTimeout(timeoutId); resolve(false); }); }) ]); } if (sendBody) { writeBody(httpRequest2, request2.body); } } function writeBody(httpRequest2, body) { if (body instanceof import_stream3.Readable) { body.pipe(httpRequest2); return; } if (body) { if (Buffer.isBuffer(body) || typeof body === "string") { httpRequest2.end(body); return; } const uint8 = body; if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); return; } httpRequest2.end(Buffer.from(body)); return; } httpRequest2.end(); } var import_stream3, MIN_WAIT_TIME; var init_write_request_body = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js"() { "use strict"; import_stream3 = require("stream"); init_timing(); MIN_WAIT_TIME = 6e3; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js var import_http3, import_https, DEFAULT_REQUEST_TIMEOUT, NodeHttpHandler; var init_node_http_handler = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js"() { "use strict"; init_dist_es2(); init_dist_es13(); import_http3 = require("http"); import_https = require("https"); init_constants2(); init_get_transformed_headers(); init_set_connection_timeout(); init_set_socket_keep_alive(); init_set_socket_timeout(); init_timing(); init_write_request_body(); DEFAULT_REQUEST_TIMEOUT = 0; NodeHttpHandler = class _NodeHttpHandler { static create(instanceOrOptions) { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } return new _NodeHttpHandler(instanceOrOptions); } static checkSocketUsage(agent, socketWarningTimestamp, logger2 = console) { const { sockets, requests, maxSockets } = agent; if (typeof maxSockets !== "number" || maxSockets === Infinity) { return socketWarningTimestamp; } const interval = 15e3; if (Date.now() - interval < socketWarningTimestamp) { return socketWarningTimestamp; } if (sockets && requests) { for (const origin in sockets) { const socketsInUse = sockets[origin]?.length ?? 0; const requestsEnqueued = requests[origin]?.length ?? 0; if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { logger2?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); return Date.now(); } } } return socketWarningTimestamp; } constructor(options) { this.socketWarningTimestamp = 0; this.metadata = { handlerProtocol: "http/1.1" }; this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options().then((_options) => { resolve(this.resolveDefaultConfig(_options)); }).catch(reject); } else { resolve(this.resolveDefaultConfig(options)); } }); } resolveDefaultConfig(options) { const { requestTimeout: requestTimeout2, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; const keepAlive = true; const maxSockets = 50; return { connectionTimeout, requestTimeout: requestTimeout2 ?? socketTimeout, socketAcquisitionWarningTimeout, httpAgent: (() => { if (httpAgent instanceof import_http3.Agent || typeof httpAgent?.destroy === "function") { return httpAgent; } return new import_http3.Agent({ keepAlive, maxSockets, ...httpAgent }); })(), httpsAgent: (() => { if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { return httpsAgent; } return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); })(), logger: console }; } destroy() { this.config?.httpAgent?.destroy(); this.config?.httpsAgent?.destroy(); } async handle(request2, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; } return new Promise((_resolve, _reject) => { let writeRequestBodyPromise = void 0; const timeouts = []; const resolve = async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _resolve(arg); }; const reject = async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _reject(arg); }; if (!this.config) { throw new Error("Node HTTP request handler config is not resolved"); } if (abortSignal?.aborted) { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const isSSL = request2.protocol === "https:"; const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; timeouts.push(timing.setTimeout(() => { this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger); }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3))); const queryString = buildQueryString(request2.query || {}); let auth = void 0; if (request2.username != null || request2.password != null) { const username = request2.username ?? ""; const password = request2.password ?? ""; auth = `${username}:${password}`; } let path3 = request2.path; if (queryString) { path3 += `?${queryString}`; } if (request2.fragment) { path3 += `#${request2.fragment}`; } let hostname = request2.hostname ?? ""; if (hostname[0] === "[" && hostname.endsWith("]")) { hostname = request2.hostname.slice(1, -1); } else { hostname = request2.hostname; } const nodeHttpsOptions = { headers: request2.headers, host: hostname, method: request2.method, path: path3, port: request2.port, agent, auth }; const requestFunc = isSSL ? import_https.request : import_http3.request; const req = requestFunc(nodeHttpsOptions, (res) => { const httpResponse = new HttpResponse({ statusCode: res.statusCode || -1, reason: res.statusMessage, headers: getTransformedHeaders(res.headers), body: res }); resolve({ response: httpResponse }); }); req.on("error", (err2) => { if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) { reject(Object.assign(err2, { name: "TimeoutError" })); } else { reject(err2); } }); if (abortSignal) { const onAbort = () => { req.destroy(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }; if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); const httpAgent = nodeHttpsOptions.agent; if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { timeouts.push(setSocketKeepAlive(req, { keepAlive: httpAgent.keepAlive, keepAliveMsecs: httpAgent.keepAliveMsecs })); } writeRequestBodyPromise = writeRequestBody(req, request2, this.config.requestTimeout).catch((e6) => { timeouts.forEach(timing.clearTimeout); return _reject(e6); }); }); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value }; }); } httpHandlerConfigs() { return this.config ?? {}; } }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js var init_node_http2_connection_pool = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js var init_node_http2_connection_manager = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js"() { "use strict"; init_node_http2_connection_pool(); } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js var init_node_http2_handler = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js"() { "use strict"; init_dist_es2(); init_dist_es13(); init_get_transformed_headers(); init_node_http2_connection_manager(); init_write_request_body(); } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js var import_stream4, Collector; var init_collector = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js"() { "use strict"; import_stream4 = require("stream"); Collector = class extends import_stream4.Writable { constructor() { super(...arguments); this.bufferedBytes = []; } _write(chunk, encoding, callback) { this.bufferedBytes.push(chunk); callback(); } }; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js async function collectReadableStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; let length = 0; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); length += value.length; } isDone = done; } const collected = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } return collected; } var streamCollector, isReadableStreamInstance; var init_stream_collector = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"() { "use strict"; init_collector(); streamCollector = (stream) => { if (isReadableStreamInstance(stream)) { return collectReadableStream(stream); } return new Promise((resolve, reject) => { const collector = new Collector(); stream.pipe(collector); stream.on("error", (err2) => { collector.end(); reject(err2); }); collector.on("error", reject); collector.on("finish", function() { const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); resolve(bytes); }); }); }; isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; } }); // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js var init_dist_es14 = __esm({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js"() { "use strict"; init_node_http_handler(); init_node_http2_handler(); init_stream_collector(); } }); // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js var init_create_request = __esm({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js var init_request_timeout = __esm({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js var init_fetch_http_handler = __esm({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() { "use strict"; init_dist_es2(); init_dist_es13(); init_create_request(); init_request_timeout(); } }); // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js async function collectBlob(blob) { const base64 = await readToBase64(blob); const arrayBuffer = fromBase64(base64); return new Uint8Array(arrayBuffer); } async function collectStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; let length = 0; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); length += value.length; } isDone = done; } const collected = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } return collected; } function readToBase64(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { if (reader.readyState !== 2) { return reject(new Error("Reader aborted too early")); } const result = reader.result ?? ""; const commaIndex = result.indexOf(","); const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; resolve(result.substring(dataOffset)); }; reader.onabort = () => reject(new Error("Read aborted")); reader.onerror = () => reject(reader.error); reader.readAsDataURL(blob); }); } var streamCollector2; var init_stream_collector2 = __esm({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() { "use strict"; init_dist_es11(); streamCollector2 = async (stream) => { if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { if (Blob.prototype.arrayBuffer !== void 0) { return new Uint8Array(await stream.arrayBuffer()); } return collectBlob(stream); } return collectStream(stream); }; } }); // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js var init_dist_es15 = __esm({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js"() { "use strict"; init_fetch_http_handler(); init_stream_collector2(); } }); // ../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js function fromHex(encoded) { if (encoded.length % 2 !== 0) { throw new Error("Hex encoded strings must have an even number length"); } const out = new Uint8Array(encoded.length / 2); for (let i6 = 0; i6 < encoded.length; i6 += 2) { const encodedByte = encoded.slice(i6, i6 + 2).toLowerCase(); if (encodedByte in HEX_TO_SHORT) { out[i6 / 2] = HEX_TO_SHORT[encodedByte]; } else { throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } } return out; } function toHex(bytes) { let out = ""; for (let i6 = 0; i6 < bytes.byteLength; i6++) { out += SHORT_TO_HEX[bytes[i6]]; } return out; } var SHORT_TO_HEX, HEX_TO_SHORT; var init_dist_es16 = __esm({ "../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() { "use strict"; SHORT_TO_HEX = {}; HEX_TO_SHORT = {}; for (let i6 = 0; i6 < 256; i6++) { let encodedByte = i6.toString(16).toLowerCase(); if (encodedByte.length === 1) { encodedByte = `0${encodedByte}`; } SHORT_TO_HEX[i6] = encodedByte; HEX_TO_SHORT[encodedByte] = i6; } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED, sdkStreamMixin, isBlobInstance; var init_sdk_stream_mixin_browser = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() { "use strict"; init_dist_es15(); init_dist_es11(); init_dist_es16(); init_dist_es10(); init_stream_type_check(); ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; sdkStreamMixin = (stream) => { if (!isBlobInstance(stream) && !isReadableStream(stream)) { const name = stream?.__proto__?.constructor?.name || stream; throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } let transformed = false; const transformToByteArray = async () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; return await streamCollector2(stream); }; const blobToWebStream = (blob) => { if (typeof blob.stream !== "function") { throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); } return blob.stream(); }; return Object.assign(stream, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); if (encoding === "base64") { return toBase64(buf); } else if (encoding === "hex") { return toHex(buf); } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") { return toUtf8(buf); } else if (typeof TextDecoder === "function") { return new TextDecoder(encoding).decode(buf); } else { throw new Error("TextDecoder is not available, please make sure polyfill is provided."); } }, transformToWebStream: () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; if (isBlobInstance(stream)) { return blobToWebStream(stream); } else if (isReadableStream(stream)) { return stream; } else { throw new Error(`Cannot transform payload to web stream, got ${stream}`); } } }); }; isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js var import_stream5, ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2, sdkStreamMixin2; var init_sdk_stream_mixin = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"() { "use strict"; init_dist_es14(); init_dist_es9(); import_stream5 = require("stream"); init_sdk_stream_mixin_browser(); ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2 = "The stream has already been transformed."; sdkStreamMixin2 = (stream) => { if (!(stream instanceof import_stream5.Readable)) { try { return sdkStreamMixin(stream); } catch (e6) { const name = stream?.__proto__?.constructor?.name || stream; throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } } let transformed = false; const transformToByteArray = async () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2); } transformed = true; return await streamCollector(stream); }; return Object.assign(stream, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); if (encoding === void 0 || Buffer.isEncoding(encoding)) { return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); } else { const decoder = new TextDecoder(encoding); return decoder.decode(buf); } }, transformToWebStream: () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2); } if (stream.readableFlowing !== null) { throw new Error("The stream has been consumed by other callbacks."); } if (typeof import_stream5.Readable.toWeb !== "function") { throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); } transformed = true; return import_stream5.Readable.toWeb(stream); } }); }; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js var init_splitStream_browser = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js var init_splitStream = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js"() { "use strict"; init_splitStream_browser(); init_stream_type_check(); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js var init_dist_es17 = __esm({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js"() { "use strict"; init_Uint8ArrayBlobAdapter(); init_ChecksumStream(); init_createChecksumStream(); init_createBufferedReadable(); init_getAwsChunkedEncodingStream(); init_headStream(); init_sdk_stream_mixin(); init_splitStream(); init_stream_type_check(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js var collectBody; var init_collect_stream_body = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() { "use strict"; init_dist_es17(); collectBody = async (streamBody = new Uint8Array(), context) => { if (streamBody instanceof Uint8Array) { return Uint8ArrayBlobAdapter.mutate(streamBody); } if (!streamBody) { return Uint8ArrayBlobAdapter.mutate(new Uint8Array()); } const fromContext = context.streamCollector(streamBody); return Uint8ArrayBlobAdapter.mutate(await fromContext); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js function extendedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) { return "%" + c5.charCodeAt(0).toString(16).toUpperCase(); }); } var init_extended_encode_uri_component = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js var init_deref = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js var init_schemaDeserializationMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() { "use strict"; init_dist_es2(); init_dist_es6(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js var init_schemaSerializationMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() { "use strict"; init_dist_es6(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js var init_getSchemaSerdePlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() { "use strict"; init_schemaDeserializationMiddleware(); init_schemaSerializationMiddleware(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js var TypeRegistry; var init_TypeRegistry = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() { "use strict"; TypeRegistry = class _TypeRegistry { constructor(namespace, schemas = /* @__PURE__ */ new Map()) { this.namespace = namespace; this.schemas = schemas; } static for(namespace) { if (!_TypeRegistry.registries.has(namespace)) { _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); } return _TypeRegistry.registries.get(namespace); } register(shapeId, schema6) { const qualifiedName = this.normalizeShapeId(shapeId); const registry = _TypeRegistry.for(this.getNamespace(shapeId)); registry.schemas.set(qualifiedName, schema6); } getSchema(shapeId) { const id = this.normalizeShapeId(shapeId); if (!this.schemas.has(id)) { throw new Error(`@smithy/core/schema - schema not found for ${id}`); } return this.schemas.get(id); } getBaseException() { for (const [id, schema6] of this.schemas.entries()) { if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) { return schema6; } } return void 0; } find(predicate) { return [...this.schemas.values()].find(predicate); } destroy() { _TypeRegistry.registries.delete(this.namespace); this.schemas.clear(); } normalizeShapeId(shapeId) { if (shapeId.includes("#")) { return shapeId; } return this.namespace + "#" + shapeId; } getNamespace(shapeId) { return this.normalizeShapeId(shapeId).split("#")[0]; } }; TypeRegistry.registries = /* @__PURE__ */ new Map(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js var init_Schema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js var init_ListSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() { "use strict"; init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js var init_MapSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() { "use strict"; init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js var init_OperationSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() { "use strict"; init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js var init_StructureSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() { "use strict"; init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js var init_ErrorSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() { "use strict"; init_TypeRegistry(); init_StructureSchema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js var init_sentinels2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js var init_SimpleSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() { "use strict"; init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js var init_NormalizedSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() { "use strict"; init_deref(); init_ListSchema(); init_MapSchema(); init_sentinels2(); init_SimpleSchema(); init_StructureSchema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js var init_schema2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() { "use strict"; init_deref(); init_getSchemaSerdePlugin(); init_ListSchema(); init_MapSchema(); init_OperationSchema(); init_ErrorSchema(); init_NormalizedSchema(); init_Schema(); init_SimpleSchema(); init_StructureSchema(); init_sentinels2(); init_TypeRegistry(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js var init_copyDocumentWithTransform = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() { "use strict"; init_schema2(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js var expectBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseFloat32, NUMBER_REGEX, parseNumber, limitedParseDouble, limitedParseFloat32, parseFloatString, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger; var init_parse_utils = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() { "use strict"; expectBoolean = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "number") { if (value === 0 || value === 1) { logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (value === 0) { return false; } if (value === 1) { return true; } } if (typeof value === "string") { const lower2 = value.toLowerCase(); if (lower2 === "false" || lower2 === "true") { logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (lower2 === "false") { return false; } if (lower2 === "true") { return true; } } if (typeof value === "boolean") { return value; } throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; expectNumber = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { const parsed = parseFloat(value); if (!Number.isNaN(parsed)) { if (String(parsed) !== String(value)) { logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } return parsed; } } if (typeof value === "number") { return value; } throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); expectFloat32 = (value) => { const expected = expectNumber(value); if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { if (Math.abs(expected) > MAX_FLOAT) { throw new TypeError(`Expected 32-bit float, got ${value}`); } } return expected; }; expectLong = (value) => { if (value === null || value === void 0) { return void 0; } if (Number.isInteger(value) && !Number.isNaN(value)) { return value; } throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); }; expectInt32 = (value) => expectSizedInt(value, 32); expectShort = (value) => expectSizedInt(value, 16); expectByte = (value) => expectSizedInt(value, 8); expectSizedInt = (value, size) => { const expected = expectLong(value); if (expected !== void 0 && castInt(expected, size) !== expected) { throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } return expected; }; castInt = (value, size) => { switch (size) { case 32: return Int32Array.of(value)[0]; case 16: return Int16Array.of(value)[0]; case 8: return Int8Array.of(value)[0]; } }; expectNonNull = (value, location) => { if (value === null || value === void 0) { if (location) { throw new TypeError(`Expected a non-null value for ${location}`); } throw new TypeError("Expected a non-null value"); } return value; }; expectObject = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "object" && !Array.isArray(value)) { return value; } const receivedType = Array.isArray(value) ? "array" : typeof value; throw new TypeError(`Expected object, got ${receivedType}: ${value}`); }; expectString = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { return value; } if (["boolean", "number", "bigint"].includes(typeof value)) { logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); return String(value); } throw new TypeError(`Expected string, got ${typeof value}: ${value}`); }; expectUnion = (value) => { if (value === null || value === void 0) { return void 0; } const asObject = expectObject(value); const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k5]) => k5); if (setKeys.length === 0) { throw new TypeError(`Unions must have exactly one non-null member. None were found.`); } if (setKeys.length > 1) { throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); } return asObject; }; strictParseFloat32 = (value) => { if (typeof value == "string") { return expectFloat32(parseNumber(value)); } return expectFloat32(value); }; NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; parseNumber = (value) => { const matches = value.match(NUMBER_REGEX); if (matches === null || matches[0].length !== value.length) { throw new TypeError(`Expected real number, got implicit NaN`); } return parseFloat(value); }; limitedParseDouble = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectNumber(value); }; limitedParseFloat32 = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectFloat32(value); }; parseFloatString = (value) => { switch (value) { case "NaN": return NaN; case "Infinity": return Infinity; case "-Infinity": return -Infinity; default: throw new Error(`Unable to parse float value: ${value}`); } }; strictParseInt32 = (value) => { if (typeof value === "string") { return expectInt32(parseNumber(value)); } return expectInt32(value); }; strictParseShort = (value) => { if (typeof value === "string") { return expectShort(parseNumber(value)); } return expectShort(value); }; strictParseByte = (value) => { if (typeof value === "string") { return expectByte(parseNumber(value)); } return expectByte(value); }; stackTraceWarning = (message) => { return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s6) => !s6.includes("stackTraceWarning")).join("\n"); }; logger = { warn: console.warn }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js var MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, buildDate, FIFTY_YEARS_IN_MILLIS, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes; var init_date_utils = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() { "use strict"; init_parse_utils(); MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); parseRfc3339DateTime = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match2 = RFC3339.exec(value); if (!match2) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); parseRfc3339DateTimeWithOffset = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match2 = RFC3339_WITH_OFFSET.exec(value); if (!match2) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } return date; }; IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); buildDate = (year, month, day, time) => { const adjustedMonth = month - 1; validateDayOfMonth(year, adjustedMonth, day); return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); }; FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; validateDayOfMonth = (year, month, day) => { let maxDays = DAYS_IN_MONTH[month]; if (month === 1 && isLeapYear(year)) { maxDays = 29; } if (day > maxDays) { throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } }; isLeapYear = (year) => { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; parseDateValue = (value, type, lower2, upper) => { const dateVal = strictParseByte(stripLeadingZeroes(value)); if (dateVal < lower2 || dateVal > upper) { throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`); } return dateVal; }; parseMilliseconds = (value) => { if (value === null || value === void 0) { return 0; } return strictParseFloat32("0." + value) * 1e3; }; parseOffsetToMilliseconds = (value) => { const directionStr = value[0]; let direction = 1; if (directionStr == "+") { direction = 1; } else if (directionStr == "-") { direction = -1; } else { throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } const hour = Number(value.substring(1, 3)); const minute = Number(value.substring(4, 6)); return direction * (hour * 60 + minute) * 60 * 1e3; }; stripLeadingZeroes = (value) => { let idx = 0; while (idx < value.length - 1 && value.charAt(idx) === "0") { idx++; } if (idx === 0) { return value; } return value.slice(idx); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js var LazyJsonString; var init_lazy_json = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() { "use strict"; LazyJsonString = function LazyJsonString2(val2) { const str = Object.assign(new String(val2), { deserializeJSON() { return JSON.parse(String(val2)); }, toString() { return String(val2); }, toJSON() { return String(val2); } }); return str; }; LazyJsonString.from = (object) => { if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { return object; } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { return LazyJsonString(String(object)); } return LazyJsonString(JSON.stringify(object)); }; LazyJsonString.fromObject = LazyJsonString.from; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js var init_quote_header = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js var init_split_every = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js var init_split_header = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js var init_NumericValue = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js var init_serde2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() { "use strict"; init_copyDocumentWithTransform(); init_date_utils(); init_lazy_json(); init_parse_utils(); init_quote_header(); init_split_every(); init_split_header(); init_NumericValue(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js var init_HttpProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() { "use strict"; init_schema2(); init_serde2(); init_dist_es2(); init_dist_es17(); init_collect_stream_body(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js var init_HttpBindingProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() { "use strict"; init_schema2(); init_dist_es2(); init_collect_stream_body(); init_extended_encode_uri_component(); init_HttpProtocol(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js var init_RpcProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() { "use strict"; init_schema2(); init_dist_es2(); init_collect_stream_body(); init_HttpProtocol(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js var resolvedPath; var init_resolve_path = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() { "use strict"; init_extended_encode_uri_component(); resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { if (input != null && input[memberName] !== void 0) { const labelValue = labelValueProvider(); if (labelValue.length <= 0) { throw new Error("Empty value provided for input HTTP label: " + memberName + "."); } resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue)); } else { throw new Error("No value provided for input HTTP label: " + memberName + "."); } return resolvedPath2; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js function requestBuilder(input, context) { return new RequestBuilder(input, context); } var RequestBuilder; var init_requestBuilder = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() { "use strict"; init_dist_es2(); init_resolve_path(); RequestBuilder = class { constructor(input, context) { this.input = input; this.context = context; this.query = {}; this.method = ""; this.headers = {}; this.path = ""; this.body = null; this.hostname = ""; this.resolvePathStack = []; } async build() { const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); this.path = basePath; for (const resolvePath of this.resolvePathStack) { resolvePath(this.path); } return new HttpRequest({ protocol, hostname: this.hostname || hostname, port, method: this.method, path: this.path, query: this.query, body: this.body, headers: this.headers }); } hn(hostname) { this.hostname = hostname; return this; } bp(uriLabel) { this.resolvePathStack.push((basePath) => { this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; }); return this; } p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { this.resolvePathStack.push((path3) => { this.path = resolvedPath(path3, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); }); return this; } h(headers) { this.headers = headers; return this; } q(query) { this.query = query; return this; } b(body) { this.body = body; return this; } m(method) { this.method = method; return this; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js var init_determineTimestampFormat = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() { "use strict"; init_schema2(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js var init_FromStringShapeDeserializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() { "use strict"; init_schema2(); init_serde2(); init_dist_es11(); init_dist_es10(); init_determineTimestampFormat(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js var init_HttpInterceptingShapeDeserializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() { "use strict"; init_schema2(); init_dist_es10(); init_FromStringShapeDeserializer(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js var init_ToStringShapeSerializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() { "use strict"; init_schema2(); init_serde2(); init_dist_es11(); init_determineTimestampFormat(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js var init_HttpInterceptingShapeSerializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() { "use strict"; init_schema2(); init_ToStringShapeSerializer(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js var init_protocols = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() { "use strict"; init_collect_stream_body(); init_extended_encode_uri_component(); init_HttpBindingProtocol(); init_RpcProtocol(); init_requestBuilder(); init_resolve_path(); init_FromStringShapeDeserializer(); init_HttpInterceptingShapeDeserializer(); init_HttpInterceptingShapeSerializer(); init_ToStringShapeSerializer(); init_determineTimestampFormat(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js var init_requestBuilder2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() { "use strict"; init_protocols(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js function setFeature(context, feature, value) { if (!context.__smithy_context) { context.__smithy_context = { features: {} }; } else if (!context.__smithy_context.features) { context.__smithy_context.features = {}; } context.__smithy_context.features[feature] = value; } var init_setFeature = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js var DefaultIdentityProviderConfig; var init_DefaultIdentityProviderConfig = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() { "use strict"; DefaultIdentityProviderConfig = class { constructor(config) { this.authSchemes = /* @__PURE__ */ new Map(); for (const [key, value] of Object.entries(config)) { if (value !== void 0) { this.authSchemes.set(key, value); } } } getIdentityProvider(schemeId) { return this.authSchemes.get(schemeId); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js var init_httpApiKeyAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() { "use strict"; init_dist_es2(); init_dist_es(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js var init_httpBearerAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() { "use strict"; init_dist_es2(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js var NoAuthSigner; var init_noAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() { "use strict"; NoAuthSigner = class { async sign(httpRequest2, identity, signingProperties) { return httpRequest2; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js var init_httpAuthSchemes = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() { "use strict"; init_httpApiKeyAuth(); init_httpBearerAuth(); init_noAuth(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider; var init_memoizeIdentityProvider = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() { "use strict"; createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; EXPIRATION_MS = 3e5; isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0; memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { if (provider === void 0) { return void 0; } const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = async (options) => { if (!pending) { pending = normalizedProvider(options); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = void 0; } return resolved; }; if (isExpired === void 0) { return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(options); } return resolved; }; } return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(options); } if (isConstant) { return resolved; } if (!requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { await coalesceProvider(options); return resolved; } return resolved; }; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js var init_util_identity_and_auth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() { "use strict"; init_DefaultIdentityProviderConfig(); init_httpAuthSchemes(); init_memoizeIdentityProvider(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js var init_dist_es18 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() { "use strict"; init_getSmithyContext(); init_middleware_http_auth_scheme(); init_middleware_http_signing(); init_normalizeProvider2(); init_createPaginator(); init_requestBuilder2(); init_setFeature(); init_util_identity_and_auth(); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js function isValidUserAgentAppId(appId) { if (appId === void 0) { return true; } return typeof appId === "string" && appId.length <= 50; } function resolveUserAgentConfig(input) { const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID); const { customUserAgent } = input; return Object.assign(input, { customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, userAgentAppId: async () => { const appId = await normalizedAppIdProvider(); if (!isValidUserAgentAppId(appId)) { const logger2 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; if (typeof appId !== "string") { logger2?.warn("userAgentAppId must be a string or undefined."); } else if (appId.length > 50) { logger2?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); } } return appId; } }); } var DEFAULT_UA_APP_ID; var init_configurations = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() { "use strict"; init_dist_es18(); DEFAULT_UA_APP_ID = void 0; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js var EndpointCache; var init_EndpointCache = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"() { "use strict"; EndpointCache = class { constructor({ size, params }) { this.data = /* @__PURE__ */ new Map(); this.parameters = []; this.capacity = size ?? 50; if (params) { this.parameters = params; } } get(endpointParams, resolver) { const key = this.hash(endpointParams); if (key === false) { return resolver(); } if (!this.data.has(key)) { if (this.data.size > this.capacity + 10) { const keys = this.data.keys(); let i6 = 0; while (true) { const { value, done } = keys.next(); this.data.delete(value); if (done || ++i6 > 10) { break; } } } this.data.set(key, resolver()); } return this.data.get(key); } size() { return this.data.size; } hash(endpointParams) { let buffer = ""; const { parameters } = this; if (parameters.length === 0) { return false; } for (const param of parameters) { const val2 = String(endpointParams[param] ?? ""); if (val2.includes("|;")) { return false; } buffer += val2 + "|;"; } return buffer; } }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js var IP_V4_REGEX, isIpAddress; var init_isIpAddress = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() { "use strict"; IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js var VALID_HOST_LABEL_REGEX, isValidHostLabel; var init_isValidHostLabel = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() { "use strict"; VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); isValidHostLabel = (value, allowSubDomains = false) => { if (!allowSubDomains) { return VALID_HOST_LABEL_REGEX.test(value); } const labels = value.split("."); for (const label of labels) { if (!isValidHostLabel(label)) { return false; } } return true; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js var customEndpointFunctions; var init_customEndpointFunctions = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() { "use strict"; customEndpointFunctions = {}; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js var debugId; var init_debugId = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() { "use strict"; debugId = "endpoints"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js function toDebugString(input) { if (typeof input !== "object" || input == null) { return input; } if ("ref" in input) { return `$${toDebugString(input.ref)}`; } if ("fn" in input) { return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; } return JSON.stringify(input, null, 2); } var init_toDebugString = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js var init_debug = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() { "use strict"; init_debugId(); init_toDebugString(); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js var EndpointError; var init_EndpointError = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() { "use strict"; EndpointError = class extends Error { constructor(message) { super(message); this.name = "EndpointError"; } }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js var init_EndpointFunctions = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js var init_EndpointRuleObject2 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js var init_ErrorRuleObject2 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js var init_RuleSetObject2 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js var init_TreeRuleObject2 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js var init_shared2 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js var init_types3 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js"() { "use strict"; init_EndpointError(); init_EndpointFunctions(); init_EndpointRuleObject2(); init_ErrorRuleObject2(); init_RuleSetObject2(); init_TreeRuleObject2(); init_shared2(); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js var booleanEquals; var init_booleanEquals = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() { "use strict"; booleanEquals = (value1, value2) => value1 === value2; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js var getAttrPathList; var init_getAttrPathList = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() { "use strict"; init_types3(); getAttrPathList = (path3) => { const parts = path3.split("."); const pathList = []; for (const part of parts) { const squareBracketIndex = part.indexOf("["); if (squareBracketIndex !== -1) { if (part.indexOf("]") !== part.length - 1) { throw new EndpointError(`Path: '${path3}' does not end with ']'`); } const arrayIndex = part.slice(squareBracketIndex + 1, -1); if (Number.isNaN(parseInt(arrayIndex))) { throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path3}'`); } if (squareBracketIndex !== 0) { pathList.push(part.slice(0, squareBracketIndex)); } pathList.push(arrayIndex); } else { pathList.push(part); } } return pathList; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js var getAttr; var init_getAttr = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() { "use strict"; init_types3(); init_getAttrPathList(); getAttr = (value, path3) => getAttrPathList(path3).reduce((acc, index6) => { if (typeof acc !== "object") { throw new EndpointError(`Index '${index6}' in '${path3}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { return acc[parseInt(index6)]; } return acc[index6]; }, value); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js var isSet; var init_isSet = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() { "use strict"; isSet = (value) => value != null; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js var not; var init_not = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() { "use strict"; not = (value) => !value; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js var DEFAULT_PORTS, parseURL; var init_parseURL = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() { "use strict"; init_dist_es(); init_isIpAddress(); DEFAULT_PORTS = { [EndpointURLScheme.HTTP]: 80, [EndpointURLScheme.HTTPS]: 443 }; parseURL = (value) => { const whatwgURL = (() => { try { if (value instanceof URL) { return value; } if (typeof value === "object" && "hostname" in value) { const { hostname: hostname2, port, protocol: protocol2 = "", path: path3 = "", query = {} } = value; const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path3}`); url.search = Object.entries(query).map(([k5, v6]) => `${k5}=${v6}`).join("&"); return url; } return new URL(value); } catch (error2) { return null; } })(); if (!whatwgURL) { console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); return null; } const urlString = whatwgURL.href; const { host, hostname, pathname, protocol, search } = whatwgURL; if (search) { return null; } const scheme = protocol.slice(0, -1); if (!Object.values(EndpointURLScheme).includes(scheme)) { return null; } const isIp = isIpAddress(hostname); const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; return { scheme, authority, path: pathname, normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, isIp }; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js var stringEquals; var init_stringEquals = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() { "use strict"; stringEquals = (value1, value2) => value1 === value2; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js var substring; var init_substring = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() { "use strict"; substring = (input, start, stop, reverse) => { if (start >= stop || input.length < stop) { return null; } if (!reverse) { return input.substring(start, stop); } return input.substring(input.length - stop, input.length - start); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js var uriEncode; var init_uriEncode = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() { "use strict"; uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js var init_lib = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() { "use strict"; init_booleanEquals(); init_getAttr(); init_isSet(); init_isValidHostLabel(); init_not(); init_parseURL(); init_stringEquals(); init_substring(); init_uriEncode(); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js var endpointFunctions; var init_endpointFunctions = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() { "use strict"; init_lib(); endpointFunctions = { booleanEquals, getAttr, isSet, isValidHostLabel, not, parseURL, stringEquals, substring, uriEncode }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js var evaluateTemplate; var init_evaluateTemplate = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() { "use strict"; init_lib(); evaluateTemplate = (template, options) => { const evaluatedTemplateArr = []; const templateContext = { ...options.endpointParams, ...options.referenceRecord }; let currentIndex = 0; while (currentIndex < template.length) { const openingBraceIndex = template.indexOf("{", currentIndex); if (openingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(currentIndex)); break; } evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); const closingBraceIndex = template.indexOf("}", openingBraceIndex); if (closingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(openingBraceIndex)); break; } if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); currentIndex = closingBraceIndex + 2; } const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); if (parameterName.includes("#")) { const [refName, attrName] = parameterName.split("#"); evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); } else { evaluatedTemplateArr.push(templateContext[parameterName]); } currentIndex = closingBraceIndex + 1; } return evaluatedTemplateArr.join(""); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js var getReferenceValue; var init_getReferenceValue = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() { "use strict"; getReferenceValue = ({ ref }, options) => { const referenceRecord = { ...options.endpointParams, ...options.referenceRecord }; return referenceRecord[ref]; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js var evaluateExpression; var init_evaluateExpression = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() { "use strict"; init_types3(); init_callFunction(); init_evaluateTemplate(); init_getReferenceValue(); evaluateExpression = (obj, keyName, options) => { if (typeof obj === "string") { return evaluateTemplate(obj, options); } else if (obj["fn"]) { return callFunction(obj, options); } else if (obj["ref"]) { return getReferenceValue(obj, options); } throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js var callFunction; var init_callFunction = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() { "use strict"; init_customEndpointFunctions(); init_endpointFunctions(); init_evaluateExpression(); callFunction = ({ fn, argv }, options) => { const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options)); const fnSegments = fn.split("."); if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } return endpointFunctions[fn](...evaluatedArgs); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js var evaluateCondition; var init_evaluateCondition = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() { "use strict"; init_debug(); init_types3(); init_callFunction(); evaluateCondition = ({ assign, ...fnArgs }, options) => { if (assign && assign in options.referenceRecord) { throw new EndpointError(`'${assign}' is already defined in Reference Record.`); } const value = callFunction(fnArgs, options); options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); return { result: value === "" ? true : !!value, ...assign != null && { toAssign: { name: assign, value } } }; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js var evaluateConditions; var init_evaluateConditions = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() { "use strict"; init_debug(); init_evaluateCondition(); evaluateConditions = (conditions = [], options) => { const conditionsReferenceRecord = {}; for (const condition of conditions) { const { result, toAssign } = evaluateCondition(condition, { ...options, referenceRecord: { ...options.referenceRecord, ...conditionsReferenceRecord } }); if (!result) { return { result }; } if (toAssign) { conditionsReferenceRecord[toAssign.name] = toAssign.value; options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); } } return { result: true, referenceRecord: conditionsReferenceRecord }; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js var getEndpointHeaders; var init_getEndpointHeaders = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() { "use strict"; init_types3(); init_evaluateExpression(); getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ ...acc, [headerKey]: headerVal.map((headerValEntry) => { const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); if (typeof processedExpr !== "string") { throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); } return processedExpr; }) }), {}); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js var getEndpointProperty; var init_getEndpointProperty = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() { "use strict"; init_types3(); init_evaluateTemplate(); init_getEndpointProperties(); getEndpointProperty = (property, options) => { if (Array.isArray(property)) { return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); } switch (typeof property) { case "string": return evaluateTemplate(property, options); case "object": if (property === null) { throw new EndpointError(`Unexpected endpoint property: ${property}`); } return getEndpointProperties(property, options); case "boolean": return property; default: throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); } }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js var getEndpointProperties; var init_getEndpointProperties = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() { "use strict"; init_getEndpointProperty(); getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ ...acc, [propertyKey]: getEndpointProperty(propertyVal, options) }), {}); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js var getEndpointUrl; var init_getEndpointUrl = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() { "use strict"; init_types3(); init_evaluateExpression(); getEndpointUrl = (endpointUrl, options) => { const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); if (typeof expression === "string") { try { return new URL(expression); } catch (error2) { console.error(`Failed to construct URL with ${expression}`, error2); throw error2; } } throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js var evaluateEndpointRule; var init_evaluateEndpointRule = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() { "use strict"; init_debug(); init_evaluateConditions(); init_getEndpointHeaders(); init_getEndpointProperties(); init_getEndpointUrl(); evaluateEndpointRule = (endpointRule, options) => { const { conditions, endpoint } = endpointRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } const endpointRuleOptions = { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } }; const { url, properties, headers } = endpoint; options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); return { ...headers != void 0 && { headers: getEndpointHeaders(headers, endpointRuleOptions) }, ...properties != void 0 && { properties: getEndpointProperties(properties, endpointRuleOptions) }, url: getEndpointUrl(url, endpointRuleOptions) }; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js var evaluateErrorRule; var init_evaluateErrorRule = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() { "use strict"; init_types3(); init_evaluateConditions(); init_evaluateExpression(); evaluateErrorRule = (errorRule, options) => { const { conditions, error: error2 } = errorRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } throw new EndpointError(evaluateExpression(error2, "Error", { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } })); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js var evaluateTreeRule; var init_evaluateTreeRule = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() { "use strict"; init_evaluateConditions(); init_evaluateRules(); evaluateTreeRule = (treeRule, options) => { const { conditions, rules } = treeRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } return evaluateRules(rules, { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } }); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js var evaluateRules; var init_evaluateRules = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() { "use strict"; init_types3(); init_evaluateEndpointRule(); init_evaluateErrorRule(); init_evaluateTreeRule(); evaluateRules = (rules, options) => { for (const rule of rules) { if (rule.type === "endpoint") { const endpointOrUndefined = evaluateEndpointRule(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else if (rule.type === "error") { evaluateErrorRule(rule, options); } else if (rule.type === "tree") { const endpointOrUndefined = evaluateTreeRule(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else { throw new EndpointError(`Unknown endpoint rule: ${rule}`); } } throw new EndpointError(`Rules evaluation failed`); }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js var init_utils5 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() { "use strict"; init_customEndpointFunctions(); init_evaluateRules(); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js var resolveEndpoint; var init_resolveEndpoint = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() { "use strict"; init_debug(); init_types3(); init_utils5(); resolveEndpoint = (ruleSetObject, options) => { const { endpointParams, logger: logger2 } = options; const { parameters, rules } = ruleSetObject; options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k5, v6]) => [k5, v6.default]); if (paramsWithDefault.length > 0) { for (const [paramKey, paramDefaultValue] of paramsWithDefault) { endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; } } const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k5]) => k5); for (const requiredParam of requiredParams) { if (endpointParams[requiredParam] == null) { throw new EndpointError(`Missing required parameter: '${requiredParam}'`); } } const endpoint = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} }); options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); return endpoint; }; } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js var init_dist_es19 = __esm({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js"() { "use strict"; init_EndpointCache(); init_isIpAddress(); init_isValidHostLabel(); init_customEndpointFunctions(); init_resolveEndpoint(); init_types3(); } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js var init_isIpAddress2 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { "use strict"; init_dist_es19(); } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js var isVirtualHostableS3Bucket; var init_isVirtualHostableS3Bucket = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { "use strict"; init_dist_es19(); init_isIpAddress2(); isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { if (allowSubDomains) { for (const label of value.split(".")) { if (!isVirtualHostableS3Bucket(label)) { return false; } } return true; } if (!isValidHostLabel(value)) { return false; } if (value.length < 3 || value.length > 63) { return false; } if (value !== value.toLowerCase()) { return false; } if (isIpAddress(value)) { return false; } return true; }; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn; var init_parseArn = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { "use strict"; ARN_DELIMITER = ":"; RESOURCE_DELIMITER = "/"; parseArn = (value) => { const segments = value.split(ARN_DELIMITER); if (segments.length < 6) return null; const [arn, partition2, service, region, accountId, ...resourcePath] = segments; if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); return { partition: partition2, service, region, accountId, resourceId }; }; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json var partitions_default; var init_partitions = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { partitions_default = { partitions: [{ id: "aws", outputs: { dnsSuffix: "amazonaws.com", dualStackDnsSuffix: "api.aws", implicitGlobalRegion: "us-east-1", name: "aws", supportsDualStack: true, supportsFIPS: true }, regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", regions: { "af-south-1": { description: "Africa (Cape Town)" }, "ap-east-1": { description: "Asia Pacific (Hong Kong)" }, "ap-northeast-1": { description: "Asia Pacific (Tokyo)" }, "ap-northeast-2": { description: "Asia Pacific (Seoul)" }, "ap-northeast-3": { description: "Asia Pacific (Osaka)" }, "ap-south-1": { description: "Asia Pacific (Mumbai)" }, "ap-south-2": { description: "Asia Pacific (Hyderabad)" }, "ap-southeast-1": { description: "Asia Pacific (Singapore)" }, "ap-southeast-2": { description: "Asia Pacific (Sydney)" }, "ap-southeast-3": { description: "Asia Pacific (Jakarta)" }, "ap-southeast-4": { description: "Asia Pacific (Melbourne)" }, "ap-southeast-5": { description: "Asia Pacific (Malaysia)" }, "ap-southeast-7": { description: "Asia Pacific (Thailand)" }, "aws-global": { description: "AWS Standard global region" }, "ca-central-1": { description: "Canada (Central)" }, "ca-west-1": { description: "Canada West (Calgary)" }, "eu-central-1": { description: "Europe (Frankfurt)" }, "eu-central-2": { description: "Europe (Zurich)" }, "eu-north-1": { description: "Europe (Stockholm)" }, "eu-south-1": { description: "Europe (Milan)" }, "eu-south-2": { description: "Europe (Spain)" }, "eu-west-1": { description: "Europe (Ireland)" }, "eu-west-2": { description: "Europe (London)" }, "eu-west-3": { description: "Europe (Paris)" }, "il-central-1": { description: "Israel (Tel Aviv)" }, "me-central-1": { description: "Middle East (UAE)" }, "me-south-1": { description: "Middle East (Bahrain)" }, "mx-central-1": { description: "Mexico (Central)" }, "sa-east-1": { description: "South America (Sao Paulo)" }, "us-east-1": { description: "US East (N. Virginia)" }, "us-east-2": { description: "US East (Ohio)" }, "us-west-1": { description: "US West (N. California)" }, "us-west-2": { description: "US West (Oregon)" } } }, { id: "aws-cn", outputs: { dnsSuffix: "amazonaws.com.cn", dualStackDnsSuffix: "api.amazonwebservices.com.cn", implicitGlobalRegion: "cn-northwest-1", name: "aws-cn", supportsDualStack: true, supportsFIPS: true }, regionRegex: "^cn\\-\\w+\\-\\d+$", regions: { "aws-cn-global": { description: "AWS China global region" }, "cn-north-1": { description: "China (Beijing)" }, "cn-northwest-1": { description: "China (Ningxia)" } } }, { id: "aws-us-gov", outputs: { dnsSuffix: "amazonaws.com", dualStackDnsSuffix: "api.aws", implicitGlobalRegion: "us-gov-west-1", name: "aws-us-gov", supportsDualStack: true, supportsFIPS: true }, regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", regions: { "aws-us-gov-global": { description: "AWS GovCloud (US) global region" }, "us-gov-east-1": { description: "AWS GovCloud (US-East)" }, "us-gov-west-1": { description: "AWS GovCloud (US-West)" } } }, { id: "aws-iso", outputs: { dnsSuffix: "c2s.ic.gov", dualStackDnsSuffix: "c2s.ic.gov", implicitGlobalRegion: "us-iso-east-1", name: "aws-iso", supportsDualStack: false, supportsFIPS: true }, regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", regions: { "aws-iso-global": { description: "AWS ISO (US) global region" }, "us-iso-east-1": { description: "US ISO East" }, "us-iso-west-1": { description: "US ISO WEST" } } }, { id: "aws-iso-b", outputs: { dnsSuffix: "sc2s.sgov.gov", dualStackDnsSuffix: "sc2s.sgov.gov", implicitGlobalRegion: "us-isob-east-1", name: "aws-iso-b", supportsDualStack: false, supportsFIPS: true }, regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", regions: { "aws-iso-b-global": { description: "AWS ISOB (US) global region" }, "us-isob-east-1": { description: "US ISOB East (Ohio)" } } }, { id: "aws-iso-e", outputs: { dnsSuffix: "cloud.adc-e.uk", dualStackDnsSuffix: "cloud.adc-e.uk", implicitGlobalRegion: "eu-isoe-west-1", name: "aws-iso-e", supportsDualStack: false, supportsFIPS: true }, regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", regions: { "aws-iso-e-global": { description: "AWS ISOE (Europe) global region" }, "eu-isoe-west-1": { description: "EU ISOE West" } } }, { id: "aws-iso-f", outputs: { dnsSuffix: "csp.hci.ic.gov", dualStackDnsSuffix: "csp.hci.ic.gov", implicitGlobalRegion: "us-isof-south-1", name: "aws-iso-f", supportsDualStack: false, supportsFIPS: true }, regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", regions: { "aws-iso-f-global": { description: "AWS ISOF global region" }, "us-isof-east-1": { description: "US ISOF EAST" }, "us-isof-south-1": { description: "US ISOF SOUTH" } } }, { id: "aws-eusc", outputs: { dnsSuffix: "amazonaws.eu", dualStackDnsSuffix: "amazonaws.eu", implicitGlobalRegion: "eusc-de-east-1", name: "aws-eusc", supportsDualStack: false, supportsFIPS: true }, regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", regions: { "eusc-de-east-1": { description: "EU (Germany)" } } }], version: "1.1" }; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix; var init_partition = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { "use strict"; init_partitions(); selectedPartitionsInfo = partitions_default; selectedUserAgentPrefix = ""; partition = (value) => { const { partitions } = selectedPartitionsInfo; for (const partition2 of partitions) { const { regions, outputs: outputs2 } = partition2; for (const [region, regionData] of Object.entries(regions)) { if (region === value) { return { ...outputs2, ...regionData }; } } } for (const partition2 of partitions) { const { regionRegex, outputs: outputs2 } = partition2; if (new RegExp(regionRegex).test(value)) { return { ...outputs2 }; } } const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); if (!DEFAULT_PARTITION) { throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); } return { ...DEFAULT_PARTITION.outputs }; }; getUserAgentPrefix = () => selectedUserAgentPrefix; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js var awsEndpointFunctions; var init_aws = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { "use strict"; init_dist_es19(); init_isVirtualHostableS3Bucket(); init_parseArn(); init_partition(); awsEndpointFunctions = { isVirtualHostableS3Bucket, parseArn, partition }; customEndpointFunctions.aws = awsEndpointFunctions; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js var init_resolveEndpoint2 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { "use strict"; init_dist_es19(); } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js var init_EndpointError2 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { "use strict"; init_dist_es19(); } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js var init_EndpointRuleObject3 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js var init_ErrorRuleObject3 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js var init_RuleSetObject3 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js var init_TreeRuleObject3 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js var init_shared3 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js var init_types4 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { "use strict"; init_EndpointError2(); init_EndpointRuleObject3(); init_ErrorRuleObject3(); init_RuleSetObject3(); init_TreeRuleObject3(); init_shared3(); } }); // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js var init_dist_es20 = __esm({ "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { "use strict"; init_aws(); init_partition(); init_isIpAddress2(); init_resolveEndpoint2(); init_types4(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js var state, emitWarningIfUnsupportedVersion; var init_emitWarningIfUnsupportedVersion = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() { "use strict"; state = { warningEmitted: false }; emitWarningIfUnsupportedVersion = (version) => { if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { state.warningEmitted = true; process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will no longer support Node.js 16.x on January 6, 2025. To continue receiving updates to AWS services, bug fixes, and security updates please upgrade to a supported Node.js LTS version. More information can be found at: https://a.co/74kJMmI`); } }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js function setCredentialFeature(credentials2, feature, value) { if (!credentials2.$source) { credentials2.$source = {}; } credentials2.$source[feature] = value; return credentials2; } var init_setCredentialFeature = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js function setFeature2(context, feature, value) { if (!context.__aws_sdk_context) { context.__aws_sdk_context = { features: {} }; } else if (!context.__aws_sdk_context.features) { context.__aws_sdk_context.features = {}; } context.__aws_sdk_context.features[feature] = value; } var init_setFeature2 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() { "use strict"; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js var init_client2 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() { "use strict"; init_emitWarningIfUnsupportedVersion(); init_setCredentialFeature(); init_setFeature2(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js var getDateHeader; var init_getDateHeader = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() { "use strict"; init_dist_es2(); getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js var getSkewCorrectedDate; var init_getSkewCorrectedDate = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() { "use strict"; getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js var isClockSkewed; var init_isClockSkewed = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() { "use strict"; init_getSkewCorrectedDate(); isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js var getUpdatedSystemClockOffset; var init_getUpdatedSystemClockOffset = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() { "use strict"; init_isClockSkewed(); getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { const clockTimeInMs = Date.parse(clockTime); if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { return clockTimeInMs - Date.now(); } return currentSystemClockOffset; }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js var init_utils6 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() { "use strict"; init_getDateHeader(); init_getSkewCorrectedDate(); init_getUpdatedSystemClockOffset(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer; var init_AwsSdkSigV4Signer = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() { "use strict"; init_dist_es2(); init_utils6(); throwSigningPropertyError = (name, property) => { if (!property) { throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); } return property; }; validateSigningProperties = async (signingProperties) => { const context = throwSigningPropertyError("context", signingProperties.context); const config = throwSigningPropertyError("config", signingProperties.config); const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; const signerFunction = throwSigningPropertyError("signer", config.signer); const signer = await signerFunction(authScheme); const signingRegion = signingProperties?.signingRegion; const signingRegionSet = signingProperties?.signingRegionSet; const signingName = signingProperties?.signingName; return { config, signer, signingRegion, signingRegionSet, signingName }; }; AwsSdkSigV4Signer = class { async sign(httpRequest2, identity, signingProperties) { if (!HttpRequest.isInstance(httpRequest2)) { throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); } const validatedProps = await validateSigningProperties(signingProperties); const { config, signer } = validatedProps; let { signingRegion, signingName } = validatedProps; const handlerExecutionContext = signingProperties.context; if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { const [first, second] = handlerExecutionContext.authSchemes; if (first?.name === "sigv4a" && second?.name === "sigv4") { signingRegion = second?.signingRegion ?? signingRegion; signingName = second?.signingName ?? signingName; } } const signedRequest = await signer.sign(httpRequest2, { signingDate: getSkewCorrectedDate(config.systemClockOffset), signingRegion, signingService: signingName }); return signedRequest; } errorHandler(signingProperties) { return (error2) => { const serverTime = error2.ServerTime ?? getDateHeader(error2.$response); if (serverTime) { const config = throwSigningPropertyError("config", signingProperties.config); const initialSystemClockOffset = config.systemClockOffset; config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; if (clockSkewCorrected && error2.$metadata) { error2.$metadata.clockSkewCorrected = true; } } throw error2; }; } successHandler(httpResponse, signingProperties) { const dateHeader = getDateHeader(httpResponse); if (dateHeader) { const config = throwSigningPropertyError("config", signingProperties.config); config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); } } }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js var getArrayForCommaSeparatedString; var init_getArrayForCommaSeparatedString = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() { "use strict"; getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js var getBearerTokenEnvKey; var init_getBearerTokenEnvKey = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() { "use strict"; getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() { "use strict"; init_getArrayForCommaSeparatedString(); init_getBearerTokenEnvKey(); NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { environmentVariableSelector: (env4, options) => { if (options?.signingName) { const bearerTokenKey = getBearerTokenEnvKey(options.signingName); if (bearerTokenKey in env4) return ["httpBearerAuth"]; } if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env4)) return void 0; return getArrayForCommaSeparatedString(env4[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); }, configFileSelector: (profile) => { if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); }, default: [] }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js var ProviderError; var init_ProviderError = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js"() { "use strict"; ProviderError = class _ProviderError extends Error { constructor(message, options = true) { let logger2; let tryNextLink = true; if (typeof options === "boolean") { logger2 = void 0; tryNextLink = options; } else if (options != null && typeof options === "object") { logger2 = options.logger; tryNextLink = options.tryNextLink ?? true; } super(message); this.name = "ProviderError"; this.tryNextLink = tryNextLink; Object.setPrototypeOf(this, _ProviderError.prototype); logger2?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } static from(error2, options = true) { return Object.assign(new this(error2.message, options), error2); } }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js var CredentialsProviderError; var init_CredentialsProviderError = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() { "use strict"; init_ProviderError(); CredentialsProviderError = class _CredentialsProviderError extends ProviderError { constructor(message, options = true) { super(message, options); this.name = "CredentialsProviderError"; Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js var TokenProviderError; var init_TokenProviderError = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() { "use strict"; init_ProviderError(); TokenProviderError = class _TokenProviderError extends ProviderError { constructor(message, options = true) { super(message, options); this.name = "TokenProviderError"; Object.setPrototypeOf(this, _TokenProviderError.prototype); } }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js var chain; var init_chain = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js"() { "use strict"; init_ProviderError(); chain = (...providers) => async () => { if (providers.length === 0) { throw new ProviderError("No providers in chain"); } let lastProviderError; for (const provider of providers) { try { const credentials2 = await provider(); return credentials2; } catch (err2) { lastProviderError = err2; if (err2?.tryNextLink) { continue; } throw err2; } } throw lastProviderError; }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js var fromStatic; var init_fromStatic = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js"() { "use strict"; fromStatic = (staticValue) => () => Promise.resolve(staticValue); } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js var memoize; var init_memoize = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js"() { "use strict"; memoize = (provider, isExpired, requiresRefresh) => { let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = async () => { if (!pending) { pending = provider(); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = void 0; } return resolved; }; if (isExpired === void 0) { return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(); } return resolved; }; } return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(); } if (isConstant) { return resolved; } if (requiresRefresh && !requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { await coalesceProvider(); return resolved; } return resolved; }; }; } }); // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js var init_dist_es21 = __esm({ "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js"() { "use strict"; init_CredentialsProviderError(); init_ProviderError(); init_TokenProviderError(); init_chain(); init_fromStatic(); init_memoize(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js var init_resolveAwsSdkSigV4AConfig = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() { "use strict"; init_dist_es18(); init_dist_es21(); } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL; var init_constants3 = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js"() { "use strict"; ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; EXPIRES_QUERY_PARAM = "X-Amz-Expires"; SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; AUTH_HEADER = "authorization"; AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); DATE_HEADER = "date"; GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); SHA256_HEADER = "x-amz-content-sha256"; TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); ALWAYS_UNSIGNABLE_HEADERS = { authorization: true, "cache-control": true, connection: true, expect: true, from: true, "keep-alive": true, "max-forwards": true, pragma: true, referer: true, te: true, trailer: true, "transfer-encoding": true, upgrade: true, "user-agent": true, "x-amzn-trace-id": true }; PROXY_HEADER_PATTERN = /^proxy-/; SEC_HEADER_PATTERN = /^sec-/; ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; MAX_CACHE_SIZE = 50; KEY_TYPE_IDENTIFIER = "aws4_request"; MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac; var init_credentialDerivation = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() { "use strict"; init_dist_es16(); init_dist_es10(); init_constants3(); signingKeyCache = {}; cacheQueue = []; createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; getSigningKey = async (sha256Constructor, credentials2, shortDate, region, service) => { const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId); const cacheKey2 = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials2.sessionToken}`; if (cacheKey2 in signingKeyCache) { return signingKeyCache[cacheKey2]; } cacheQueue.push(cacheKey2); while (cacheQueue.length > MAX_CACHE_SIZE) { delete signingKeyCache[cacheQueue.shift()]; } let key = `AWS4${credentials2.secretAccessKey}`; for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { key = await hmac(sha256Constructor, key, signable); } return signingKeyCache[cacheKey2] = key; }; hmac = (ctor, secret, data) => { const hash = new ctor(secret); hash.update(toUint8Array(data)); return hash.digest(); }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js var getCanonicalHeaders; var init_getCanonicalHeaders = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() { "use strict"; init_constants3(); getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { const canonical = {}; for (const headerName of Object.keys(headers).sort()) { if (headers[headerName] == void 0) { continue; } const canonicalHeaderName = headerName.toLowerCase(); if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { continue; } } canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); } return canonical; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js var getPayloadHash; var init_getPayloadHash = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() { "use strict"; init_dist_es8(); init_dist_es16(); init_dist_es10(); init_constants3(); getPayloadHash = async ({ headers, body }, hashConstructor) => { for (const headerName of Object.keys(headers)) { if (headerName.toLowerCase() === SHA256_HEADER) { return headers[headerName]; } } if (body == void 0) { return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { const hashCtor = new hashConstructor(); hashCtor.update(toUint8Array(body)); return toHex(await hashCtor.digest()); } return UNSIGNED_PAYLOAD; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js function negate(bytes) { for (let i6 = 0; i6 < 8; i6++) { bytes[i6] ^= 255; } for (let i6 = 7; i6 > -1; i6--) { bytes[i6]++; if (bytes[i6] !== 0) break; } } var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64; var init_HeaderFormatter = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() { "use strict"; init_dist_es16(); init_dist_es10(); HeaderFormatter = class { format(headers) { const chunks = []; for (const headerName of Object.keys(headers)) { const bytes = fromUtf8(headerName); chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); let position = 0; for (const chunk of chunks) { out.set(chunk, position); position += chunk.byteLength; } return out; } formatHeaderValue(header) { switch (header.type) { case "boolean": return Uint8Array.from([header.value ? 0 : 1]); case "byte": return Uint8Array.from([2, header.value]); case "short": const shortView = new DataView(new ArrayBuffer(3)); shortView.setUint8(0, 3); shortView.setInt16(1, header.value, false); return new Uint8Array(shortView.buffer); case "integer": const intView = new DataView(new ArrayBuffer(5)); intView.setUint8(0, 4); intView.setInt32(1, header.value, false); return new Uint8Array(intView.buffer); case "long": const longBytes = new Uint8Array(9); longBytes[0] = 5; longBytes.set(header.value.bytes, 1); return longBytes; case "binary": const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); binView.setUint8(0, 6); binView.setUint16(1, header.value.byteLength, false); const binBytes = new Uint8Array(binView.buffer); binBytes.set(header.value, 3); return binBytes; case "string": const utf8Bytes = fromUtf8(header.value); const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); strView.setUint8(0, 7); strView.setUint16(1, utf8Bytes.byteLength, false); const strBytes = new Uint8Array(strView.buffer); strBytes.set(utf8Bytes, 3); return strBytes; case "timestamp": const tsBytes = new Uint8Array(9); tsBytes[0] = 8; tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); return tsBytes; case "uuid": if (!UUID_PATTERN.test(header.value)) { throw new Error(`Invalid UUID received: ${header.value}`); } const uuidBytes = new Uint8Array(17); uuidBytes[0] = 9; uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1); return uuidBytes; } } }; (function(HEADER_VALUE_TYPE2) { HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; Int64 = class _Int64 { constructor(bytes) { this.bytes = bytes; if (bytes.byteLength !== 8) { throw new Error("Int64 buffers must be exactly 8 bytes"); } } static fromNumber(number) { if (number > 9223372036854776e3 || number < -9223372036854776e3) { throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); } const bytes = new Uint8Array(8); for (let i6 = 7, remaining = Math.abs(Math.round(number)); i6 > -1 && remaining > 0; i6--, remaining /= 256) { bytes[i6] = remaining; } if (number < 0) { negate(bytes); } return new _Int64(bytes); } valueOf() { const bytes = this.bytes.slice(0); const negative = bytes[0] & 128; if (negative) { negate(bytes); } return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); } toString() { return String(this.valueOf()); } }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js var hasHeader; var init_headerUtil = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() { "use strict"; hasHeader = (soughtHeader, headers) => { soughtHeader = soughtHeader.toLowerCase(); for (const headerName of Object.keys(headers)) { if (soughtHeader === headerName.toLowerCase()) { return true; } } return false; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js var moveHeadersToQuery; var init_moveHeadersToQuery = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() { "use strict"; init_dist_es2(); moveHeadersToQuery = (request2, options = {}) => { const { headers, query = {} } = HttpRequest.clone(request2); for (const name of Object.keys(headers)) { const lname = name.toLowerCase(); if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { query[name] = headers[name]; delete headers[name]; } } return { ...request2, headers, query }; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js var prepareRequest; var init_prepareRequest = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() { "use strict"; init_dist_es2(); init_constants3(); prepareRequest = (request2) => { request2 = HttpRequest.clone(request2); for (const headerName of Object.keys(request2.headers)) { if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { delete request2.headers[headerName]; } } return request2; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js var getCanonicalQuery; var init_getCanonicalQuery = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() { "use strict"; init_dist_es12(); init_constants3(); getCanonicalQuery = ({ query = {} }) => { const keys = []; const serialized = {}; for (const key of Object.keys(query)) { if (key.toLowerCase() === SIGNATURE_HEADER) { continue; } const encodedKey = escapeUri(key); keys.push(encodedKey); const value = query[key]; if (typeof value === "string") { serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`; } else if (Array.isArray(value)) { serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${escapeUri(value2)}`]), []).sort().join("&"); } } return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js var iso8601, toDate; var init_utilDate = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js"() { "use strict"; iso8601 = (time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"); toDate = (time) => { if (typeof time === "number") { return new Date(time * 1e3); } if (typeof time === "string") { if (Number(time)) { return new Date(Number(time) * 1e3); } return new Date(time); } return time; }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js var SignatureV4Base; var init_SignatureV4Base = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js"() { "use strict"; init_dist_es16(); init_dist_es6(); init_dist_es12(); init_dist_es10(); init_getCanonicalQuery(); init_utilDate(); SignatureV4Base = class { constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) { this.service = service; this.sha256 = sha2562; this.uriEscapePath = uriEscapePath; this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; this.regionProvider = normalizeProvider(region); this.credentialProvider = normalizeProvider(credentials2); } createCanonicalRequest(request2, canonicalHeaders, payloadHash) { const sortedHeaders = Object.keys(canonicalHeaders).sort(); return `${request2.method} ${this.getCanonicalPath(request2)} ${getCanonicalQuery(request2)} ${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} ${sortedHeaders.join(";")} ${payloadHash}`; } async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { const hash = new this.sha256(); hash.update(toUint8Array(canonicalRequest)); const hashedRequest = await hash.digest(); return `${algorithmIdentifier} ${longDate} ${credentialScope} ${toHex(hashedRequest)}`; } getCanonicalPath({ path: path3 }) { if (this.uriEscapePath) { const normalizedPathSegments = []; for (const pathSegment of path3.split("/")) { if (pathSegment?.length === 0) continue; if (pathSegment === ".") continue; if (pathSegment === "..") { normalizedPathSegments.pop(); } else { normalizedPathSegments.push(pathSegment); } } const normalizedPath = `${path3?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path3?.endsWith("/") ? "/" : ""}`; const doubleEncoded = escapeUri(normalizedPath); return doubleEncoded.replace(/%2F/g, "/"); } return path3; } validateResolvedCredentials(credentials2) { if (typeof credentials2 !== "object" || typeof credentials2.accessKeyId !== "string" || typeof credentials2.secretAccessKey !== "string") { throw new Error("Resolved credential object is not valid"); } } formatDate(now) { const longDate = iso8601(now).replace(/[\-:]/g, ""); return { longDate, shortDate: longDate.slice(0, 8) }; } getCanonicalHeaderList(headers) { return Object.keys(headers).sort().join(";"); } }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js var SignatureV4; var init_SignatureV4 = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() { "use strict"; init_dist_es16(); init_dist_es10(); init_constants3(); init_credentialDerivation(); init_getCanonicalHeaders(); init_getPayloadHash(); init_HeaderFormatter(); init_headerUtil(); init_moveHeadersToQuery(); init_prepareRequest(); init_SignatureV4Base(); SignatureV4 = class extends SignatureV4Base { constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) { super({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath }); this.headerFormatter = new HeaderFormatter(); } async presign(originalRequest, options = {}) { const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options; const credentials2 = await this.credentialProvider(); this.validateResolvedCredentials(credentials2); const region = signingRegion ?? await this.regionProvider(); const { longDate, shortDate } = this.formatDate(signingDate); if (expiresIn > MAX_PRESIGNED_TTL) { return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future"); } const scope = createScope(shortDate, region, signingService ?? this.service); const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); if (credentials2.sessionToken) { request2.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken; } request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`; request2.query[AMZ_DATE_QUERY_PARAM] = longDate; request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders); request2.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); return request2; } async sign(toSign, options) { if (typeof toSign === "string") { return this.signString(toSign, options); } else if (toSign.headers && toSign.payload) { return this.signEvent(toSign, options); } else if (toSign.message) { return this.signMessage(toSign, options); } else { return this.signRequest(toSign, options); } } async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { const region = signingRegion ?? await this.regionProvider(); const { shortDate, longDate } = this.formatDate(signingDate); const scope = createScope(shortDate, region, signingService ?? this.service); const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); const hash = new this.sha256(); hash.update(headers); const hashedHeaders = toHex(await hash.digest()); const stringToSign = [ EVENT_ALGORITHM_IDENTIFIER, longDate, scope, priorSignature, hashedHeaders, hashedPayload ].join("\n"); return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); } async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { const promise = this.signEvent({ headers: this.headerFormatter.format(signableMessage.message.headers), payload: signableMessage.message.body }, { signingDate, signingRegion, signingService, priorSignature: signableMessage.priorSignature }); return promise.then((signature) => { return { message: signableMessage.message, signature }; }); } async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { const credentials2 = await this.credentialProvider(); this.validateResolvedCredentials(credentials2); const region = signingRegion ?? await this.regionProvider(); const { shortDate } = this.formatDate(signingDate); const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService)); hash.update(toUint8Array(stringToSign)); return toHex(await hash.digest()); } async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { const credentials2 = await this.credentialProvider(); this.validateResolvedCredentials(credentials2); const region = signingRegion ?? await this.regionProvider(); const request2 = prepareRequest(requestToSign); const { longDate, shortDate } = this.formatDate(signingDate); const scope = createScope(shortDate, region, signingService ?? this.service); request2.headers[AMZ_DATE_HEADER] = longDate; if (credentials2.sessionToken) { request2.headers[TOKEN_HEADER] = credentials2.sessionToken; } const payloadHash = await getPayloadHash(request2, this.sha256); if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) { request2.headers[SHA256_HEADER] = payloadHash; } const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders); const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash)); request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; return request2; } async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); const hash = new this.sha256(await keyPromise); hash.update(toUint8Array(stringToSign)); return toHex(await hash.digest()); } getSigningKey(credentials2, region, shortDate, service) { return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service); } }; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js var init_signature_v4a_container = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js var init_dist_es22 = __esm({ "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js"() { "use strict"; init_SignatureV4(); init_constants3(); init_getCanonicalHeaders(); init_getCanonicalQuery(); init_getPayloadHash(); init_moveHeadersToQuery(); init_prepareRequest(); init_credentialDerivation(); init_SignatureV4Base(); init_headerUtil(); init_signature_v4a_container(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js function normalizeCredentialProvider(config, { credentials: credentials2, credentialDefaultProvider }) { let credentialsProvider; if (credentials2) { if (!credentials2?.memoized) { credentialsProvider = memoizeIdentityProvider(credentials2, isIdentityExpired, doesIdentityRequireRefresh); } else { credentialsProvider = credentials2; } } else { if (credentialDefaultProvider) { credentialsProvider = normalizeProvider2(credentialDefaultProvider(Object.assign({}, config, { parentClientConfig: config }))); } else { credentialsProvider = async () => { throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); }; } } credentialsProvider.memoized = true; return credentialsProvider; } function bindCallerConfig(config, credentialsProvider) { if (credentialsProvider.configBound) { return credentialsProvider; } const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); fn.memoized = credentialsProvider.memoized; fn.configBound = true; return fn; } var resolveAwsSdkSigV4Config; var init_resolveAwsSdkSigV4Config = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() { "use strict"; init_client2(); init_dist_es18(); init_dist_es22(); resolveAwsSdkSigV4Config = (config) => { let inputCredentials = config.credentials; let isUserSupplied = !!config.credentials; let resolvedCredentials = void 0; Object.defineProperty(config, "credentials", { set(credentials2) { if (credentials2 && credentials2 !== inputCredentials && credentials2 !== resolvedCredentials) { isUserSupplied = true; } inputCredentials = credentials2; const memoizedProvider = normalizeCredentialProvider(config, { credentials: inputCredentials, credentialDefaultProvider: config.credentialDefaultProvider }); const boundProvider = bindCallerConfig(config, memoizedProvider); if (isUserSupplied && !boundProvider.attributed) { resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); resolvedCredentials.memoized = boundProvider.memoized; resolvedCredentials.configBound = boundProvider.configBound; resolvedCredentials.attributed = true; } else { resolvedCredentials = boundProvider; } }, get() { return resolvedCredentials; }, enumerable: true, configurable: true }); config.credentials = inputCredentials; const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256: sha2562 } = config; let signer; if (config.signer) { signer = normalizeProvider2(config.signer); } else if (config.regionInfoProvider) { signer = () => normalizeProvider2(config.region)().then(async (region) => [ await config.regionInfoProvider(region, { useFipsEndpoint: await config.useFipsEndpoint(), useDualstackEndpoint: await config.useDualstackEndpoint() }) || {}, region ]).then(([regionInfo, region]) => { const { signingRegion, signingService } = regionInfo; config.signingRegion = config.signingRegion || signingRegion || region; config.signingName = config.signingName || signingService || config.serviceId; const params = { ...config, credentials: config.credentials, region: config.signingRegion, service: config.signingName, sha256: sha2562, uriEscapePath: signingEscapePath }; const SignerCtor = config.signerConstructor || SignatureV4; return new SignerCtor(params); }); } else { signer = async (authScheme) => { authScheme = Object.assign({}, { name: "sigv4", signingName: config.signingName || config.defaultSigningName, signingRegion: await normalizeProvider2(config.region)(), properties: {} }, authScheme); const signingRegion = authScheme.signingRegion; const signingService = authScheme.signingName; config.signingRegion = config.signingRegion || signingRegion; config.signingName = config.signingName || signingService || config.serviceId; const params = { ...config, credentials: config.credentials, region: config.signingRegion, service: config.signingName, sha256: sha2562, uriEscapePath: signingEscapePath }; const SignerCtor = config.signerConstructor || SignatureV4; return new SignerCtor(params); }; } const resolvedConfig = Object.assign(config, { systemClockOffset, signingEscapePath, signer }); return resolvedConfig; }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js var init_aws_sdk = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() { "use strict"; init_AwsSdkSigV4Signer(); init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS(); init_resolveAwsSdkSigV4AConfig(); init_resolveAwsSdkSigV4Config(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js var init_httpAuthSchemes2 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() { "use strict"; init_aws_sdk(); init_getBearerTokenEnvKey(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js var init_coercing_serializers = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights; var init_MiddlewareStack = __esm({ "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() { "use strict"; getAllAliases = (name, aliases) => { const _aliases = []; if (name) { _aliases.push(name); } if (aliases) { for (const alias of aliases) { _aliases.push(alias); } } return _aliases; }; getMiddlewareNameWithAliases = (name, aliases) => { return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; }; constructStack = () => { let absoluteEntries = []; let relativeEntries = []; let identifyOnResolve = false; const entriesNameSet = /* @__PURE__ */ new Set(); const sort = (entries) => entries.sort((a5, b5) => stepWeights[b5.step] - stepWeights[a5.step] || priorityWeights[b5.priority || "normal"] - priorityWeights[a5.priority || "normal"]); const removeByName = (toRemove) => { let isRemoved = false; const filterCb = (entry) => { const aliases = getAllAliases(entry.name, entry.aliases); if (aliases.includes(toRemove)) { isRemoved = true; for (const alias of aliases) { entriesNameSet.delete(alias); } return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }; const removeByReference = (toRemove) => { let isRemoved = false; const filterCb = (entry) => { if (entry.middleware === toRemove) { isRemoved = true; for (const alias of getAllAliases(entry.name, entry.aliases)) { entriesNameSet.delete(alias); } return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }; const cloneTo = (toStack) => { absoluteEntries.forEach((entry) => { toStack.add(entry.middleware, { ...entry }); }); relativeEntries.forEach((entry) => { toStack.addRelativeTo(entry.middleware, { ...entry }); }); toStack.identifyOnResolve?.(stack.identifyOnResolve()); return toStack; }; const expandRelativeMiddlewareList = (from) => { const expandedMiddlewareList = []; from.before.forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); expandedMiddlewareList.push(from); from.after.reverse().forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); return expandedMiddlewareList; }; const getMiddlewareList = (debug = false) => { const normalizedAbsoluteEntries = []; const normalizedRelativeEntries = []; const normalizedEntriesNameMap = {}; absoluteEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [] }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedAbsoluteEntries.push(normalizedEntry); }); relativeEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [] }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedRelativeEntries.push(normalizedEntry); }); normalizedRelativeEntries.forEach((entry) => { if (entry.toMiddleware) { const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; if (toMiddleware === void 0) { if (debug) { return; } throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`); } if (entry.relation === "after") { toMiddleware.after.push(entry); } if (entry.relation === "before") { toMiddleware.before.push(entry); } } }); const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { wholeList.push(...expandedMiddlewareList); return wholeList; }, []); return mainChain; }; const stack = { add: (middleware, options = {}) => { const { name, override, aliases: _aliases } = options; const entry = { step: "initialize", priority: "normal", middleware, ...options }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); if (toOverrideIndex === -1) { continue; } const toOverride = absoluteEntries[toOverrideIndex]; if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`); } absoluteEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } absoluteEntries.push(entry); }, addRelativeTo: (middleware, options) => { const { name, override, aliases: _aliases } = options; const entry = { middleware, ...options }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); if (toOverrideIndex === -1) { continue; } const toOverride = relativeEntries[toOverrideIndex]; if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`); } relativeEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } relativeEntries.push(entry); }, clone: () => cloneTo(constructStack()), use: (plugin) => { plugin.applyToStack(stack); }, remove: (toRemove) => { if (typeof toRemove === "string") return removeByName(toRemove); else return removeByReference(toRemove); }, removeByTag: (toRemove) => { let isRemoved = false; const filterCb = (entry) => { const { tags, name, aliases: _aliases } = entry; if (tags && tags.includes(toRemove)) { const aliases = getAllAliases(name, _aliases); for (const alias of aliases) { entriesNameSet.delete(alias); } isRemoved = true; return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }, concat: (from) => { const cloned = cloneTo(constructStack()); cloned.use(from); cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); return cloned; }, applyToStack: cloneTo, identify: () => { return getMiddlewareList(true).map((mw) => { const step = mw.step ?? mw.relation + " " + mw.toMiddleware; return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; }); }, identifyOnResolve(toggle) { if (typeof toggle === "boolean") identifyOnResolve = toggle; return identifyOnResolve; }, resolve: (handler, context) => { for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { handler = middleware(handler, context); } if (identifyOnResolve) { console.log(stack.identify()); } return handler; } }; return stack; }; stepWeights = { initialize: 5, serialize: 4, build: 3, finalizeRequest: 2, deserialize: 1 }; priorityWeights = { high: 3, normal: 2, low: 1 }; } }); // ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js var init_dist_es23 = __esm({ "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js"() { "use strict"; init_MiddlewareStack(); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js var Client; var init_client3 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js"() { "use strict"; init_dist_es23(); Client = class { constructor(config) { this.config = config; this.middlewareStack = constructStack(); } send(command, optionsOrCb, cb) { const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; let handler; if (useHandlerCache) { if (!this.handlers) { this.handlers = /* @__PURE__ */ new WeakMap(); } const handlers = this.handlers; if (handlers.has(command.constructor)) { handler = handlers.get(command.constructor); } else { handler = command.resolveMiddleware(this.middlewareStack, this.config, options); handlers.set(command.constructor, handler); } } else { delete this.handlers; handler = command.resolveMiddleware(this.middlewareStack, this.config, options); } if (callback) { handler(command).then((result) => callback(null, result.output), (err2) => callback(err2)).catch(() => { }); } else { return handler(command).then((result) => result.output); } } destroy() { this.config?.requestHandler?.destroy?.(); delete this.handlers; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js var init_collect_stream_body2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() { "use strict"; init_protocols(); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js var Command, ClassBuilder; var init_command2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js"() { "use strict"; init_dist_es23(); init_dist_es(); Command = class { constructor() { this.middlewareStack = constructStack(); } static classBuilder() { return new ClassBuilder(); } resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) { for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { this.middlewareStack.use(mw); } const stack = clientStack.concat(this.middlewareStack); const { logger: logger2 } = configuration; const handlerExecutionContext = { logger: logger2, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, [SMITHY_CONTEXT_KEY]: { commandInstance: this, ...smithyContext }, ...additionalContext }; const { requestHandler } = configuration; return stack.resolve((request2) => requestHandler.handle(request2.request, options || {}), handlerExecutionContext); } }; ClassBuilder = class { constructor() { this._init = () => { }; this._ep = {}; this._middlewareFn = () => []; this._commandName = ""; this._clientName = ""; this._additionalContext = {}; this._smithyContext = {}; this._inputFilterSensitiveLog = (_3) => _3; this._outputFilterSensitiveLog = (_3) => _3; this._serializer = null; this._deserializer = null; } init(cb) { this._init = cb; } ep(endpointParameterInstructions) { this._ep = endpointParameterInstructions; return this; } m(middlewareSupplier) { this._middlewareFn = middlewareSupplier; return this; } s(service, operation, smithyContext = {}) { this._smithyContext = { service, operation, ...smithyContext }; return this; } c(additionalContext = {}) { this._additionalContext = additionalContext; return this; } n(clientName, commandName) { this._clientName = clientName; this._commandName = commandName; return this; } f(inputFilter = (_3) => _3, outputFilter = (_3) => _3) { this._inputFilterSensitiveLog = inputFilter; this._outputFilterSensitiveLog = outputFilter; return this; } ser(serializer) { this._serializer = serializer; return this; } de(deserializer) { this._deserializer = deserializer; return this; } sc(operation) { this._operationSchema = operation; this._smithyContext.operationSchema = operation; return this; } build() { const closure = this; let CommandRef; return CommandRef = class extends Command { static getEndpointParameterInstructions() { return closure._ep; } constructor(...[input]) { super(); this.serialize = closure._serializer; this.deserialize = closure._deserializer; this.input = input ?? {}; closure._init(this); this.schema = closure._operationSchema; } resolveMiddleware(stack, configuration, options) { return this.resolveMiddlewareWithContext(stack, configuration, options, { CommandCtor: CommandRef, middlewareFn: closure._middlewareFn, clientName: closure._clientName, commandName: closure._commandName, inputFilterSensitiveLog: closure._inputFilterSensitiveLog, outputFilterSensitiveLog: closure._outputFilterSensitiveLog, smithyContext: closure._smithyContext, additionalContext: closure._additionalContext }); } }; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js var SENSITIVE_STRING; var init_constants4 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js"() { "use strict"; SENSITIVE_STRING = "***SensitiveInformation***"; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js var createAggregatedClient; var init_create_aggregated_client = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() { "use strict"; createAggregatedClient = (commands5, Client2) => { for (const command of Object.keys(commands5)) { const CommandCtor = commands5[command]; const methodImpl = async function(args, optionsOrCb, cb) { const command2 = new CommandCtor(args); if (typeof optionsOrCb === "function") { this.send(command2, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expected http options but got ${typeof optionsOrCb}`); this.send(command2, optionsOrCb || {}, cb); } else { return this.send(command2, optionsOrCb); } }; const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); Client2.prototype[methodName] = methodImpl; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js var ServiceException, decorateServiceException; var init_exceptions = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js"() { "use strict"; ServiceException = class _ServiceException extends Error { constructor(options) { super(options.message); Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); this.name = options.name; this.$fault = options.$fault; this.$metadata = options.$metadata; } static isInstance(value) { if (!value) return false; const candidate = value; return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); } static [Symbol.hasInstance](instance) { if (!instance) return false; const candidate = instance; if (this === _ServiceException) { return _ServiceException.isInstance(instance); } if (_ServiceException.isInstance(instance)) { if (candidate.name && this.name) { return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; } return this.prototype.isPrototypeOf(instance); } return false; } }; decorateServiceException = (exception, additions = {}) => { Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k5, v6]) => { if (exception[k5] == void 0 || exception[k5] === "") { exception[k5] = v6; } }); const message = exception.message || exception.Message || "UnknownError"; exception.message = message; delete exception.Message; return exception; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js var throwDefaultError, withBaseException, deserializeMetadata; var init_default_error_handler = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() { "use strict"; init_exceptions(); throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { const $metadata = deserializeMetadata(output); const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; const response = new exceptionCtor({ name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", $fault: "client", $metadata }); throw decorateServiceException(response, parsedBody); }; withBaseException = (ExceptionCtor) => { return ({ output, parsedBody, errorCode }) => { throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); }; }; deserializeMetadata = (output) => ({ httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"] }); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js var loadConfigsForDefaultMode; var init_defaults_mode = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() { "use strict"; loadConfigsForDefaultMode = (mode) => { switch (mode) { case "standard": return { retryMode: "standard", connectionTimeout: 3100 }; case "in-region": return { retryMode: "standard", connectionTimeout: 1100 }; case "cross-region": return { retryMode: "standard", connectionTimeout: 3100 }; case "mobile": return { retryMode: "standard", connectionTimeout: 3e4 }; default: return {}; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js var warningEmitted, emitWarningIfUnsupportedVersion2; var init_emitWarningIfUnsupportedVersion2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() { "use strict"; warningEmitted = false; emitWarningIfUnsupportedVersion2 = (version) => { if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { warningEmitted = true; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js var init_extended_encode_uri_component2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() { "use strict"; init_protocols(); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js var getChecksumConfiguration2, resolveChecksumRuntimeConfig2; var init_checksum3 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() { "use strict"; init_dist_es(); getChecksumConfiguration2 = (runtimeConfig) => { const checksumAlgorithms = []; for (const id in AlgorithmId) { const algorithmId = AlgorithmId[id]; if (runtimeConfig[algorithmId] === void 0) { continue; } checksumAlgorithms.push({ algorithmId: () => algorithmId, checksumConstructor: () => runtimeConfig[algorithmId] }); } return { addChecksumAlgorithm(algo) { checksumAlgorithms.push(algo); }, checksumAlgorithms() { return checksumAlgorithms; } }; }; resolveChecksumRuntimeConfig2 = (clientConfig) => { const runtimeConfig = {}; clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); return runtimeConfig; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js var getRetryConfiguration, resolveRetryRuntimeConfig; var init_retry2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() { "use strict"; getRetryConfiguration = (runtimeConfig) => { return { setRetryStrategy(retryStrategy) { runtimeConfig.retryStrategy = retryStrategy; }, retryStrategy() { return runtimeConfig.retryStrategy; } }; }; resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { const runtimeConfig = {}; runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); return runtimeConfig; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig; var init_defaultExtensionConfiguration2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() { "use strict"; init_checksum3(); init_retry2(); getDefaultExtensionConfiguration = (runtimeConfig) => { return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration(runtimeConfig)); }; resolveDefaultRuntimeConfig = (config) => { return Object.assign(resolveChecksumRuntimeConfig2(config), resolveRetryRuntimeConfig(config)); }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js var init_extensions3 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() { "use strict"; init_defaultExtensionConfiguration2(); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js var init_get_array_if_single_item = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js var getValueFromTextNode; var init_get_value_from_text_node = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() { "use strict"; getValueFromTextNode = (obj) => { const textNodeName = "#text"; for (const key in obj) { if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { obj[key] = obj[key][textNodeName]; } else if (typeof obj[key] === "object" && obj[key] !== null) { obj[key] = getValueFromTextNode(obj[key]); } } return obj; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js var isSerializableHeaderValue; var init_is_serializable_header_value = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js"() { "use strict"; isSerializableHeaderValue = (value) => { return value != null; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js var NoOpLogger; var init_NoOpLogger = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() { "use strict"; NoOpLogger = class { trace() { } debug() { } info() { } warn() { } error() { } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js function map(arg0, arg1, arg2) { let target; let filter2; let instructions; if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { target = {}; instructions = arg0; } else { target = arg0; if (typeof arg1 === "function") { filter2 = arg1; instructions = arg2; return mapWithFilter(target, filter2, instructions); } else { instructions = arg1; } } for (const key of Object.keys(instructions)) { if (!Array.isArray(instructions[key])) { target[key] = instructions[key]; continue; } applyInstruction(target, null, instructions, key); } return target; } var take, mapWithFilter, applyInstruction, nonNullish, pass; var init_object_mapping = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() { "use strict"; take = (source, instructions) => { const out = {}; for (const key in instructions) { applyInstruction(out, source, instructions, key); } return out; }; mapWithFilter = (target, filter2, instructions) => { return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { if (Array.isArray(value)) { _instructions[key] = value; } else { if (typeof value === "function") { _instructions[key] = [filter2, value()]; } else { _instructions[key] = [filter2, value]; } } return _instructions; }, {})); }; applyInstruction = (target, source, instructions, targetKey) => { if (source !== null) { let instruction = instructions[targetKey]; if (typeof instruction === "function") { instruction = [, instruction]; } const [filter3 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) { target[targetKey] = valueFn(source[sourceKey]); } return; } let [filter2, value] = instructions[targetKey]; if (typeof value === "function") { let _value; const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null; const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2; if (defaultFilterPassed) { target[targetKey] = _value; } else if (customFilterPassed) { target[targetKey] = value(); } } else { const defaultFilterPassed = filter2 === void 0 && value != null; const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2; if (defaultFilterPassed || customFilterPassed) { target[targetKey] = value; } } }; nonNullish = (_3) => _3 != null; pass = (_3) => _3; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js var init_resolve_path2 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() { "use strict"; init_protocols(); } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js var serializeFloat; var init_ser_utils = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() { "use strict"; serializeFloat = (value) => { if (value !== value) { return "NaN"; } switch (value) { case Infinity: return "Infinity"; case -Infinity: return "-Infinity"; default: return value; } }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js var _json; var init_serde_json = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js"() { "use strict"; _json = (obj) => { if (obj == null) { return {}; } if (Array.isArray(obj)) { return obj.filter((_3) => _3 != null).map(_json); } if (typeof obj === "object") { const target = {}; for (const key of Object.keys(obj)) { if (obj[key] == null) { continue; } target[key] = _json(obj[key]); } return target; } return obj; }; } }); // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js var init_dist_es24 = __esm({ "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js"() { "use strict"; init_client3(); init_collect_stream_body2(); init_command2(); init_constants4(); init_create_aggregated_client(); init_default_error_handler(); init_defaults_mode(); init_emitWarningIfUnsupportedVersion2(); init_exceptions(); init_extended_encode_uri_component2(); init_extensions3(); init_get_array_if_single_item(); init_get_value_from_text_node(); init_is_serializable_header_value(); init_NoOpLogger(); init_object_mapping(); init_resolve_path2(); init_ser_utils(); init_serde_json(); init_serde2(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js var awsExpectUnion; var init_awsExpectUnion = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() { "use strict"; init_dist_es24(); awsExpectUnion = (value) => { if (value == null) { return void 0; } if (typeof value === "object" && "__type" in value) { delete value.__type; } return expectUnion(value); }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js var collectBodyString; var init_common2 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() { "use strict"; init_dist_es24(); collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body)); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode; var init_parseJsonBody = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() { "use strict"; init_common2(); parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { try { return JSON.parse(encoded); } catch (e6) { if (e6?.name === "SyntaxError") { Object.defineProperty(e6, "$responseBodyText", { value: encoded }); } throw e6; } } return {}; }); parseJsonErrorBody = async (errorBody, context) => { const value = await parseJsonBody(errorBody, context); value.message = value.message ?? value.Message; return value; }; loadRestJsonErrorCode = (output, data) => { const findKey = (object, key) => Object.keys(object).find((k5) => k5.toLowerCase() === key.toLowerCase()); const sanitizeErrorCode = (rawValue) => { let cleanValue = rawValue; if (typeof cleanValue === "number") { cleanValue = cleanValue.toString(); } if (cleanValue.indexOf(",") >= 0) { cleanValue = cleanValue.split(",")[0]; } if (cleanValue.indexOf(":") >= 0) { cleanValue = cleanValue.split(":")[0]; } if (cleanValue.indexOf("#") >= 0) { cleanValue = cleanValue.split("#")[1]; } return cleanValue; }; const headerKey = findKey(output.headers, "x-amzn-errortype"); if (headerKey !== void 0) { return sanitizeErrorCode(output.headers[headerKey]); } if (data && typeof data === "object") { const codeKey = findKey(data, "code"); if (codeKey && data[codeKey] !== void 0) { return sanitizeErrorCode(data[codeKey]); } if (data["__type"] !== void 0) { return sanitizeErrorCode(data["__type"]); } } }; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js var require_util2 = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports2) { "use strict"; var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; var regexName = new RegExp("^" + nameRegexp + "$"); var getAllMatches = function(string, regex) { const matches = []; let match2 = regex.exec(string); while (match2) { const allmatches = []; allmatches.startIndex = regex.lastIndex - match2[0].length; const len = match2.length; for (let index6 = 0; index6 < len; index6++) { allmatches.push(match2[index6]); } matches.push(allmatches); match2 = regex.exec(string); } return matches; }; var isName = function(string) { const match2 = regexName.exec(string); return !(match2 === null || typeof match2 === "undefined"); }; exports2.isExist = function(v6) { return typeof v6 !== "undefined"; }; exports2.isEmptyObject = function(obj) { return Object.keys(obj).length === 0; }; exports2.merge = function(target, a5, arrayMode) { if (a5) { const keys = Object.keys(a5); const len = keys.length; for (let i6 = 0; i6 < len; i6++) { if (arrayMode === "strict") { target[keys[i6]] = [a5[keys[i6]]]; } else { target[keys[i6]] = a5[keys[i6]]; } } } }; exports2.getValue = function(v6) { if (exports2.isExist(v6)) { return v6; } else { return ""; } }; exports2.isName = isName; exports2.getAllMatches = getAllMatches; exports2.nameRegexp = nameRegexp; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js var require_validator = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports2) { "use strict"; var util2 = require_util2(); var defaultOptions = { allowBooleanAttributes: false, //A tag can have attributes without any value unpairedTags: [] }; exports2.validate = function(xmlData, options) { options = Object.assign({}, defaultOptions, options); const tags = []; let tagFound = false; let reachedRoot = false; if (xmlData[0] === "\uFEFF") { xmlData = xmlData.substr(1); } for (let i6 = 0; i6 < xmlData.length; i6++) { if (xmlData[i6] === "<" && xmlData[i6 + 1] === "?") { i6 += 2; i6 = readPI(xmlData, i6); if (i6.err) return i6; } else if (xmlData[i6] === "<") { let tagStartPos = i6; i6++; if (xmlData[i6] === "!") { i6 = readCommentAndCDATA(xmlData, i6); continue; } else { let closingTag = false; if (xmlData[i6] === "/") { closingTag = true; i6++; } let tagName = ""; for (; i6 < xmlData.length && xmlData[i6] !== ">" && xmlData[i6] !== " " && xmlData[i6] !== " " && xmlData[i6] !== "\n" && xmlData[i6] !== "\r"; i6++) { tagName += xmlData[i6]; } tagName = tagName.trim(); if (tagName[tagName.length - 1] === "/") { tagName = tagName.substring(0, tagName.length - 1); i6--; } if (!validateTagName(tagName)) { let msg; if (tagName.trim().length === 0) { msg = "Invalid space after '<'."; } else { msg = "Tag '" + tagName + "' is an invalid name."; } return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i6)); } const result = readAttributeStr(xmlData, i6); if (result === false) { return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i6)); } let attrStr = result.value; i6 = result.index; if (attrStr[attrStr.length - 1] === "/") { const attrStrStart = i6 - attrStr.length; attrStr = attrStr.substring(0, attrStr.length - 1); const isValid2 = validateAttributeString(attrStr, options); if (isValid2 === true) { tagFound = true; } else { return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line)); } } else if (closingTag) { if (!result.tagClosed) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i6)); } else if (attrStr.trim().length > 0) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); } else if (tags.length === 0) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); } else { const otg = tags.pop(); if (tagName !== otg.tagName) { let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); return getErrorObject( "InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos) ); } if (tags.length == 0) { reachedRoot = true; } } } else { const isValid2 = validateAttributeString(attrStr, options); if (isValid2 !== true) { return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i6 - attrStr.length + isValid2.err.line)); } if (reachedRoot === true) { return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i6)); } else if (options.unpairedTags.indexOf(tagName) !== -1) { } else { tags.push({ tagName, tagStartPos }); } tagFound = true; } for (i6++; i6 < xmlData.length; i6++) { if (xmlData[i6] === "<") { if (xmlData[i6 + 1] === "!") { i6++; i6 = readCommentAndCDATA(xmlData, i6); continue; } else if (xmlData[i6 + 1] === "?") { i6 = readPI(xmlData, ++i6); if (i6.err) return i6; } else { break; } } else if (xmlData[i6] === "&") { const afterAmp = validateAmpersand(xmlData, i6); if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i6)); i6 = afterAmp; } else { if (reachedRoot === true && !isWhiteSpace(xmlData[i6])) { return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i6)); } } } if (xmlData[i6] === "<") { i6--; } } } else { if (isWhiteSpace(xmlData[i6])) { continue; } return getErrorObject("InvalidChar", "char '" + xmlData[i6] + "' is not expected.", getLineNumberForPosition(xmlData, i6)); } } if (!tagFound) { return getErrorObject("InvalidXml", "Start tag expected.", 1); } else if (tags.length == 1) { return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); } else if (tags.length > 0) { return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t6) => t6.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); } return true; }; function isWhiteSpace(char) { return char === " " || char === " " || char === "\n" || char === "\r"; } function readPI(xmlData, i6) { const start = i6; for (; i6 < xmlData.length; i6++) { if (xmlData[i6] == "?" || xmlData[i6] == " ") { const tagname = xmlData.substr(start, i6 - start); if (i6 > 5 && tagname === "xml") { return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i6)); } else if (xmlData[i6] == "?" && xmlData[i6 + 1] == ">") { i6++; break; } else { continue; } } } return i6; } function readCommentAndCDATA(xmlData, i6) { if (xmlData.length > i6 + 5 && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === "-") { for (i6 += 3; i6 < xmlData.length; i6++) { if (xmlData[i6] === "-" && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === ">") { i6 += 2; break; } } } else if (xmlData.length > i6 + 8 && xmlData[i6 + 1] === "D" && xmlData[i6 + 2] === "O" && xmlData[i6 + 3] === "C" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "Y" && xmlData[i6 + 6] === "P" && xmlData[i6 + 7] === "E") { let angleBracketsCount = 1; for (i6 += 8; i6 < xmlData.length; i6++) { if (xmlData[i6] === "<") { angleBracketsCount++; } else if (xmlData[i6] === ">") { angleBracketsCount--; if (angleBracketsCount === 0) { break; } } } } else if (xmlData.length > i6 + 9 && xmlData[i6 + 1] === "[" && xmlData[i6 + 2] === "C" && xmlData[i6 + 3] === "D" && xmlData[i6 + 4] === "A" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "A" && xmlData[i6 + 7] === "[") { for (i6 += 8; i6 < xmlData.length; i6++) { if (xmlData[i6] === "]" && xmlData[i6 + 1] === "]" && xmlData[i6 + 2] === ">") { i6 += 2; break; } } } return i6; } var doubleQuote = '"'; var singleQuote = "'"; function readAttributeStr(xmlData, i6) { let attrStr = ""; let startChar = ""; let tagClosed = false; for (; i6 < xmlData.length; i6++) { if (xmlData[i6] === doubleQuote || xmlData[i6] === singleQuote) { if (startChar === "") { startChar = xmlData[i6]; } else if (startChar !== xmlData[i6]) { } else { startChar = ""; } } else if (xmlData[i6] === ">") { if (startChar === "") { tagClosed = true; break; } } attrStr += xmlData[i6]; } if (startChar !== "") { return false; } return { value: attrStr, index: i6, tagClosed }; } var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); function validateAttributeString(attrStr, options) { const matches = util2.getAllMatches(attrStr, validAttrStrRegxp); const attrNames = {}; for (let i6 = 0; i6 < matches.length; i6++) { if (matches[i6][1].length === 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' has no space in starting.", getPositionFromMatch(matches[i6])); } else if (matches[i6][3] !== void 0 && matches[i6][4] === void 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' is without value.", getPositionFromMatch(matches[i6])); } else if (matches[i6][3] === void 0 && !options.allowBooleanAttributes) { return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i6][2] + "' is not allowed.", getPositionFromMatch(matches[i6])); } const attrName = matches[i6][2]; if (!validateAttrName(attrName)) { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i6])); } if (!attrNames.hasOwnProperty(attrName)) { attrNames[attrName] = 1; } else { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i6])); } } return true; } function validateNumberAmpersand(xmlData, i6) { let re = /\d/; if (xmlData[i6] === "x") { i6++; re = /[\da-fA-F]/; } for (; i6 < xmlData.length; i6++) { if (xmlData[i6] === ";") return i6; if (!xmlData[i6].match(re)) break; } return -1; } function validateAmpersand(xmlData, i6) { i6++; if (xmlData[i6] === ";") return -1; if (xmlData[i6] === "#") { i6++; return validateNumberAmpersand(xmlData, i6); } let count = 0; for (; i6 < xmlData.length; i6++, count++) { if (xmlData[i6].match(/\w/) && count < 20) continue; if (xmlData[i6] === ";") break; return -1; } return i6; } function getErrorObject(code, message, lineNumber) { return { err: { code, msg: message, line: lineNumber.line || lineNumber, col: lineNumber.col } }; } function validateAttrName(attrName) { return util2.isName(attrName); } function validateTagName(tagname) { return util2.isName(tagname); } function getLineNumberForPosition(xmlData, index6) { const lines = xmlData.substring(0, index6).split(/\r?\n/); return { line: lines.length, // column number is last line's length + 1, because column numbering starts at 1: col: lines[lines.length - 1].length + 1 }; } function getPositionFromMatch(match2) { return match2.startIndex + match2[1].length; } } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js var require_OptionsBuilder = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) { "use strict"; var defaultOptions = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, // remove NS from tag name or attribute name if true allowBooleanAttributes: false, //a tag can have attributes without any value //ignoreRootElement : false, parseTagValue: true, parseAttributeValue: false, trimValues: true, //Trim string values of tag and attributes cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(tagName, val2) { return val2; }, attributeValueProcessor: function(attrName, val2) { return val2; }, stopNodes: [], //nested tags will not be parsed even for errors alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(tagName, jPath, attrs) { return tagName; } // skipEmptyListItem: false }; var buildOptions = function(options) { return Object.assign({}, defaultOptions, options); }; exports2.buildOptions = buildOptions; exports2.defaultOptions = defaultOptions; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js var require_xmlNode = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) { "use strict"; var XmlNode = class { constructor(tagname) { this.tagname = tagname; this.child = []; this[":@"] = {}; } add(key, val2) { if (key === "__proto__") key = "#__proto__"; this.child.push({ [key]: val2 }); } addChild(node) { if (node.tagname === "__proto__") node.tagname = "#__proto__"; if (node[":@"] && Object.keys(node[":@"]).length > 0) { this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); } else { this.child.push({ [node.tagname]: node.child }); } } }; module2.exports = XmlNode; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js var require_DocTypeReader = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) { "use strict"; var util2 = require_util2(); function readDocType(xmlData, i6) { const entities = {}; if (xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "C" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "Y" && xmlData[i6 + 7] === "P" && xmlData[i6 + 8] === "E") { i6 = i6 + 9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = ""; for (; i6 < xmlData.length; i6++) { if (xmlData[i6] === "<" && !comment) { if (hasBody && isEntity(xmlData, i6)) { i6 += 7; [entityName, val, i6] = readEntityExp(xmlData, i6 + 1); if (val.indexOf("&") === -1) entities[validateEntityName(entityName)] = { regx: RegExp(`&${entityName};`, "g"), val }; } else if (hasBody && isElement(xmlData, i6)) i6 += 8; else if (hasBody && isAttlist(xmlData, i6)) i6 += 8; else if (hasBody && isNotation(xmlData, i6)) i6 += 9; else if (isComment) comment = true; else throw new Error("Invalid DOCTYPE"); angleBracketsCount++; exp = ""; } else if (xmlData[i6] === ">") { if (comment) { if (xmlData[i6 - 1] === "-" && xmlData[i6 - 2] === "-") { comment = false; angleBracketsCount--; } } else { angleBracketsCount--; } if (angleBracketsCount === 0) { break; } } else if (xmlData[i6] === "[") { hasBody = true; } else { exp += xmlData[i6]; } } if (angleBracketsCount !== 0) { throw new Error(`Unclosed DOCTYPE`); } } else { throw new Error(`Invalid Tag instead of DOCTYPE`); } return { entities, i: i6 }; } function readEntityExp(xmlData, i6) { let entityName2 = ""; for (; i6 < xmlData.length && (xmlData[i6] !== "'" && xmlData[i6] !== '"'); i6++) { entityName2 += xmlData[i6]; } entityName2 = entityName2.trim(); if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); const startChar = xmlData[i6++]; let val2 = ""; for (; i6 < xmlData.length && xmlData[i6] !== startChar; i6++) { val2 += xmlData[i6]; } return [entityName2, val2, i6]; } function isComment(xmlData, i6) { if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "-" && xmlData[i6 + 3] === "-") return true; return false; } function isEntity(xmlData, i6) { if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "N" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "I" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "Y") return true; return false; } function isElement(xmlData, i6) { if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "L" && xmlData[i6 + 4] === "E" && xmlData[i6 + 5] === "M" && xmlData[i6 + 6] === "E" && xmlData[i6 + 7] === "N" && xmlData[i6 + 8] === "T") return true; return false; } function isAttlist(xmlData, i6) { if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "A" && xmlData[i6 + 3] === "T" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "L" && xmlData[i6 + 6] === "I" && xmlData[i6 + 7] === "S" && xmlData[i6 + 8] === "T") return true; return false; } function isNotation(xmlData, i6) { if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "N" && xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "A" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "I" && xmlData[i6 + 8] === "O" && xmlData[i6 + 9] === "N") return true; return false; } function validateEntityName(name) { if (util2.isName(name)) return name; else throw new Error(`Invalid entity name ${name}`); } module2.exports = readDocType; } }); // ../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js var require_strnum = __commonJS({ "../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js"(exports2, module2) { "use strict"; var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; var consider = { hex: true, // oct: false, leadingZeros: true, decimalPoint: ".", eNotation: true //skipLike: /regex/ }; function toNumber(str, options = {}) { options = Object.assign({}, consider, options); if (!str || typeof str !== "string") return str; let trimmedStr = str.trim(); if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str; else if (str === "0") return 0; else if (options.hex && hexRegex.test(trimmedStr)) { return parse_int(trimmedStr, 16); } else if (trimmedStr.search(/[eE]/) !== -1) { const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); if (notation) { if (options.leadingZeros) { trimmedStr = (notation[1] || "") + notation[3]; } else { if (notation[2] === "0" && notation[3][0] === ".") { } else { return str; } } return options.eNotation ? Number(trimmedStr) : str; } else { return str; } } else { const match2 = numRegex.exec(trimmedStr); if (match2) { const sign = match2[1]; const leadingZeros = match2[2]; let numTrimmedByZeros = trimZeros(match2[3]); if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; else if (options.leadingZeros && leadingZeros === str) return 0; else { const num = Number(trimmedStr); const numStr = "" + num; if (numStr.search(/[eE]/) !== -1) { if (options.eNotation) return num; else return str; } else if (trimmedStr.indexOf(".") !== -1) { if (numStr === "0" && numTrimmedByZeros === "") return num; else if (numStr === numTrimmedByZeros) return num; else if (sign && numStr === "-" + numTrimmedByZeros) return num; else return str; } if (leadingZeros) { return numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str; } else { return trimmedStr === numStr || trimmedStr === sign + numStr ? num : str; } } } else { return str; } } } function trimZeros(numStr) { if (numStr && numStr.indexOf(".") !== -1) { numStr = numStr.replace(/0+$/, ""); if (numStr === ".") numStr = "0"; else if (numStr[0] === ".") numStr = "0" + numStr; else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); return numStr; } return numStr; } function parse_int(numStr, base) { if (parseInt) return parseInt(numStr, base); else if (Number.parseInt) return Number.parseInt(numStr, base); else if (window && window.parseInt) return window.parseInt(numStr, base); else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); } module2.exports = toNumber; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js var require_OrderedObjParser = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) { "use strict"; var util2 = require_util2(); var xmlNode = require_xmlNode(); var readDocType = require_DocTypeReader(); var toNumber = require_strnum(); var OrderedObjParser = class { constructor(options) { this.options = options; this.currentNode = null; this.tagsNodeStack = []; this.docTypeEntities = {}; this.lastEntities = { "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } }; this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; this.htmlEntities = { "space": { regex: /&(nbsp|#160);/g, val: " " }, // "lt" : { regex: /&(lt|#60);/g, val: "<" }, // "gt" : { regex: /&(gt|#62);/g, val: ">" }, // "amp" : { regex: /&(amp|#38);/g, val: "&" }, // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, // "apos" : { regex: /&(apos|#39);/g, val: "'" }, "cent": { regex: /&(cent|#162);/g, val: "\xA2" }, "pound": { regex: /&(pound|#163);/g, val: "\xA3" }, "yen": { regex: /&(yen|#165);/g, val: "\xA5" }, "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" }, "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 10)) }, "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 16)) } }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; this.parseTextData = parseTextData; this.resolveNameSpace = resolveNameSpace; this.buildAttributesMap = buildAttributesMap; this.isItStopNode = isItStopNode; this.replaceEntitiesValue = replaceEntitiesValue; this.readStopNodeData = readStopNodeData; this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; } }; function addExternalEntities(externalEntities) { const entKeys = Object.keys(externalEntities); for (let i6 = 0; i6 < entKeys.length; i6++) { const ent = entKeys[i6]; this.lastEntities[ent] = { regex: new RegExp("&" + ent + ";", "g"), val: externalEntities[ent] }; } } function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { if (val2 !== void 0) { if (this.options.trimValues && !dontTrim) { val2 = val2.trim(); } if (val2.length > 0) { if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); if (newval === null || newval === void 0) { return val2; } else if (typeof newval !== typeof val2 || newval !== val2) { return newval; } else if (this.options.trimValues) { return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); } else { const trimmedVal = val2.trim(); if (trimmedVal === val2) { return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); } else { return val2; } } } } } function resolveNameSpace(tagname) { if (this.options.removeNSPrefix) { const tags = tagname.split(":"); const prefix2 = tagname.charAt(0) === "/" ? "/" : ""; if (tags[0] === "xmlns") { return ""; } if (tags.length === 2) { tagname = prefix2 + tags[1]; } } return tagname; } var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); function buildAttributesMap(attrStr, jPath, tagName) { if (!this.options.ignoreAttributes && typeof attrStr === "string") { const matches = util2.getAllMatches(attrStr, attrsRegx); const len = matches.length; const attrs = {}; for (let i6 = 0; i6 < len; i6++) { const attrName = this.resolveNameSpace(matches[i6][1]); let oldVal = matches[i6][4]; let aName = this.options.attributeNamePrefix + attrName; if (attrName.length) { if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } if (aName === "__proto__") aName = "#__proto__"; if (oldVal !== void 0) { if (this.options.trimValues) { oldVal = oldVal.trim(); } oldVal = this.replaceEntitiesValue(oldVal); const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); if (newVal === null || newVal === void 0) { attrs[aName] = oldVal; } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { attrs[aName] = newVal; } else { attrs[aName] = parseValue( oldVal, this.options.parseAttributeValue, this.options.numberParseOptions ); } } else if (this.options.allowBooleanAttributes) { attrs[aName] = true; } } } if (!Object.keys(attrs).length) { return; } if (this.options.attributesGroupName) { const attrCollection = {}; attrCollection[this.options.attributesGroupName] = attrs; return attrCollection; } return attrs; } } var parseXml = function(xmlData) { xmlData = xmlData.replace(/\r\n?/g, "\n"); const xmlObj = new xmlNode("!xml"); let currentNode = xmlObj; let textData = ""; let jPath = ""; for (let i6 = 0; i6 < xmlData.length; i6++) { const ch = xmlData[i6]; if (ch === "<") { if (xmlData[i6 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i6, "Closing Tag is not closed."); let tagName = xmlData.substring(i6 + 2, closeIndex).trim(); if (this.options.removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); } } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode) { textData = this.saveTextToParentTag(textData, currentNode, jPath); } const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`); } let propIndex = 0; if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); this.tagsNodeStack.pop(); } else { propIndex = jPath.lastIndexOf("."); } jPath = jPath.substring(0, propIndex); currentNode = this.tagsNodeStack.pop(); textData = ""; i6 = closeIndex; } else if (xmlData[i6 + 1] === "?") { let tagData = readTagExp(xmlData, i6, false, "?>"); if (!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { } else { const childNode = new xmlNode(tagData.tagName); childNode.add(this.options.textNodeName, ""); if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); } this.addChild(currentNode, childNode, jPath); } i6 = tagData.closeIndex + 1; } else if (xmlData.substr(i6 + 1, 3) === "!--") { const endIndex = findClosingIndex(xmlData, "-->", i6 + 4, "Comment is not closed."); if (this.options.commentPropName) { const comment = xmlData.substring(i6 + 4, endIndex - 2); textData = this.saveTextToParentTag(textData, currentNode, jPath); currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); } i6 = endIndex; } else if (xmlData.substr(i6 + 1, 2) === "!D") { const result = readDocType(xmlData, i6); this.docTypeEntities = result.entities; i6 = result.i; } else if (xmlData.substr(i6 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i6, "CDATA is not closed.") - 2; const tagExp = xmlData.substring(i6 + 9, closeIndex); textData = this.saveTextToParentTag(textData, currentNode, jPath); let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); if (val2 == void 0) val2 = ""; if (this.options.cdataPropName) { currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); } else { currentNode.add(this.options.textNodeName, val2); } i6 = closeIndex + 2; } else { let result = readTagExp(xmlData, i6, this.options.removeNSPrefix); let tagName = result.tagName; const rawTagName = result.rawTagName; let tagExp = result.tagExp; let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode && textData) { if (currentNode.tagname !== "!xml") { textData = this.saveTextToParentTag(textData, currentNode, jPath, false); } } const lastTag = currentNode; if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { currentNode = this.tagsNodeStack.pop(); jPath = jPath.substring(0, jPath.lastIndexOf(".")); } if (tagName !== xmlObj.tagname) { jPath += jPath ? "." + tagName : tagName; } if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { let tagContent = ""; if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; } else { tagExp = tagExp.substr(0, tagExp.length - 1); } i6 = result.closeIndex; } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { i6 = result.closeIndex; } else { const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); i6 = result2.i; tagContent = result2.tagContent; } const childNode = new xmlNode(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } if (tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); } jPath = jPath.substr(0, jPath.lastIndexOf(".")); childNode.add(this.options.textNodeName, tagContent); this.addChild(currentNode, childNode, jPath); } else { if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; } else { tagExp = tagExp.substr(0, tagExp.length - 1); } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } const childNode = new xmlNode(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); jPath = jPath.substr(0, jPath.lastIndexOf(".")); } else { const childNode = new xmlNode(tagName); this.tagsNodeStack.push(currentNode); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); currentNode = childNode; } textData = ""; i6 = closeIndex; } } } else { textData += xmlData[i6]; } } return xmlObj.child; }; function addChild(currentNode, childNode, jPath) { const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); if (result === false) { } else if (typeof result === "string") { childNode.tagname = result; currentNode.addChild(childNode); } else { currentNode.addChild(childNode); } } var replaceEntitiesValue = function(val2) { if (this.options.processEntities) { for (let entityName2 in this.docTypeEntities) { const entity = this.docTypeEntities[entityName2]; val2 = val2.replace(entity.regx, entity.val); } for (let entityName2 in this.lastEntities) { const entity = this.lastEntities[entityName2]; val2 = val2.replace(entity.regex, entity.val); } if (this.options.htmlEntities) { for (let entityName2 in this.htmlEntities) { const entity = this.htmlEntities[entityName2]; val2 = val2.replace(entity.regex, entity.val); } } val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val); } return val2; }; function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; textData = this.parseTextData( textData, currentNode.tagname, jPath, false, currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, isLeafNode ); if (textData !== void 0 && textData !== "") currentNode.add(this.options.textNodeName, textData); textData = ""; } return textData; } function isItStopNode(stopNodes, jPath, currentTagName) { const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; } return false; } function tagExpWithClosingIndex(xmlData, i6, closingChar = ">") { let attrBoundary; let tagExp = ""; for (let index6 = i6; index6 < xmlData.length; index6++) { let ch = xmlData[index6]; if (attrBoundary) { if (ch === attrBoundary) attrBoundary = ""; } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { if (closingChar[1]) { if (xmlData[index6 + 1] === closingChar[1]) { return { data: tagExp, index: index6 }; } } else { return { data: tagExp, index: index6 }; } } else if (ch === " ") { ch = " "; } tagExp += ch; } } function findClosingIndex(xmlData, str, i6, errMsg) { const closingIndex = xmlData.indexOf(str, i6); if (closingIndex === -1) { throw new Error(errMsg); } else { return closingIndex + str.length - 1; } } function readTagExp(xmlData, i6, removeNSPrefix, closingChar = ">") { const result = tagExpWithClosingIndex(xmlData, i6 + 1, closingChar); if (!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); let tagName = tagExp; let attrExpPresent = true; if (separatorIndex !== -1) { tagName = tagExp.substring(0, separatorIndex); tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } const rawTagName = tagName; if (removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } } return { tagName, tagExp, closeIndex, attrExpPresent, rawTagName }; } function readStopNodeData(xmlData, tagName, i6) { const startIndex = i6; let openTagCount = 1; for (; i6 < xmlData.length; i6++) { if (xmlData[i6] === "<") { if (xmlData[i6 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i6, `${tagName} is not closed`); let closeTagName = xmlData.substring(i6 + 2, closeIndex).trim(); if (closeTagName === tagName) { openTagCount--; if (openTagCount === 0) { return { tagContent: xmlData.substring(startIndex, i6), i: closeIndex }; } } i6 = closeIndex; } else if (xmlData[i6 + 1] === "?") { const closeIndex = findClosingIndex(xmlData, "?>", i6 + 1, "StopNode is not closed."); i6 = closeIndex; } else if (xmlData.substr(i6 + 1, 3) === "!--") { const closeIndex = findClosingIndex(xmlData, "-->", i6 + 3, "StopNode is not closed."); i6 = closeIndex; } else if (xmlData.substr(i6 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i6, "StopNode is not closed.") - 2; i6 = closeIndex; } else { const tagData = readTagExp(xmlData, i6, ">"); if (tagData) { const openTagName = tagData && tagData.tagName; if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { openTagCount++; } i6 = tagData.closeIndex; } } } } } function parseValue(val2, shouldParse, options) { if (shouldParse && typeof val2 === "string") { const newval = val2.trim(); if (newval === "true") return true; else if (newval === "false") return false; else return toNumber(val2, options); } else { if (util2.isExist(val2)) { return val2; } else { return ""; } } } module2.exports = OrderedObjParser; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js var require_node2json = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) { "use strict"; function prettify(node, options) { return compress2(node, options); } function compress2(arr, options, jPath) { let text; const compressedObj = {}; for (let i6 = 0; i6 < arr.length; i6++) { const tagObj = arr[i6]; const property = propName(tagObj); let newJpath = ""; if (jPath === void 0) newJpath = property; else newJpath = jPath + "." + property; if (property === options.textNodeName) { if (text === void 0) text = tagObj[property]; else text += "" + tagObj[property]; } else if (property === void 0) { continue; } else if (tagObj[property]) { let val2 = compress2(tagObj[property], options, newJpath); const isLeaf = isLeafTag(val2, options); if (tagObj[":@"]) { assignAttributes(val2, tagObj[":@"], newJpath, options); } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { val2 = val2[options.textNodeName]; } else if (Object.keys(val2).length === 0) { if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; else val2 = ""; } if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { if (!Array.isArray(compressedObj[property])) { compressedObj[property] = [compressedObj[property]]; } compressedObj[property].push(val2); } else { if (options.isArray(property, newJpath, isLeaf)) { compressedObj[property] = [val2]; } else { compressedObj[property] = val2; } } } } if (typeof text === "string") { if (text.length > 0) compressedObj[options.textNodeName] = text; } else if (text !== void 0) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj) { const keys = Object.keys(obj); for (let i6 = 0; i6 < keys.length; i6++) { const key = keys[i6]; if (key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options) { if (attrMap) { const keys = Object.keys(attrMap); const len = keys.length; for (let i6 = 0; i6 < len; i6++) { const atrrName = keys[i6]; if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { obj[atrrName] = [attrMap[atrrName]]; } else { obj[atrrName] = attrMap[atrrName]; } } } } function isLeafTag(obj, options) { const { textNodeName } = options; const propCount = Object.keys(obj).length; if (propCount === 0) { return true; } if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { return true; } return false; } exports2.prettify = prettify; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js var require_XMLParser = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) { "use strict"; var { buildOptions } = require_OptionsBuilder(); var OrderedObjParser = require_OrderedObjParser(); var { prettify } = require_node2json(); var validator2 = require_validator(); var XMLParser2 = class { constructor(options) { this.externalEntities = {}; this.options = buildOptions(options); } /** * Parse XML dats to JS object * @param {string|Buffer} xmlData * @param {boolean|Object} validationOption */ parse(xmlData, validationOption) { if (typeof xmlData === "string") { } else if (xmlData.toString) { xmlData = xmlData.toString(); } else { throw new Error("XML data is accepted in String or Bytes[] form."); } if (validationOption) { if (validationOption === true) validationOption = {}; const result = validator2.validate(xmlData, validationOption); if (result !== true) { throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); } } const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; else return prettify(orderedResult, this.options); } /** * Add Entity which is not by default supported by this library * @param {string} key * @param {string} value */ addEntity(key, value) { if (value.indexOf("&") !== -1) { throw new Error("Entity value can't have '&'"); } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'"); } else if (value === "&") { throw new Error("An entity with value '&' is not permitted"); } else { this.externalEntities[key] = value; } } }; module2.exports = XMLParser2; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js var require_orderedJs2Xml = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) { "use strict"; var EOL = "\n"; function toXml(jArray, options) { let indentation = ""; if (options.format && options.indentBy.length > 0) { indentation = EOL; } return arrToStr(jArray, options, "", indentation); } function arrToStr(arr, options, jPath, indentation) { let xmlStr = ""; let isPreviousElementTag = false; for (let i6 = 0; i6 < arr.length; i6++) { const tagObj = arr[i6]; const tagName = propName(tagObj); if (tagName === void 0) continue; let newJPath = ""; if (jPath.length === 0) newJPath = tagName; else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { tagText = options.tagValueProcessor(tagName, tagText); tagText = replaceEntitiesValue(tagText, options); } if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += tagText; isPreviousElementTag = false; continue; } else if (tagName === options.cdataPropName) { if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`; isPreviousElementTag = false; continue; } else if (tagName === options.commentPropName) { xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`; isPreviousElementTag = true; continue; } else if (tagName[0] === "?") { const attStr2 = attr_to_str(tagObj[":@"], options); const tempInd = tagName === "?xml" ? "" : indentation; let piTextNodeName = tagObj[tagName][0][options.textNodeName]; piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; isPreviousElementTag = true; continue; } let newIdentation = indentation; if (newIdentation !== "") { newIdentation += options.indentBy; } const attStr = attr_to_str(tagObj[":@"], options); const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`; } else { xmlStr += tagStart + ">"; if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) { xmlStr += indentation + options.indentBy + tagValue + indentation; } else { xmlStr += tagValue; } xmlStr += `</${tagName}>`; } isPreviousElementTag = true; } return xmlStr; } function propName(obj) { const keys = Object.keys(obj); for (let i6 = 0; i6 < keys.length; i6++) { const key = keys[i6]; if (!obj.hasOwnProperty(key)) continue; if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { if (!attrMap.hasOwnProperty(attr)) continue; let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); attrVal = replaceEntitiesValue(attrVal, options); if (attrVal === true && options.suppressBooleanAttributes) { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; } else { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } } return attrStr; } function isStopNode(jPath, options) { jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index6 in options.stopNodes) { if (options.stopNodes[index6] === jPath || options.stopNodes[index6] === "*." + tagName) return true; } return false; } function replaceEntitiesValue(textValue, options) { if (textValue && textValue.length > 0 && options.processEntities) { for (let i6 = 0; i6 < options.entities.length; i6++) { const entity = options.entities[i6]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; } module2.exports = toXml; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js var require_json2xml = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) { "use strict"; var buildFromOrderedJs = require_orderedJs2Xml(); var defaultOptions = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(key, a5) { return a5; }, attributeValueProcessor: function(attrName, a5) { return a5; }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [ { regex: new RegExp("&", "g"), val: "&" }, //it must be on top { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ } ], processEntities: true, stopNodes: [], // transformTagName: false, // transformAttributeName: false, oneListGroup: false }; function Builder(options) { this.options = Object.assign({}, defaultOptions, options); if (this.options.ignoreAttributes || this.options.attributesGroupName) { this.isAttribute = function() { return false; }; } else { this.attrPrefixLen = this.options.attributeNamePrefix.length; this.isAttribute = isAttribute; } this.processTextOrObjNode = processTextOrObjNode; if (this.options.format) { this.indentate = indentate; this.tagEndChar = ">\n"; this.newLine = "\n"; } else { this.indentate = function() { return ""; }; this.tagEndChar = ">"; this.newLine = ""; } } Builder.prototype.build = function(jObj) { if (this.options.preserveOrder) { return buildFromOrderedJs(jObj, this.options); } else { if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { jObj = { [this.options.arrayNodeName]: jObj }; } return this.j2x(jObj, 0).val; } }; Builder.prototype.j2x = function(jObj, level) { let attrStr = ""; let val2 = ""; for (let key in jObj) { if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; if (typeof jObj[key] === "undefined") { if (this.isAttribute(key)) { val2 += ""; } } else if (jObj[key] === null) { if (this.isAttribute(key)) { val2 += ""; } else if (key[0] === "?") { val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; } else { val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } } else if (jObj[key] instanceof Date) { val2 += this.buildTextValNode(jObj[key], key, "", level); } else if (typeof jObj[key] !== "object") { const attr = this.isAttribute(key); if (attr) { attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); } else { if (key === this.options.textNodeName) { let newval = this.options.tagValueProcessor(key, "" + jObj[key]); val2 += this.replaceEntitiesValue(newval); } else { val2 += this.buildTextValNode(jObj[key], key, "", level); } } } else if (Array.isArray(jObj[key])) { const arrLen = jObj[key].length; let listTagVal = ""; let listTagAttr = ""; for (let j5 = 0; j5 < arrLen; j5++) { const item = jObj[key][j5]; if (typeof item === "undefined") { } else if (item === null) { if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } else if (typeof item === "object") { if (this.options.oneListGroup) { const result = this.j2x(item, level + 1); listTagVal += result.val; if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { listTagAttr += result.attrStr; } } else { listTagVal += this.processTextOrObjNode(item, key, level); } } else { if (this.options.oneListGroup) { let textValue = this.options.tagValueProcessor(key, item); textValue = this.replaceEntitiesValue(textValue); listTagVal += textValue; } else { listTagVal += this.buildTextValNode(item, key, "", level); } } } if (this.options.oneListGroup) { listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); } val2 += listTagVal; } else { if (this.options.attributesGroupName && key === this.options.attributesGroupName) { const Ks = Object.keys(jObj[key]); const L = Ks.length; for (let j5 = 0; j5 < L; j5++) { attrStr += this.buildAttrPairStr(Ks[j5], "" + jObj[key][Ks[j5]]); } } else { val2 += this.processTextOrObjNode(jObj[key], key, level); } } } return { attrStr, val: val2 }; }; Builder.prototype.buildAttrPairStr = function(attrName, val2) { val2 = this.options.attributeValueProcessor(attrName, "" + val2); val2 = this.replaceEntitiesValue(val2); if (this.options.suppressBooleanAttributes && val2 === "true") { return " " + attrName; } else return " " + attrName + '="' + val2 + '"'; }; function processTextOrObjNode(object, key, level) { const result = this.j2x(object, level + 1); if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); } else { return this.buildObjectNode(result.val, key, result.attrStr, level); } } Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { if (val2 === "") { if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; else { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } } else { let tagEndExp = "</" + key + this.tagEndChar; let piClosingChar = ""; if (key[0] === "?") { piClosingChar = "?"; tagEndExp = ""; } if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) { return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp; } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { return this.indentate(level) + `<!--${val2}-->` + this.newLine; } else { return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp; } } }; Builder.prototype.closeTag = function(key) { let closeTag = ""; if (this.options.unpairedTags.indexOf(key) !== -1) { if (!this.options.suppressUnpairedNode) closeTag = "/"; } else if (this.options.suppressEmptyNode) { closeTag = "/"; } else { closeTag = `></${key}`; } return closeTag; }; Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) { if (this.options.cdataPropName !== false && key === this.options.cdataPropName) { return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine; } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { return this.indentate(level) + `<!--${val2}-->` + this.newLine; } else if (key[0] === "?") { return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; } else { let textValue = this.options.tagValueProcessor(key, val2); textValue = this.replaceEntitiesValue(textValue); if (textValue === "") { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } else { return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar; } } }; Builder.prototype.replaceEntitiesValue = function(textValue) { if (textValue && textValue.length > 0 && this.options.processEntities) { for (let i6 = 0; i6 < this.options.entities.length; i6++) { const entity = this.options.entities[i6]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; }; function indentate(level) { return this.options.indentBy.repeat(level); } function isAttribute(name) { if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { return name.substr(this.attrPrefixLen); } else { return false; } } module2.exports = Builder; } }); // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js var require_fxp = __commonJS({ "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) { "use strict"; var validator2 = require_validator(); var XMLParser2 = require_XMLParser(); var XMLBuilder = require_json2xml(); module2.exports = { XMLParser: XMLParser2, XMLValidator: validator2, XMLBuilder }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js var import_fast_xml_parser, parseXmlBody, parseXmlErrorBody; var init_parseXmlBody = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() { "use strict"; init_dist_es24(); import_fast_xml_parser = __toESM(require_fxp()); init_common2(); parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { const parser = new import_fast_xml_parser.XMLParser({ attributeNamePrefix: "", htmlEntities: true, ignoreAttributes: false, ignoreDeclaration: true, parseTagValue: false, trimValues: false, tagValueProcessor: (_3, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0 }); parser.addEntity("#xD", "\r"); parser.addEntity("#10", "\n"); let parsedObj; try { parsedObj = parser.parse(encoded, true); } catch (e6) { if (e6 && typeof e6 === "object") { Object.defineProperty(e6, "$responseBodyText", { value: encoded }); } throw e6; } const textNodeName = "#text"; const key = Object.keys(parsedObj)[0]; const parsedObjToReturn = parsedObj[key]; if (parsedObjToReturn[textNodeName]) { parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; delete parsedObjToReturn[textNodeName]; } return getValueFromTextNode(parsedObjToReturn); } return {}; }); parseXmlErrorBody = async (errorBody, context) => { const value = await parseXmlBody(errorBody, context); if (value.Error) { value.Error.message = value.Error.message ?? value.Error.Message; } return value; }; } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js var init_protocols2 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() { "use strict"; init_coercing_serializers(); init_awsExpectUnion(); init_parseJsonBody(); init_parseXmlBody(); } }); // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js var init_dist_es25 = __esm({ "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js"() { "use strict"; init_client2(); init_httpAuthSchemes2(); init_protocols2(); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js async function checkFeatures(context, config, args) { const request2 = args.request; if (request2?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { setFeature2(context, "PROTOCOL_RPC_V2_CBOR", "M"); } if (typeof config.retryStrategy === "function") { const retryStrategy = await config.retryStrategy(); if (typeof retryStrategy.acquireInitialRetryToken === "function") { if (retryStrategy.constructor?.name?.includes("Adaptive")) { setFeature2(context, "RETRY_MODE_ADAPTIVE", "F"); } else { setFeature2(context, "RETRY_MODE_STANDARD", "E"); } } else { setFeature2(context, "RETRY_MODE_LEGACY", "D"); } } if (typeof config.accountIdEndpointMode === "function") { const endpointV2 = context.endpointV2; if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { setFeature2(context, "ACCOUNT_ID_ENDPOINT", "O"); } switch (await config.accountIdEndpointMode?.()) { case "disabled": setFeature2(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); break; case "preferred": setFeature2(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); break; case "required": setFeature2(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); break; } } const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; if (identity?.$source) { const credentials2 = identity; if (credentials2.accountId) { setFeature2(context, "RESOLVED_ACCOUNT_ID", "T"); } for (const [key, value] of Object.entries(credentials2.$source ?? {})) { setFeature2(context, key, value); } } } var ACCOUNT_ID_ENDPOINT_REGEX; var init_check_features = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js"() { "use strict"; init_dist_es25(); ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js var USER_AGENT, X_AMZ_USER_AGENT, SPACE2, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR; var init_constants5 = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() { "use strict"; USER_AGENT = "user-agent"; X_AMZ_USER_AGENT = "x-amz-user-agent"; SPACE2 = " "; UA_NAME_SEPARATOR = "/"; UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; UA_ESCAPE_CHAR = "-"; } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js function encodeFeatures(features) { let buffer = ""; for (const key in features) { const val2 = features[key]; if (buffer.length + val2.length + 1 <= BYTE_LIMIT) { if (buffer.length) { buffer += "," + val2; } else { buffer += val2; } continue; } break; } return buffer; } var BYTE_LIMIT; var init_encode_features = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js"() { "use strict"; BYTE_LIMIT = 1024; } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin; var init_user_agent_middleware = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() { "use strict"; init_dist_es20(); init_dist_es2(); init_check_features(); init_constants5(); init_encode_features(); userAgentMiddleware = (options) => (next, context) => async (args) => { const { request: request2 } = args; if (!HttpRequest.isInstance(request2)) { return next(args); } const { headers } = request2; const userAgent = context?.userAgent?.map(escapeUserAgent) || []; const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); await checkFeatures(context, options, args); const awsContext = context; defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; const appId = await options.userAgentAppId(); if (appId) { defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); } const prefix2 = getUserAgentPrefix(); const sdkUserAgentValue = (prefix2 ? [prefix2] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE2); const normalUAValue = [ ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), ...customUserAgent ].join(SPACE2); if (options.runtime !== "browser") { if (normalUAValue) { headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; } headers[USER_AGENT] = sdkUserAgentValue; } else { headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; } return next({ ...args, request: request2 }); }; escapeUserAgent = (userAgentPair) => { const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); const prefix2 = name.substring(0, prefixSeparatorIndex); let uaName = name.substring(prefixSeparatorIndex + 1); if (prefix2 === "api") { uaName = uaName.toLowerCase(); } return [prefix2, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index6) => { switch (index6) { case 0: return item; case 1: return `${acc}/${item}`; default: return `${acc}#${item}`; } }, ""); }; getUserAgentMiddlewareOptions = { name: "getUserAgentMiddleware", step: "build", priority: "low", tags: ["SET_USER_AGENT", "USER_AGENT"], override: true }; getUserAgentPlugin = (config) => ({ applyToStack: (clientStack) => { clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js var init_dist_es26 = __esm({ "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() { "use strict"; init_configurations(); init_user_agent_middleware(); } }); // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js var booleanSelector; var init_booleanSelector = __esm({ "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"() { "use strict"; booleanSelector = (obj, key, type) => { if (!(key in obj)) return void 0; if (obj[key] === "true") return true; if (obj[key] === "false") return false; throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); }; } }); // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js var init_numberSelector = __esm({ "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js var SelectorType; var init_types5 = __esm({ "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js"() { "use strict"; (function(SelectorType2) { SelectorType2["ENV"] = "env"; SelectorType2["CONFIG"] = "shared config entry"; })(SelectorType || (SelectorType = {})); } }); // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js var init_dist_es27 = __esm({ "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js"() { "use strict"; init_booleanSelector(); init_numberSelector(); init_types5(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js var ENV_USE_DUALSTACK_ENDPOINT, CONFIG_USE_DUALSTACK_ENDPOINT, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; var init_NodeUseDualstackEndpointConfigOptions = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() { "use strict"; init_dist_es27(); ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV), configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG), default: false }; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js var ENV_USE_FIPS_ENDPOINT, CONFIG_USE_FIPS_ENDPOINT, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; var init_NodeUseFipsEndpointConfigOptions = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() { "use strict"; init_dist_es27(); ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV), configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG), default: false }; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js var init_resolveCustomEndpointsConfig = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() { "use strict"; init_dist_es6(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js var init_getEndpointFromRegion = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js var init_resolveEndpointsConfig = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() { "use strict"; init_dist_es6(); init_getEndpointFromRegion(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js var init_endpointsConfig = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() { "use strict"; init_NodeUseDualstackEndpointConfigOptions(); init_NodeUseFipsEndpointConfigOptions(); init_resolveCustomEndpointsConfig(); init_resolveEndpointsConfig(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js var REGION_ENV_NAME, REGION_INI_NAME, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS; var init_config2 = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() { "use strict"; REGION_ENV_NAME = "AWS_REGION"; REGION_INI_NAME = "region"; NODE_REGION_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => env4[REGION_ENV_NAME], configFileSelector: (profile) => profile[REGION_INI_NAME], default: () => { throw new Error("Region is missing"); } }; NODE_REGION_CONFIG_FILE_OPTIONS = { preferredFile: "credentials" }; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js var isFipsRegion; var init_isFipsRegion = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() { "use strict"; isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js var getRealRegion; var init_getRealRegion = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() { "use strict"; init_isFipsRegion(); getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js var resolveRegionConfig; var init_resolveRegionConfig = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() { "use strict"; init_getRealRegion(); init_isFipsRegion(); resolveRegionConfig = (input) => { const { region, useFipsEndpoint } = input; if (!region) { throw new Error("Region is missing"); } return Object.assign(input, { region: async () => { if (typeof region === "string") { return getRealRegion(region); } const providedRegion = await region(); return getRealRegion(providedRegion); }, useFipsEndpoint: async () => { const providedRegion = typeof region === "string" ? region : await region(); if (isFipsRegion(providedRegion)) { return true; } return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); } }); }; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js var init_regionConfig = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() { "use strict"; init_config2(); init_resolveRegionConfig(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js var init_PartitionHash = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js var init_RegionHash = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js var init_getHostnameFromVariants = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js var init_getResolvedHostname = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js var init_getResolvedPartition = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js var init_getResolvedSigningRegion = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js var init_getRegionInfo = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() { "use strict"; init_getHostnameFromVariants(); init_getResolvedHostname(); init_getResolvedPartition(); init_getResolvedSigningRegion(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js var init_regionInfo = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() { "use strict"; init_PartitionHash(); init_RegionHash(); init_getRegionInfo(); } }); // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js var init_dist_es28 = __esm({ "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js"() { "use strict"; init_endpointsConfig(); init_regionConfig(); init_regionInfo(); } }); // ../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js function contentLengthMiddleware(bodyLengthChecker) { return (next) => async (args) => { const request2 = args.request; if (HttpRequest.isInstance(request2)) { const { body, headers } = request2; if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { try { const length = bodyLengthChecker(body); request2.headers = { ...request2.headers, [CONTENT_LENGTH_HEADER]: String(length) }; } catch (error2) { } } } return next({ ...args, request: request2 }); }; } var CONTENT_LENGTH_HEADER, contentLengthMiddlewareOptions, getContentLengthPlugin; var init_dist_es29 = __esm({ "../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js"() { "use strict"; init_dist_es2(); CONTENT_LENGTH_HEADER = "content-length"; contentLengthMiddlewareOptions = { step: "build", tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], name: "contentLengthMiddleware", override: true }; getContentLengthPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName; var init_s3 = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() { "use strict"; resolveParamsForS3 = async (endpointParams) => { const bucket = endpointParams?.Bucket || ""; if (typeof endpointParams.Bucket === "string") { endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); } if (isArnBucketName(bucket)) { if (endpointParams.ForcePathStyle === true) { throw new Error("Path-style addressing cannot be used with ARN buckets"); } } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { endpointParams.ForcePathStyle = true; } if (endpointParams.DisableMultiRegionAccessPoints) { endpointParams.disableMultiRegionAccessPoints = true; endpointParams.DisableMRAP = true; } return endpointParams; }; DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; DOTS_PATTERN = /\.\./; isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); isArnBucketName = (bucketName) => { const [arn, partition2, service, , , bucket] = bucketName.split(":"); const isArn = arn === "arn" && bucketName.split(":").length >= 6; const isValidArn = Boolean(isArn && partition2 && service && bucket); if (isArn && !isValidArn) { throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } return isValidArn; }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js var init_service_customizations = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() { "use strict"; init_s3(); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js var createConfigValueProvider; var init_createConfigValueProvider = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() { "use strict"; createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { const configProvider = async () => { const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; if (typeof configValue === "function") { return configValue(); } return configValue; }; if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { return async () => { const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials; const configValue = credentials2?.credentialScope ?? credentials2?.CredentialScope; return configValue; }; } if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { return async () => { const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials; const configValue = credentials2?.accountId ?? credentials2?.AccountId; return configValue; }; } if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { return async () => { const endpoint = await configProvider(); if (endpoint && typeof endpoint === "object") { if ("url" in endpoint) { return endpoint.url.href; } if ("hostname" in endpoint) { const { protocol, hostname, port, path: path3 } = endpoint; return `${protocol}//${hostname}${port ? ":" + port : ""}${path3}`; } } return endpoint; }; } return configProvider; }; } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js function getSelectorName(functionString) { try { const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); constants.delete("CONFIG"); constants.delete("CONFIG_PREFIX_SEPARATOR"); constants.delete("ENV"); return [...constants].join(", "); } catch (e6) { return functionString; } } var init_getSelectorName = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js var fromEnv; var init_fromEnv = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js"() { "use strict"; init_dist_es21(); init_getSelectorName(); fromEnv = (envVarSelector, options) => async () => { try { const config = envVarSelector(process.env, options); if (config === void 0) { throw new Error(); } return config; } catch (e6) { throw new CredentialsProviderError(e6.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); } }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js var import_os, import_path3, homeDirCache, getHomeDirCacheKey, getHomeDir; var init_getHomeDir = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js"() { "use strict"; import_os = require("os"); import_path3 = require("path"); homeDirCache = {}; getHomeDirCacheKey = () => { if (process && process.geteuid) { return `${process.geteuid()}`; } return "DEFAULT"; }; getHomeDir = () => { const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${import_path3.sep}` } = process.env; if (HOME) return HOME; if (USERPROFILE) return USERPROFILE; if (HOMEPATH) return `${HOMEDRIVE}${HOMEPATH}`; const homeDirCacheKey = getHomeDirCacheKey(); if (!homeDirCache[homeDirCacheKey]) homeDirCache[homeDirCacheKey] = (0, import_os.homedir)(); return homeDirCache[homeDirCacheKey]; }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js var ENV_PROFILE, DEFAULT_PROFILE, getProfileName; var init_getProfileName = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js"() { "use strict"; ENV_PROFILE = "AWS_PROFILE"; DEFAULT_PROFILE = "default"; getProfileName = (init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js var import_crypto3, import_path4, getSSOTokenFilepath; var init_getSSOTokenFilepath = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js"() { "use strict"; import_crypto3 = require("crypto"); import_path4 = require("path"); init_getHomeDir(); getSSOTokenFilepath = (id) => { const hasher = (0, import_crypto3.createHash)("sha1"); const cacheName = hasher.update(id).digest("hex"); return (0, import_path4.join)(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`); }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js var import_fs3, readFile2, getSSOTokenFromFile; var init_getSSOTokenFromFile = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js"() { "use strict"; import_fs3 = require("fs"); init_getSSOTokenFilepath(); ({ readFile: readFile2 } = import_fs3.promises); getSSOTokenFromFile = async (id) => { const ssoTokenFilepath = getSSOTokenFilepath(id); const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8"); return JSON.parse(ssoTokenText); }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js var getConfigData; var init_getConfigData = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js"() { "use strict"; init_dist_es(); init_loadSharedConfigFiles(); getConfigData = (data) => Object.entries(data).filter(([key]) => { const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); if (indexOfSeparator === -1) { return false; } return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator)); }).reduce((acc, [key, value]) => { const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; acc[updatedKey] = value; return acc; }, { ...data.default && { default: data.default } }); } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js var import_path5, ENV_CONFIG_PATH, getConfigFilepath; var init_getConfigFilepath = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js"() { "use strict"; import_path5 = require("path"); init_getHomeDir(); ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || (0, import_path5.join)(getHomeDir(), ".aws", "config"); } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js var import_path6, ENV_CREDENTIALS_PATH, getCredentialsFilepath; var init_getCredentialsFilepath = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js"() { "use strict"; import_path6 = require("path"); init_getHomeDir(); ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || (0, import_path6.join)(getHomeDir(), ".aws", "credentials"); } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js var prefixKeyRegex, profileNameBlockList, parseIni; var init_parseIni = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js"() { "use strict"; init_dist_es(); init_loadSharedConfigFiles(); prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; profileNameBlockList = ["__proto__", "profile __proto__"]; parseIni = (iniData) => { const map2 = {}; let currentSection; let currentSubSection; for (const iniLine of iniData.split(/\r?\n/)) { const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; if (isSection) { currentSection = void 0; currentSubSection = void 0; const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); const matches = prefixKeyRegex.exec(sectionName); if (matches) { const [, prefix2, , name] = matches; if (Object.values(IniSectionType).includes(prefix2)) { currentSection = [prefix2, name].join(CONFIG_PREFIX_SEPARATOR); } } else { currentSection = sectionName; } if (profileNameBlockList.includes(sectionName)) { throw new Error(`Found invalid profile name "${sectionName}"`); } } else if (currentSection) { const indexOfEqualsSign = trimmedLine.indexOf("="); if (![0, -1].includes(indexOfEqualsSign)) { const [name, value] = [ trimmedLine.substring(0, indexOfEqualsSign).trim(), trimmedLine.substring(indexOfEqualsSign + 1).trim() ]; if (value === "") { currentSubSection = name; } else { if (currentSubSection && iniLine.trimStart() === iniLine) { currentSubSection = void 0; } map2[currentSection] = map2[currentSection] || {}; const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; map2[currentSection][key] = value; } } } } return map2; }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js var import_fs4, readFile3, filePromisesHash, slurpFile; var init_slurpFile = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js"() { "use strict"; import_fs4 = require("fs"); ({ readFile: readFile3 } = import_fs4.promises); filePromisesHash = {}; slurpFile = (path3, options) => { if (!filePromisesHash[path3] || options?.ignoreCache) { filePromisesHash[path3] = readFile3(path3, "utf8"); } return filePromisesHash[path3]; }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js var import_path7, swallowError, CONFIG_PREFIX_SEPARATOR, loadSharedConfigFiles; var init_loadSharedConfigFiles = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js"() { "use strict"; import_path7 = require("path"); init_getConfigData(); init_getConfigFilepath(); init_getCredentialsFilepath(); init_getHomeDir(); init_parseIni(); init_slurpFile(); swallowError = () => ({}); CONFIG_PREFIX_SEPARATOR = "."; loadSharedConfigFiles = async (init2 = {}) => { const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2; const homeDir = getHomeDir(); const relativeHomeDirPrefix = "~/"; let resolvedFilepath = filepath; if (filepath.startsWith(relativeHomeDirPrefix)) { resolvedFilepath = (0, import_path7.join)(homeDir, filepath.slice(2)); } let resolvedConfigFilepath = configFilepath; if (configFilepath.startsWith(relativeHomeDirPrefix)) { resolvedConfigFilepath = (0, import_path7.join)(homeDir, configFilepath.slice(2)); } const parsedFiles = await Promise.all([ slurpFile(resolvedConfigFilepath, { ignoreCache: init2.ignoreCache }).then(parseIni).then(getConfigData).catch(swallowError), slurpFile(resolvedFilepath, { ignoreCache: init2.ignoreCache }).then(parseIni).catch(swallowError) ]); return { configFile: parsedFiles[0], credentialsFile: parsedFiles[1] }; }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js var getSsoSessionData; var init_getSsoSessionData = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js"() { "use strict"; init_dist_es(); init_loadSharedConfigFiles(); getSsoSessionData = (data) => Object.entries(data).filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js var swallowError2, loadSsoSessionData; var init_loadSsoSessionData = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js"() { "use strict"; init_getConfigFilepath(); init_getSsoSessionData(); init_parseIni(); init_slurpFile(); swallowError2 = () => ({}); loadSsoSessionData = async (init2 = {}) => slurpFile(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2); } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js var mergeConfigFiles; var init_mergeConfigFiles = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js"() { "use strict"; mergeConfigFiles = (...files) => { const merged = {}; for (const file of files) { for (const [key, values] of Object.entries(file)) { if (merged[key] !== void 0) { Object.assign(merged[key], values); } else { merged[key] = values; } } } return merged; }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js var parseKnownFiles; var init_parseKnownFiles = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js"() { "use strict"; init_loadSharedConfigFiles(); init_mergeConfigFiles(); parseKnownFiles = async (init2) => { const parsedFiles = await loadSharedConfigFiles(init2); return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); }; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js var init_types6 = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js var init_dist_es30 = __esm({ "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js"() { "use strict"; init_getHomeDir(); init_getProfileName(); init_getSSOTokenFilepath(); init_getSSOTokenFromFile(); init_loadSharedConfigFiles(); init_loadSsoSessionData(); init_parseKnownFiles(); init_types6(); } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js var fromSharedConfigFiles; var init_fromSharedConfigFiles = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js"() { "use strict"; init_dist_es21(); init_dist_es30(); init_getSelectorName(); fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init2 } = {}) => async () => { const profile = getProfileName(init2); const { configFile, credentialsFile } = await loadSharedConfigFiles(init2); const profileFromCredentials = credentialsFile[profile] || {}; const profileFromConfig = configFile[profile] || {}; const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; try { const cfgFile = preferredFile === "config" ? configFile : credentialsFile; const configValue = configSelector(mergedProfile, cfgFile); if (configValue === void 0) { throw new Error(); } return configValue; } catch (e6) { throw new CredentialsProviderError(e6.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init2.logger }); } }; } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js var isFunction, fromStatic2; var init_fromStatic2 = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js"() { "use strict"; init_dist_es21(); isFunction = (func) => typeof func === "function"; fromStatic2 = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : fromStatic(defaultValue); } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js var loadConfig; var init_configLoader = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js"() { "use strict"; init_dist_es21(); init_fromEnv(); init_fromSharedConfigFiles(); init_fromStatic2(); loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { const { signingName, logger: logger2 } = configuration; const envOptions = { signingName, logger: logger2 }; return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic2(defaultValue))); }; } }); // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js var init_dist_es31 = __esm({ "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js"() { "use strict"; init_configLoader(); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js var ENV_ENDPOINT_URL, CONFIG_ENDPOINT_URL, getEndpointUrlConfig; var init_getEndpointUrlConfig = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js"() { "use strict"; init_dist_es30(); ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; CONFIG_ENDPOINT_URL = "endpoint_url"; getEndpointUrlConfig = (serviceId) => ({ environmentVariableSelector: (env4) => { const serviceSuffixParts = serviceId.split(" ").map((w4) => w4.toUpperCase()); const serviceEndpointUrl = env4[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; if (serviceEndpointUrl) return serviceEndpointUrl; const endpointUrl = env4[ENV_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return void 0; }, configFileSelector: (profile, config) => { if (config && profile.services) { const servicesSection = config[["services", profile.services].join(CONFIG_PREFIX_SEPARATOR)]; if (servicesSection) { const servicePrefixParts = serviceId.split(" ").map((w4) => w4.toLowerCase()); const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)]; if (endpointUrl2) return endpointUrl2; } } const endpointUrl = profile[CONFIG_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return void 0; }, default: void 0 }); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js var getEndpointFromConfig; var init_getEndpointFromConfig = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js"() { "use strict"; init_dist_es31(); init_getEndpointUrlConfig(); getEndpointFromConfig = async (serviceId) => loadConfig(getEndpointUrlConfig(serviceId ?? ""))(); } }); // ../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js function parseQueryString(querystring) { const query = {}; querystring = querystring.replace(/^\?/, ""); if (querystring) { for (const pair of querystring.split("&")) { let [key, value = null] = pair.split("="); key = decodeURIComponent(key); if (value) { value = decodeURIComponent(value); } if (!(key in query)) { query[key] = value; } else if (Array.isArray(query[key])) { query[key].push(value); } else { query[key] = [query[key], value]; } } } return query; } var init_dist_es32 = __esm({ "../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js var parseUrl; var init_dist_es33 = __esm({ "../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js"() { "use strict"; init_dist_es32(); parseUrl = (url) => { if (typeof url === "string") { return parseUrl(new URL(url)); } const { hostname, pathname, port, protocol, search } = url; let query; if (search) { query = parseQueryString(search); } return { hostname, port: port ? parseInt(port) : void 0, protocol, path: pathname, query }; }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js var toEndpointV1; var init_toEndpointV1 = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() { "use strict"; init_dist_es33(); toEndpointV1 = (endpoint) => { if (typeof endpoint === "object") { if ("url" in endpoint) { return parseUrl(endpoint.url); } return endpoint; } return parseUrl(endpoint); }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js var getEndpointFromInstructions, resolveParams; var init_getEndpointFromInstructions = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() { "use strict"; init_service_customizations(); init_createConfigValueProvider(); init_getEndpointFromConfig(); init_toEndpointV1(); getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { if (!clientConfig.endpoint) { let endpointFromConfig; if (clientConfig.serviceConfiguredEndpoint) { endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); } else { endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId); } if (endpointFromConfig) { clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); } } const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); if (typeof clientConfig.endpointProvider !== "function") { throw new Error("config.endpointProvider is not set."); } const endpoint = clientConfig.endpointProvider(endpointParams, context); return endpoint; }; resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { const endpointParams = {}; const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; for (const [name, instruction] of Object.entries(instructions)) { switch (instruction.type) { case "staticContextParams": endpointParams[name] = instruction.value; break; case "contextParams": endpointParams[name] = commandInput[instruction.name]; break; case "clientContextParams": case "builtInParams": endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); break; case "operationContextParams": endpointParams[name] = instruction.get(commandInput); break; default: throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } } if (Object.keys(instructions).length === 0) { Object.assign(endpointParams, clientConfig); } if (String(clientConfig.serviceId).toLowerCase() === "s3") { await resolveParamsForS3(endpointParams); } return endpointParams; }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js var init_adaptors = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() { "use strict"; init_getEndpointFromInstructions(); init_toEndpointV1(); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js var endpointMiddleware; var init_endpointMiddleware = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() { "use strict"; init_dist_es18(); init_dist_es6(); init_getEndpointFromInstructions(); endpointMiddleware = ({ config, instructions }) => { return (next, context) => async (args) => { if (config.endpoint) { setFeature(context, "ENDPOINT_OVERRIDE", "N"); } const endpoint = await getEndpointFromInstructions(args.input, { getEndpointParameterInstructions() { return instructions; } }, { ...config }, context); context.endpointV2 = endpoint; context.authSchemes = endpoint.properties?.authSchemes; const authScheme = context.authSchemes?.[0]; if (authScheme) { context["signing_region"] = authScheme.signingRegion; context["signing_service"] = authScheme.signingName; const smithyContext = getSmithyContext(context); const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; if (httpAuthOption) { httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { signing_region: authScheme.signingRegion, signingRegion: authScheme.signingRegion, signing_service: authScheme.signingName, signingName: authScheme.signingName, signingRegionSet: authScheme.signingRegionSet }, authScheme.properties); } } return next({ ...args }); }; }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js var endpointMiddlewareOptions, getEndpointPlugin; var init_getEndpointPlugin = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() { "use strict"; init_dist_es7(); init_endpointMiddleware(); endpointMiddlewareOptions = { step: "serialize", tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], name: "endpointV2Middleware", override: true, relation: "before", toMiddleware: serializerMiddlewareOption.name }; getEndpointPlugin = (config, instructions) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(endpointMiddleware({ config, instructions }), endpointMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js var resolveEndpointConfig; var init_resolveEndpointConfig = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() { "use strict"; init_dist_es6(); init_getEndpointFromConfig(); init_toEndpointV1(); resolveEndpointConfig = (input) => { const tls = input.tls ?? true; const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0; const isCustomEndpoint = !!endpoint; const resolvedConfig = Object.assign(input, { endpoint: customEndpointProvider, tls, isCustomEndpoint, useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false) }); let configuredEndpointPromise = void 0; resolvedConfig.serviceConfiguredEndpoint = async () => { if (input.serviceId && !configuredEndpointPromise) { configuredEndpointPromise = getEndpointFromConfig(input.serviceId); } return configuredEndpointPromise; }; return resolvedConfig; }; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js var init_types7 = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js var init_dist_es34 = __esm({ "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js"() { "use strict"; init_adaptors(); init_endpointMiddleware(); init_getEndpointPlugin(); init_resolveEndpointConfig(); init_types7(); } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE; var init_config3 = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js"() { "use strict"; (function(RETRY_MODES2) { RETRY_MODES2["STANDARD"] = "standard"; RETRY_MODES2["ADAPTIVE"] = "adaptive"; })(RETRY_MODES || (RETRY_MODES = {})); DEFAULT_MAX_ATTEMPTS = 3; DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD; } }); // ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES2; var init_constants6 = __esm({ "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js"() { "use strict"; THROTTLING_ERROR_CODES = [ "BandwidthLimitExceeded", "EC2ThrottledException", "LimitExceededException", "PriorRequestNotComplete", "ProvisionedThroughputExceededException", "RequestLimitExceeded", "RequestThrottled", "RequestThrottledException", "SlowDown", "ThrottledException", "Throttling", "ThrottlingException", "TooManyRequestsException", "TransactionInProgressException" ]; TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; NODEJS_TIMEOUT_ERROR_CODES2 = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; } }); // ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js var isClockSkewCorrectedError, isBrowserNetworkError, isThrottlingError, isTransientError, isServerError; var init_dist_es35 = __esm({ "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js"() { "use strict"; init_constants6(); isClockSkewCorrectedError = (error2) => error2.$metadata?.clockSkewCorrected; isBrowserNetworkError = (error2) => { const errorMessages = /* @__PURE__ */ new Set([ "Failed to fetch", "NetworkError when attempting to fetch resource", "The Internet connection appears to be offline", "Load failed", "Network request failed" ]); const isValid2 = error2 && error2 instanceof TypeError; if (!isValid2) { return false; } return errorMessages.has(error2.message); }; isThrottlingError = (error2) => error2.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || error2.$retryable?.throttling == true; isTransientError = (error2, depth = 0) => isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES2.includes(error2?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error2.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error2) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1); isServerError = (error2) => { if (error2.$metadata?.httpStatusCode !== void 0) { const statusCode = error2.$metadata.httpStatusCode; if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) { return true; } return false; } return false; }; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js var DefaultRateLimiter; var init_DefaultRateLimiter = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() { "use strict"; init_dist_es35(); DefaultRateLimiter = class _DefaultRateLimiter { constructor(options) { this.currentCapacity = 0; this.enabled = false; this.lastMaxRate = 0; this.measuredTxRate = 0; this.requestCount = 0; this.lastTimestamp = 0; this.timeWindow = 0; this.beta = options?.beta ?? 0.7; this.minCapacity = options?.minCapacity ?? 1; this.minFillRate = options?.minFillRate ?? 0.5; this.scaleConstant = options?.scaleConstant ?? 0.4; this.smooth = options?.smooth ?? 0.8; const currentTimeInSeconds = this.getCurrentTimeInSeconds(); this.lastThrottleTime = currentTimeInSeconds; this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); this.fillRate = this.minFillRate; this.maxCapacity = this.minCapacity; } getCurrentTimeInSeconds() { return Date.now() / 1e3; } async getSendToken() { return this.acquireTokenBucket(1); } async acquireTokenBucket(amount) { if (!this.enabled) { return; } this.refillTokenBucket(); if (amount > this.currentCapacity) { const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); } this.currentCapacity = this.currentCapacity - amount; } refillTokenBucket() { const timestamp = this.getCurrentTimeInSeconds(); if (!this.lastTimestamp) { this.lastTimestamp = timestamp; return; } const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); this.lastTimestamp = timestamp; } updateClientSendingRate(response) { let calculatedRate; this.updateMeasuredRate(); if (isThrottlingError(response)) { const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); this.lastMaxRate = rateToUse; this.calculateTimeWindow(); this.lastThrottleTime = this.getCurrentTimeInSeconds(); calculatedRate = this.cubicThrottle(rateToUse); this.enableTokenBucket(); } else { this.calculateTimeWindow(); calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); } const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); this.updateTokenBucketRate(newRate); } calculateTimeWindow() { this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); } cubicThrottle(rateToUse) { return this.getPrecise(rateToUse * this.beta); } cubicSuccess(timestamp) { return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); } enableTokenBucket() { this.enabled = true; } updateTokenBucketRate(newRate) { this.refillTokenBucket(); this.fillRate = Math.max(newRate, this.minFillRate); this.maxCapacity = Math.max(newRate, this.minCapacity); this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); } updateMeasuredRate() { const t6 = this.getCurrentTimeInSeconds(); const timeBucket = Math.floor(t6 * 2) / 2; this.requestCount++; if (timeBucket > this.lastTxRateBucket) { const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); this.requestCount = 0; this.lastTxRateBucket = timeBucket; } } getPrecise(num) { return parseFloat(num.toFixed(8)); } }; DefaultRateLimiter.setTimeoutFn = setTimeout; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER; var init_constants7 = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js"() { "use strict"; DEFAULT_RETRY_DELAY_BASE = 100; MAXIMUM_RETRY_DELAY = 20 * 1e3; THROTTLING_RETRY_DELAY_BASE = 500; INITIAL_RETRY_TOKENS = 500; RETRY_COST = 5; TIMEOUT_RETRY_COST = 10; NO_RETRY_INCREMENT = 1; INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; REQUEST_HEADER = "amz-sdk-request"; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js var getDefaultRetryBackoffStrategy; var init_defaultRetryBackoffStrategy = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() { "use strict"; init_constants7(); getDefaultRetryBackoffStrategy = () => { let delayBase = DEFAULT_RETRY_DELAY_BASE; const computeNextBackoffDelay = (attempts) => { return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); }; const setDelayBase = (delay) => { delayBase = delay; }; return { computeNextBackoffDelay, setDelayBase }; }; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js var createDefaultRetryToken; var init_defaultRetryToken = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() { "use strict"; init_constants7(); createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => { const getRetryCount = () => retryCount; const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay); const getRetryCost = () => retryCost; return { getRetryCount, getRetryDelay, getRetryCost }; }; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js var StandardRetryStrategy; var init_StandardRetryStrategy = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() { "use strict"; init_config3(); init_constants7(); init_defaultRetryBackoffStrategy(); init_defaultRetryToken(); StandardRetryStrategy = class { constructor(maxAttempts) { this.maxAttempts = maxAttempts; this.mode = RETRY_MODES.STANDARD; this.capacity = INITIAL_RETRY_TOKENS; this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; } async acquireInitialRetryToken(retryTokenScope) { return createDefaultRetryToken({ retryDelay: DEFAULT_RETRY_DELAY_BASE, retryCount: 0 }); } async refreshRetryTokenForRetry(token, errorInfo) { const maxAttempts = await this.getMaxAttempts(); if (this.shouldRetry(token, errorInfo, maxAttempts)) { const errorType = errorInfo.errorType; this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE); const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; const capacityCost = this.getCapacityCost(errorType); this.capacity -= capacityCost; return createDefaultRetryToken({ retryDelay, retryCount: token.getRetryCount() + 1, retryCost: capacityCost }); } throw new Error("No retry token available"); } recordSuccess(token) { this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); } getCapacity() { return this.capacity; } async getMaxAttempts() { try { return await this.maxAttemptsProvider(); } catch (error2) { console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); return DEFAULT_MAX_ATTEMPTS; } } shouldRetry(tokenToRenew, errorInfo, maxAttempts) { const attempts = tokenToRenew.getRetryCount() + 1; return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); } getCapacityCost(errorType) { return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; } isRetryableError(errorType) { return errorType === "THROTTLING" || errorType === "TRANSIENT"; } }; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js var AdaptiveRetryStrategy; var init_AdaptiveRetryStrategy = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() { "use strict"; init_config3(); init_DefaultRateLimiter(); init_StandardRetryStrategy(); AdaptiveRetryStrategy = class { constructor(maxAttemptsProvider, options) { this.maxAttemptsProvider = maxAttemptsProvider; this.mode = RETRY_MODES.ADAPTIVE; const { rateLimiter } = options ?? {}; this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); } async acquireInitialRetryToken(retryTokenScope) { await this.rateLimiter.getSendToken(); return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); } async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { this.rateLimiter.updateClientSendingRate(errorInfo); return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); } recordSuccess(token) { this.rateLimiter.updateClientSendingRate({}); this.standardRetryStrategy.recordSuccess(token); } }; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js var init_ConfiguredRetryStrategy = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() { "use strict"; init_constants7(); init_StandardRetryStrategy(); } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js var init_types8 = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js"() { "use strict"; } }); // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js var init_dist_es36 = __esm({ "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js"() { "use strict"; init_AdaptiveRetryStrategy(); init_ConfiguredRetryStrategy(); init_DefaultRateLimiter(); init_StandardRetryStrategy(); init_config3(); init_constants7(); init_types8(); } }); // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js function rng() { if (poolPtr > rnds8Pool.length - 16) { import_crypto4.default.randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } var import_crypto4, rnds8Pool, poolPtr; var init_rng = __esm({ "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() { "use strict"; import_crypto4 = __toESM(require("crypto")); rnds8Pool = new Uint8Array(256); poolPtr = rnds8Pool.length; } }); // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js function unsafeStringify(arr, offset = 0) { return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; } var byteToHex; var init_stringify = __esm({ "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() { "use strict"; byteToHex = []; for (let i6 = 0; i6 < 256; ++i6) { byteToHex.push((i6 + 256).toString(16).slice(1)); } } }); // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js var import_crypto5, native_default; var init_native = __esm({ "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() { "use strict"; import_crypto5 = __toESM(require("crypto")); native_default = { randomUUID: import_crypto5.default.randomUUID }; } }); // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js function v4(options, buf, offset) { if (native_default.randomUUID && !buf && !options) { return native_default.randomUUID(); } options = options || {}; const rnds = options.random || (options.rng || rng)(); rnds[6] = rnds[6] & 15 | 64; rnds[8] = rnds[8] & 63 | 128; if (buf) { offset = offset || 0; for (let i6 = 0; i6 < 16; ++i6) { buf[offset + i6] = rnds[i6]; } return buf; } return unsafeStringify(rnds); } var v4_default; var init_v4 = __esm({ "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js"() { "use strict"; init_native(); init_rng(); init_stringify(); v4_default = v4; } }); // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js var init_esm_node = __esm({ "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() { "use strict"; init_v4(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js var init_defaultRetryQuota = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js"() { "use strict"; init_dist_es36(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js var init_delayDecider = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() { "use strict"; init_dist_es36(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js var init_retryDecider = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() { "use strict"; init_dist_es35(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js var asSdkError; var init_util3 = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js"() { "use strict"; asSdkError = (error2) => { if (error2 instanceof Error) return error2; if (error2 instanceof Object) return Object.assign(new Error(), error2); if (typeof error2 === "string") return new Error(error2); return new Error(`AWS SDK error wrapper for ${error2}`); }; } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js var init_StandardRetryStrategy2 = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() { "use strict"; init_dist_es2(); init_dist_es35(); init_dist_es36(); init_defaultRetryQuota(); init_delayDecider(); init_retryDecider(); init_util3(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js var init_AdaptiveRetryStrategy2 = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() { "use strict"; init_dist_es36(); init_StandardRetryStrategy2(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js var ENV_MAX_ATTEMPTS, CONFIG_MAX_ATTEMPTS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, ENV_RETRY_MODE, CONFIG_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS; var init_configurations2 = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js"() { "use strict"; init_dist_es6(); init_dist_es36(); ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; CONFIG_MAX_ATTEMPTS = "max_attempts"; NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => { const value = env4[ENV_MAX_ATTEMPTS]; if (!value) return void 0; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, configFileSelector: (profile) => { const value = profile[CONFIG_MAX_ATTEMPTS]; if (!value) return void 0; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, default: DEFAULT_MAX_ATTEMPTS }; resolveRetryConfig = (input) => { const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS); return Object.assign(input, { maxAttempts, retryStrategy: async () => { if (retryStrategy) { return retryStrategy; } const retryMode = await normalizeProvider(_retryMode)(); if (retryMode === RETRY_MODES.ADAPTIVE) { return new AdaptiveRetryStrategy(maxAttempts); } return new StandardRetryStrategy(maxAttempts); } }); }; ENV_RETRY_MODE = "AWS_RETRY_MODE"; CONFIG_RETRY_MODE = "retry_mode"; NODE_RETRY_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => env4[ENV_RETRY_MODE], configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], default: DEFAULT_RETRY_MODE }; } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js var init_omitRetryHeadersMiddleware = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() { "use strict"; init_dist_es2(); init_dist_es36(); } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js var import_stream6, isStreamingPayload; var init_isStreamingPayload = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js"() { "use strict"; import_stream6 = require("stream"); isStreamingPayload = (request2) => request2?.body instanceof import_stream6.Readable || typeof ReadableStream !== "undefined" && request2?.body instanceof ReadableStream; } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint; var init_retryMiddleware = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() { "use strict"; init_dist_es2(); init_dist_es35(); init_dist_es24(); init_dist_es36(); init_esm_node(); init_isStreamingPayload(); init_util3(); retryMiddleware = (options) => (next, context) => async (args) => { let retryStrategy = await options.retryStrategy(); const maxAttempts = await options.maxAttempts(); if (isRetryStrategyV2(retryStrategy)) { retryStrategy = retryStrategy; let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); let lastError = new Error(); let attempts = 0; let totalRetryDelay = 0; const { request: request2 } = args; const isRequest2 = HttpRequest.isInstance(request2); if (isRequest2) { request2.headers[INVOCATION_ID_HEADER] = v4_default(); } while (true) { try { if (isRequest2) { request2.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } const { response, output } = await next(args); retryStrategy.recordSuccess(retryToken); output.$metadata.attempts = attempts + 1; output.$metadata.totalRetryDelay = totalRetryDelay; return { response, output }; } catch (e6) { const retryErrorInfo = getRetryErrorInfo(e6); lastError = asSdkError(e6); if (isRequest2 && isStreamingPayload(request2)) { (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); throw lastError; } try { retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); } catch (refreshError) { if (!lastError.$metadata) { lastError.$metadata = {}; } lastError.$metadata.attempts = attempts + 1; lastError.$metadata.totalRetryDelay = totalRetryDelay; throw lastError; } attempts = retryToken.getRetryCount(); const delay = retryToken.getRetryDelay(); totalRetryDelay += delay; await new Promise((resolve) => setTimeout(resolve, delay)); } } } else { retryStrategy = retryStrategy; if (retryStrategy?.mode) context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; return retryStrategy.retry(next, args); } }; isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined"; getRetryErrorInfo = (error2) => { const errorInfo = { error: error2, errorType: getRetryErrorType(error2) }; const retryAfterHint = getRetryAfterHint(error2.$response); if (retryAfterHint) { errorInfo.retryAfterHint = retryAfterHint; } return errorInfo; }; getRetryErrorType = (error2) => { if (isThrottlingError(error2)) return "THROTTLING"; if (isTransientError(error2)) return "TRANSIENT"; if (isServerError(error2)) return "SERVER_ERROR"; return "CLIENT_ERROR"; }; retryMiddlewareOptions = { name: "retryMiddleware", tags: ["RETRY"], step: "finalizeRequest", priority: "high", override: true }; getRetryPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(retryMiddleware(options), retryMiddlewareOptions); } }); getRetryAfterHint = (response) => { if (!HttpResponse.isInstance(response)) return; const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); if (!retryAfterHeaderName) return; const retryAfter = response.headers[retryAfterHeaderName]; const retryAfterSeconds = Number(retryAfter); if (!Number.isNaN(retryAfterSeconds)) return new Date(retryAfterSeconds * 1e3); const retryAfterDate = new Date(retryAfter); return retryAfterDate; }; } }); // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js var init_dist_es37 = __esm({ "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js"() { "use strict"; init_AdaptiveRetryStrategy2(); init_StandardRetryStrategy2(); init_configurations2(); init_delayDecider(); init_omitRetryHeadersMiddleware(); init_retryDecider(); init_retryMiddleware(); } }); // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js function createAwsAuthSigv4HttpAuthOption(authParameters) { return { schemeId: "aws.auth#sigv4", signingProperties: { name: "rds-data", region: authParameters.region }, propertiesExtractor: (config, context) => ({ signingProperties: { config, context } }) }; } var defaultRDSDataHttpAuthSchemeParametersProvider, defaultRDSDataHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig; var init_httpAuthSchemeProvider = __esm({ "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js"() { "use strict"; init_dist_es25(); init_dist_es6(); defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => { return { operation: getSmithyContext(context).operation, region: await normalizeProvider(config.region)() || (() => { throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); })() }; }; defaultRDSDataHttpAuthSchemeProvider = (authParameters) => { const options = []; switch (authParameters.operation) { default: { options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); } } return options; }; resolveHttpAuthSchemeConfig = (config) => { const config_0 = resolveAwsSdkSigV4Config(config); return Object.assign(config_0, { authSchemePreference: normalizeProvider(config.authSchemePreference ?? []) }); }; } }); // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js var resolveClientEndpointParameters, commonParams; var init_EndpointParameters = __esm({ "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js"() { "use strict"; resolveClientEndpointParameters = (options) => { return Object.assign(options, { useDualstackEndpoint: options.useDualstackEndpoint ?? false, useFipsEndpoint: options.useFipsEndpoint ?? false, defaultSigningName: "rds-data" }); }; commonParams = { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } }; } }); // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json var package_default; var init_package = __esm({ "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json"() { package_default = { name: "@aws-sdk/client-rds-data", description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native", version: "3.817.0", scripts: { build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'", "build:cjs": "node ../../scripts/compilation/inline client-rds-data", "build:es": "tsc -p tsconfig.es.json", "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build", "build:types": "tsc -p tsconfig.types.json", "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", clean: "rimraf ./dist-* && rimraf *.tsbuildinfo", "extract:docs": "api-extractor run --local", "generate:client": "node ../../scripts/generate-clients/single-service --solo rds-data" }, main: "./dist-cjs/index.js", types: "./dist-types/index.d.ts", module: "./dist-es/index.js", sideEffects: false, dependencies: { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.816.0", "@aws-sdk/credential-provider-node": "3.817.0", "@aws-sdk/middleware-host-header": "3.804.0", "@aws-sdk/middleware-logger": "3.804.0", "@aws-sdk/middleware-recursion-detection": "3.804.0", "@aws-sdk/middleware-user-agent": "3.816.0", "@aws-sdk/region-config-resolver": "3.808.0", "@aws-sdk/types": "3.804.0", "@aws-sdk/util-endpoints": "3.808.0", "@aws-sdk/util-user-agent-browser": "3.804.0", "@aws-sdk/util-user-agent-node": "3.816.0", "@smithy/config-resolver": "^4.1.2", "@smithy/core": "^3.3.3", "@smithy/fetch-http-handler": "^5.0.2", "@smithy/hash-node": "^4.0.2", "@smithy/invalid-dependency": "^4.0.2", "@smithy/middleware-content-length": "^4.0.2", "@smithy/middleware-endpoint": "^4.1.6", "@smithy/middleware-retry": "^4.1.7", "@smithy/middleware-serde": "^4.0.5", "@smithy/middleware-stack": "^4.0.2", "@smithy/node-config-provider": "^4.1.1", "@smithy/node-http-handler": "^4.0.4", "@smithy/protocol-http": "^5.1.0", "@smithy/smithy-client": "^4.2.6", "@smithy/types": "^4.2.0", "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", "@smithy/util-defaults-mode-browser": "^4.0.14", "@smithy/util-defaults-mode-node": "^4.0.14", "@smithy/util-endpoints": "^3.0.4", "@smithy/util-middleware": "^4.0.2", "@smithy/util-retry": "^4.0.3", "@smithy/util-utf8": "^4.0.0", tslib: "^2.6.2" }, devDependencies: { "@tsconfig/node18": "18.2.4", "@types/node": "^18.19.69", concurrently: "7.0.0", "downlevel-dts": "0.10.1", rimraf: "3.0.2", typescript: "~5.8.3" }, engines: { node: ">=18.0.0" }, typesVersions: { "<4.0": { "dist-types/*": [ "dist-types/ts3.4/*" ] } }, files: [ "dist-*/**" ], author: { name: "AWS SDK for JavaScript Team", url: "https://aws.amazon.com/javascript/" }, license: "Apache-2.0", browser: { "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" }, "react-native": { "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" }, homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-rds-data", repository: { type: "git", url: "https://github.com/aws/aws-sdk-js-v3.git", directory: "clients/client-rds-data" } }; } }); // ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js var ENV_KEY, ENV_SECRET, ENV_SESSION, ENV_EXPIRATION, ENV_CREDENTIAL_SCOPE, ENV_ACCOUNT_ID, fromEnv2; var init_fromEnv2 = __esm({ "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"() { "use strict"; init_client2(); init_dist_es21(); ENV_KEY = "AWS_ACCESS_KEY_ID"; ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; ENV_SESSION = "AWS_SESSION_TOKEN"; ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; fromEnv2 = (init2) => async () => { init2?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); const accessKeyId = process.env[ENV_KEY]; const secretAccessKey = process.env[ENV_SECRET]; const sessionToken = process.env[ENV_SESSION]; const expiry = process.env[ENV_EXPIRATION]; const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; const accountId = process.env[ENV_ACCOUNT_ID]; if (accessKeyId && secretAccessKey) { const credentials2 = { accessKeyId, secretAccessKey, ...sessionToken && { sessionToken }, ...expiry && { expiration: new Date(expiry) }, ...credentialScope && { credentialScope }, ...accountId && { accountId } }; setCredentialFeature(credentials2, "CREDENTIALS_ENV_VARS", "g"); return credentials2; } throw new CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2?.logger }); }; } }); // ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js var dist_es_exports = {}; __export(dist_es_exports, { ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, ENV_EXPIRATION: () => ENV_EXPIRATION, ENV_KEY: () => ENV_KEY, ENV_SECRET: () => ENV_SECRET, ENV_SESSION: () => ENV_SESSION, fromEnv: () => fromEnv2 }); var init_dist_es38 = __esm({ "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js"() { "use strict"; init_fromEnv2(); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js function httpRequest(options) { return new Promise((resolve, reject) => { const req = (0, import_http4.request)({ method: "GET", ...options, hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") }); req.on("error", (err2) => { reject(Object.assign(new ProviderError("Unable to connect to instance metadata service"), err2)); req.destroy(); }); req.on("timeout", () => { reject(new ProviderError("TimeoutError from instance metadata service")); req.destroy(); }); req.on("response", (res) => { const { statusCode = 400 } = res; if (statusCode < 200 || 300 <= statusCode) { reject(Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode })); req.destroy(); } const chunks = []; res.on("data", (chunk) => { chunks.push(chunk); }); res.on("end", () => { resolve(import_buffer3.Buffer.concat(chunks)); req.destroy(); }); }); req.end(); }); } var import_buffer3, import_http4; var init_httpRequest2 = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js"() { "use strict"; init_dist_es21(); import_buffer3 = require("buffer"); import_http4 = require("http"); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js var isImdsCredentials, fromImdsCredentials; var init_ImdsCredentials = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js"() { "use strict"; isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string"; fromImdsCredentials = (creds) => ({ accessKeyId: creds.AccessKeyId, secretAccessKey: creds.SecretAccessKey, sessionToken: creds.Token, expiration: new Date(creds.Expiration), ...creds.AccountId && { accountId: creds.AccountId } }); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, providerConfigFromInit; var init_RemoteProviderInit = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js"() { "use strict"; DEFAULT_TIMEOUT = 1e3; DEFAULT_MAX_RETRIES = 0; providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout }); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js var retry; var init_retry3 = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js"() { "use strict"; retry = (toRetry, maxRetries) => { let promise = toRetry(); for (let i6 = 0; i6 < maxRetries; i6++) { promise = promise.catch(toRetry); } return promise; }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js var import_url8, ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, ENV_CMDS_AUTH_TOKEN, fromContainerMetadata, requestFromEcsImds, CMDS_IP, GREENGRASS_HOSTS, GREENGRASS_PROTOCOLS, getCmdsUri; var init_fromContainerMetadata = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js"() { "use strict"; init_dist_es21(); import_url8 = require("url"); init_httpRequest2(); init_ImdsCredentials(); init_RemoteProviderInit(); init_retry3(); ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; fromContainerMetadata = (init2 = {}) => { const { timeout, maxRetries } = providerConfigFromInit(init2); return () => retry(async () => { const requestOptions = await getCmdsUri({ logger: init2.logger }); const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); if (!isImdsCredentials(credsResponse)) { throw new CredentialsProviderError("Invalid response received from instance metadata service.", { logger: init2.logger }); } return fromImdsCredentials(credsResponse); }, maxRetries); }; requestFromEcsImds = async (timeout, options) => { if (process.env[ENV_CMDS_AUTH_TOKEN]) { options.headers = { ...options.headers, Authorization: process.env[ENV_CMDS_AUTH_TOKEN] }; } const buffer = await httpRequest({ ...options, timeout }); return buffer.toString(); }; CMDS_IP = "169.254.170.2"; GREENGRASS_HOSTS = { localhost: true, "127.0.0.1": true }; GREENGRASS_PROTOCOLS = { "http:": true, "https:": true }; getCmdsUri = async ({ logger: logger2 }) => { if (process.env[ENV_CMDS_RELATIVE_URI]) { return { hostname: CMDS_IP, path: process.env[ENV_CMDS_RELATIVE_URI] }; } if (process.env[ENV_CMDS_FULL_URI]) { const parsed = (0, import_url8.parse)(process.env[ENV_CMDS_FULL_URI]); if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { tryNextLink: false, logger: logger2 }); } if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { tryNextLink: false, logger: logger2 }); } return { ...parsed, port: parsed.port ? parseInt(parsed.port, 10) : void 0 }; } throw new CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, { tryNextLink: false, logger: logger2 }); }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js var InstanceMetadataV1FallbackError; var init_InstanceMetadataV1FallbackError = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js"() { "use strict"; init_dist_es21(); InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends CredentialsProviderError { constructor(message, tryNextLink = true) { super(message, tryNextLink); this.tryNextLink = tryNextLink; this.name = "InstanceMetadataV1FallbackError"; Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); } }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js var Endpoint; var init_Endpoint = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js"() { "use strict"; (function(Endpoint2) { Endpoint2["IPv4"] = "http://169.254.169.254"; Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; })(Endpoint || (Endpoint = {})); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js var ENV_ENDPOINT_NAME, CONFIG_ENDPOINT_NAME, ENDPOINT_CONFIG_OPTIONS; var init_EndpointConfigOptions = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js"() { "use strict"; ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_NAME], configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], default: void 0 }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js var EndpointMode; var init_EndpointMode = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js"() { "use strict"; (function(EndpointMode2) { EndpointMode2["IPv4"] = "IPv4"; EndpointMode2["IPv6"] = "IPv6"; })(EndpointMode || (EndpointMode = {})); } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js var ENV_ENDPOINT_MODE_NAME, CONFIG_ENDPOINT_MODE_NAME, ENDPOINT_MODE_CONFIG_OPTIONS; var init_EndpointModeConfigOptions = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js"() { "use strict"; init_EndpointMode(); ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; ENDPOINT_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_MODE_NAME], configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], default: EndpointMode.IPv4 }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js var getInstanceMetadataEndpoint, getFromEndpointConfig, getFromEndpointModeConfig; var init_getInstanceMetadataEndpoint = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js"() { "use strict"; init_dist_es31(); init_dist_es33(); init_Endpoint(); init_EndpointConfigOptions(); init_EndpointMode(); init_EndpointModeConfigOptions(); getInstanceMetadataEndpoint = async () => parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig()); getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)(); getFromEndpointModeConfig = async () => { const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); switch (endpointMode) { case EndpointMode.IPv4: return Endpoint.IPv4; case EndpointMode.IPv6: return Endpoint.IPv6; default: throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); } }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS, STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS, STATIC_STABILITY_DOC_URL, getExtendedInstanceMetadataCredentials; var init_getExtendedInstanceMetadataCredentials = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js"() { "use strict"; STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; getExtendedInstanceMetadataCredentials = (credentials2, logger2) => { const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); const newExpiration = new Date(Date.now() + refreshInterval * 1e3); logger2.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. For more information, please visit: ` + STATIC_STABILITY_DOC_URL); const originalExpiration = credentials2.originalExpiration ?? credentials2.expiration; return { ...credentials2, ...originalExpiration ? { originalExpiration } : {}, expiration: newExpiration }; }; } }); // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js var staticStabilityProvider; var init_staticStabilityProvider = __esm({ "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"() { "use strict"; init_getExtendedInstanceMetadataCredentials(); staticStabilityProvider = (provider, options = {}) => { const logger2 = options?.logger || console; let pastCredentials; return async () => { let credentials2; try {