@schemavaults/dbh 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist-cli/cli.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as B$}from"node:module";var f$=Object.create;var{getPrototypeOf:j$,defineProperty:f9,getOwnPropertyNames:A$}=Object;var N$=Object.prototype.hasOwnProperty;function C$(W){return this[W]}var q$,O$,x$=(W,$,Z)=>{var J=W!=null&&typeof W==="object";if(J){var X=$?q$??=new WeakMap:O$??=new WeakMap,Y=X.get(W);if(Y)return Y}Z=W!=null?f$(j$(W)):{};let M=$||!W||!W.__esModule?f9(Z,"default",{value:W,enumerable:!0}):Z;for(let G of A$(W))if(!N$.call(M,G))f9(M,G,{get:C$.bind(W,G),enumerable:!0});if(J)X.set(W,M);return M};var L8=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var LW=B$(import.meta.url);var KW=L8((b$)=>{class o4 extends Error{constructor(W,$,Z){super(Z);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=W,this.nestedError=void 0}}class j9 extends o4{constructor(W){super(1,"commander.invalidArgument",W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}b$.CommanderError=o4;b$.InvalidArgumentError=j9});var oW=L8((c$)=>{var{InvalidArgumentError:g$}=KW();class A9{constructor(W,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,W[0]){case"<":this.required=!0,this._name=W.slice(1,-1);break;case"[":this.required=!1,this._name=W.slice(1,-1);break;default:this.required=!0,this._name=W;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}argParser(W){return this.parseArg=W,this}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new g$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function m$(W){let $=W.name()+(W.variadic===!0?"...":"");return W.required?"<"+$+">":"["+$+"]"}c$.Argument=A9;c$.humanReadableArgName=m$});var e4=L8((i$)=>{var{humanReadableArgName:p$}=oW();class N9{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(W){this.helpWidth=this.helpWidth??W.helpWidth??80}visibleCommands(W){let $=W.commands.filter((J)=>!J._hidden),Z=W._getHelpCommand();if(Z&&!Z._hidden)$.push(Z);if(this.sortSubcommands)$.sort((J,X)=>{return J.name().localeCompare(X.name())});return $}compareOptions(W,$){let Z=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return Z(W).localeCompare(Z($))}visibleOptions(W){let $=W.options.filter((J)=>!J.hidden),Z=W._getHelpOption();if(Z&&!Z.hidden){let J=Z.short&&W._findOption(Z.short),X=Z.long&&W._findOption(Z.long);if(!J&&!X)$.push(Z);else if(Z.long&&!X)$.push(W.createOption(Z.long,Z.description));else if(Z.short&&!J)$.push(W.createOption(Z.short,Z.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(W){if(!this.showGlobalOptions)return[];let $=[];for(let Z=W.parent;Z;Z=Z.parent){let J=Z.options.filter((X)=>!X.hidden);$.push(...J)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(W){if(W._argsDescription)W.registeredArguments.forEach(($)=>{$.description=$.description||W._argsDescription[$.name()]||""});if(W.registeredArguments.find(($)=>$.description))return W.registeredArguments;return[]}subcommandTerm(W){let $=W.registeredArguments.map((Z)=>p$(Z)).join(" ");return W._name+(W._aliases[0]?"|"+W._aliases[0]:"")+(W.options.length?" [options]":"")+($?" "+$:"")}optionTerm(W){return W.flags}argumentTerm(W){return W.name()}longestSubcommandTermLength(W,$){return $.visibleCommands(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(J))))},0)}longestOptionTermLength(W,$){return $.visibleOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestGlobalOptionTermLength(W,$){return $.visibleGlobalOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestArgumentTermLength(W,$){return $.visibleArguments(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleArgumentTerm($.argumentTerm(J))))},0)}commandUsage(W){let $=W._name;if(W._aliases[0])$=$+"|"+W._aliases[0];let Z="";for(let J=W.parent;J;J=J.parent)Z=J.name()+" "+Z;return Z+$+" "+W.usage()}commandDescription(W){return W.description()}subcommandDescription(W){return W.summary()||W.description()}optionDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0){if(W.required||W.optional||W.isBoolean()&&typeof W.defaultValue==="boolean")$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`)}if(W.presetArg!==void 0&&W.optional)$.push(`preset: ${JSON.stringify(W.presetArg)}`);if(W.envVar!==void 0)$.push(`env: ${W.envVar}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}argumentDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0)$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}formatItemList(W,$,Z){if($.length===0)return[];return[Z.styleTitle(W),...$,""]}groupItems(W,$,Z){let J=new Map;return W.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[])}),$.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[]);J.get(Y).push(X)}),J}formatHelp(W,$){let Z=$.padWidth(W,$),J=$.helpWidth??80;function X(P,w){return $.formatItem(P,Z,w,$)}let Y=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(W))}`,""],M=$.commandDescription(W);if(M.length>0)Y=Y.concat([$.boxWrap($.styleCommandDescription(M),J),""]);let G=$.visibleArguments(W).map((P)=>{return X($.styleArgumentTerm($.argumentTerm(P)),$.styleArgumentDescription($.argumentDescription(P)))});if(Y=Y.concat(this.formatItemList("Arguments:",G,$)),this.groupItems(W.options,$.visibleOptions(W),(P)=>P.helpGroupHeading??"Options:").forEach((P,w)=>{let D=P.map((S)=>{return X($.styleOptionTerm($.optionTerm(S)),$.styleOptionDescription($.optionDescription(S)))});Y=Y.concat(this.formatItemList(w,D,$))}),$.showGlobalOptions){let P=$.visibleGlobalOptions(W).map((w)=>{return X($.styleOptionTerm($.optionTerm(w)),$.styleOptionDescription($.optionDescription(w)))});Y=Y.concat(this.formatItemList("Global Options:",P,$))}return this.groupItems(W.commands,$.visibleCommands(W),(P)=>P.helpGroup()||"Commands:").forEach((P,w)=>{let D=P.map((S)=>{return X($.styleSubcommandTerm($.subcommandTerm(S)),$.styleSubcommandDescription($.subcommandDescription(S)))});Y=Y.concat(this.formatItemList(w,D,$))}),Y.join(`
3
- `)}displayWidth(W){return C9(W).length}styleTitle(W){return W}styleUsage(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(W){return this.styleDescriptionText(W)}styleOptionDescription(W){return this.styleDescriptionText(W)}styleSubcommandDescription(W){return this.styleDescriptionText(W)}styleArgumentDescription(W){return this.styleDescriptionText(W)}styleDescriptionText(W){return W}styleOptionTerm(W){return this.styleOptionText(W)}styleSubcommandTerm(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(W){return this.styleArgumentText(W)}styleOptionText(W){return W}styleArgumentText(W){return W}styleSubcommandText(W){return W}styleCommandText(W){return W}padWidth(W,$){return Math.max($.longestOptionTermLength(W,$),$.longestGlobalOptionTermLength(W,$),$.longestSubcommandTermLength(W,$),$.longestArgumentTermLength(W,$))}preformatted(W){return/\n[^\S\r\n]/.test(W)}formatItem(W,$,Z,J){let Y=" ".repeat(2);if(!Z)return Y+W;let M=W.padEnd($+W.length-J.displayWidth(W)),G=2,R=(this.helpWidth??80)-$-G-2,P;if(R<this.minWidthToWrap||J.preformatted(Z))P=Z;else P=J.boxWrap(Z,R).replace(/\n/g,`
4
- `+" ".repeat($+G));return Y+M+" ".repeat(G)+P.replace(/\n/g,`
5
- ${Y}`)}boxWrap(W,$){if($<this.minWidthToWrap)return W;let Z=W.split(/\r\n|\n/),J=/[\s]*[^\s]+/g,X=[];return Z.forEach((Y)=>{let M=Y.match(J);if(M===null){X.push("");return}let G=[M.shift()],V=this.displayWidth(G[0]);M.forEach((R)=>{let P=this.displayWidth(R);if(V+P<=$){G.push(R),V+=P;return}X.push(G.join(""));let w=R.trimStart();G=[w],V=this.displayWidth(w)}),X.push(G.join(""))}),X.join(`
6
- `)}}function C9(W){let $=/\x1b\[\d*(;\d*)*m/g;return W.replace($,"")}i$.Help=N9;i$.stripColor=C9});var W6=L8((n$)=>{var{InvalidArgumentError:d$}=KW();class O9{constructor(W,$){this.flags=W,this.description=$||"",this.required=W.includes("<"),this.optional=W.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(W),this.mandatory=!1;let Z=s$(W);if(this.short=Z.shortFlag,this.long=Z.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}preset(W){return this.presetArg=W,this}conflicts(W){return this.conflictsWith=this.conflictsWith.concat(W),this}implies(W){let $=W;if(typeof W==="string")$={[W]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(W){return this.envVar=W,this}argParser(W){return this.parseArg=W,this}makeOptionMandatory(W=!0){return this.mandatory=!!W,this}hideHelp(W=!0){return this.hidden=!!W,this}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new d$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return q9(this.name().replace(/^no-/,""));return q9(this.name())}helpGroup(W){return this.helpGroupHeading=W,this}is(W){return this.short===W||this.long===W}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class x9{constructor(W){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,W.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,Z)=>{if(this.positiveOptions.has(Z))this.dualOptions.add(Z)})}valueFromOption(W,$){let Z=$.attributeName();if(!this.dualOptions.has(Z))return!0;let J=this.negativeOptions.get(Z).presetArg,X=J!==void 0?J:!1;return $.negate===(X===W)}}function q9(W){return W.split("-").reduce(($,Z)=>{return $+Z[0].toUpperCase()+Z.slice(1)})}function s$(W){let $,Z,J=/^-[^-]$/,X=/^--[^-]/,Y=W.split(/[ |,]+/).concat("guard");if(J.test(Y[0]))$=Y.shift();if(X.test(Y[0]))Z=Y.shift();if(!$&&J.test(Y[0]))$=Y.shift();if(!$&&X.test(Y[0]))$=Z,Z=Y.shift();if(Y[0].startsWith("-")){let M=Y[0],G=`option creation failed due to '${M}' in option flags '${W}'`;if(/^-[^-][^-]/.test(M))throw Error(`${G}
2
+ import{createRequire as y$}from"node:module";var N$=Object.create;var{getPrototypeOf:C$,defineProperty:j9,getOwnPropertyNames:q$}=Object;var O$=Object.prototype.hasOwnProperty;function x$(W){return this[W]}var B$,b$,I$=(W,$,Z)=>{var J=W!=null&&typeof W==="object";if(J){var X=$?B$??=new WeakMap:b$??=new WeakMap,Y=X.get(W);if(Y)return Y}Z=W!=null?N$(C$(W)):{};let L=$||!W||!W.__esModule?j9(Z,"default",{value:W,enumerable:!0}):Z;for(let G of q$(W))if(!O$.call(L,G))j9(L,G,{get:x$.bind(W,G),enumerable:!0});if(J)X.set(W,L);return L};var K8=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var KW=y$(import.meta.url);var MW=K8((g$)=>{class e4 extends Error{constructor(W,$,Z){super(Z);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=W,this.nestedError=void 0}}class A9 extends e4{constructor(W){super(1,"commander.invalidArgument",W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}g$.CommanderError=e4;g$.InvalidArgumentError=A9});var eW=K8((p$)=>{var{InvalidArgumentError:u$}=MW();class N9{constructor(W,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,W[0]){case"<":this.required=!0,this._name=W.slice(1,-1);break;case"[":this.required=!1,this._name=W.slice(1,-1);break;default:this.required=!0,this._name=W;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}argParser(W){return this.parseArg=W,this}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new u$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function l$(W){let $=W.name()+(W.variadic===!0?"...":"");return W.required?"<"+$+">":"["+$+"]"}p$.Argument=N9;p$.humanReadableArgName=l$});var W6=K8((d$)=>{var{humanReadableArgName:a$}=eW();class C9{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(W){this.helpWidth=this.helpWidth??W.helpWidth??80}visibleCommands(W){let $=W.commands.filter((J)=>!J._hidden),Z=W._getHelpCommand();if(Z&&!Z._hidden)$.push(Z);if(this.sortSubcommands)$.sort((J,X)=>{return J.name().localeCompare(X.name())});return $}compareOptions(W,$){let Z=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return Z(W).localeCompare(Z($))}visibleOptions(W){let $=W.options.filter((J)=>!J.hidden),Z=W._getHelpOption();if(Z&&!Z.hidden){let J=Z.short&&W._findOption(Z.short),X=Z.long&&W._findOption(Z.long);if(!J&&!X)$.push(Z);else if(Z.long&&!X)$.push(W.createOption(Z.long,Z.description));else if(Z.short&&!J)$.push(W.createOption(Z.short,Z.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(W){if(!this.showGlobalOptions)return[];let $=[];for(let Z=W.parent;Z;Z=Z.parent){let J=Z.options.filter((X)=>!X.hidden);$.push(...J)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(W){if(W._argsDescription)W.registeredArguments.forEach(($)=>{$.description=$.description||W._argsDescription[$.name()]||""});if(W.registeredArguments.find(($)=>$.description))return W.registeredArguments;return[]}subcommandTerm(W){let $=W.registeredArguments.map((Z)=>a$(Z)).join(" ");return W._name+(W._aliases[0]?"|"+W._aliases[0]:"")+(W.options.length?" [options]":"")+($?" "+$:"")}optionTerm(W){return W.flags}argumentTerm(W){return W.name()}longestSubcommandTermLength(W,$){return $.visibleCommands(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(J))))},0)}longestOptionTermLength(W,$){return $.visibleOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestGlobalOptionTermLength(W,$){return $.visibleGlobalOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestArgumentTermLength(W,$){return $.visibleArguments(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleArgumentTerm($.argumentTerm(J))))},0)}commandUsage(W){let $=W._name;if(W._aliases[0])$=$+"|"+W._aliases[0];let Z="";for(let J=W.parent;J;J=J.parent)Z=J.name()+" "+Z;return Z+$+" "+W.usage()}commandDescription(W){return W.description()}subcommandDescription(W){return W.summary()||W.description()}optionDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0){if(W.required||W.optional||W.isBoolean()&&typeof W.defaultValue==="boolean")$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`)}if(W.presetArg!==void 0&&W.optional)$.push(`preset: ${JSON.stringify(W.presetArg)}`);if(W.envVar!==void 0)$.push(`env: ${W.envVar}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}argumentDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0)$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}formatItemList(W,$,Z){if($.length===0)return[];return[Z.styleTitle(W),...$,""]}groupItems(W,$,Z){let J=new Map;return W.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[])}),$.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[]);J.get(Y).push(X)}),J}formatHelp(W,$){let Z=$.padWidth(W,$),J=$.helpWidth??80;function X(P,w){return $.formatItem(P,Z,w,$)}let Y=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(W))}`,""],L=$.commandDescription(W);if(L.length>0)Y=Y.concat([$.boxWrap($.styleCommandDescription(L),J),""]);let G=$.visibleArguments(W).map((P)=>{return X($.styleArgumentTerm($.argumentTerm(P)),$.styleArgumentDescription($.argumentDescription(P)))});if(Y=Y.concat(this.formatItemList("Arguments:",G,$)),this.groupItems(W.options,$.visibleOptions(W),(P)=>P.helpGroupHeading??"Options:").forEach((P,w)=>{let R=P.map((S)=>{return X($.styleOptionTerm($.optionTerm(S)),$.styleOptionDescription($.optionDescription(S)))});Y=Y.concat(this.formatItemList(w,R,$))}),$.showGlobalOptions){let P=$.visibleGlobalOptions(W).map((w)=>{return X($.styleOptionTerm($.optionTerm(w)),$.styleOptionDescription($.optionDescription(w)))});Y=Y.concat(this.formatItemList("Global Options:",P,$))}return this.groupItems(W.commands,$.visibleCommands(W),(P)=>P.helpGroup()||"Commands:").forEach((P,w)=>{let R=P.map((S)=>{return X($.styleSubcommandTerm($.subcommandTerm(S)),$.styleSubcommandDescription($.subcommandDescription(S)))});Y=Y.concat(this.formatItemList(w,R,$))}),Y.join(`
3
+ `)}displayWidth(W){return q9(W).length}styleTitle(W){return W}styleUsage(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(W){return this.styleDescriptionText(W)}styleOptionDescription(W){return this.styleDescriptionText(W)}styleSubcommandDescription(W){return this.styleDescriptionText(W)}styleArgumentDescription(W){return this.styleDescriptionText(W)}styleDescriptionText(W){return W}styleOptionTerm(W){return this.styleOptionText(W)}styleSubcommandTerm(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(W){return this.styleArgumentText(W)}styleOptionText(W){return W}styleArgumentText(W){return W}styleSubcommandText(W){return W}styleCommandText(W){return W}padWidth(W,$){return Math.max($.longestOptionTermLength(W,$),$.longestGlobalOptionTermLength(W,$),$.longestSubcommandTermLength(W,$),$.longestArgumentTermLength(W,$))}preformatted(W){return/\n[^\S\r\n]/.test(W)}formatItem(W,$,Z,J){let Y=" ".repeat(2);if(!Z)return Y+W;let L=W.padEnd($+W.length-J.displayWidth(W)),G=2,D=(this.helpWidth??80)-$-G-2,P;if(D<this.minWidthToWrap||J.preformatted(Z))P=Z;else P=J.boxWrap(Z,D).replace(/\n/g,`
4
+ `+" ".repeat($+G));return Y+L+" ".repeat(G)+P.replace(/\n/g,`
5
+ ${Y}`)}boxWrap(W,$){if($<this.minWidthToWrap)return W;let Z=W.split(/\r\n|\n/),J=/[\s]*[^\s]+/g,X=[];return Z.forEach((Y)=>{let L=Y.match(J);if(L===null){X.push("");return}let G=[L.shift()],U=this.displayWidth(G[0]);L.forEach((D)=>{let P=this.displayWidth(D);if(U+P<=$){G.push(D),U+=P;return}X.push(G.join(""));let w=D.trimStart();G=[w],U=this.displayWidth(w)}),X.push(G.join(""))}),X.join(`
6
+ `)}}function q9(W){let $=/\x1b\[\d*(;\d*)*m/g;return W.replace($,"")}d$.Help=C9;d$.stripColor=q9});var $6=K8((e$)=>{var{InvalidArgumentError:r$}=MW();class x9{constructor(W,$){this.flags=W,this.description=$||"",this.required=W.includes("<"),this.optional=W.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(W),this.mandatory=!1;let Z=o$(W);if(this.short=Z.shortFlag,this.long=Z.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}preset(W){return this.presetArg=W,this}conflicts(W){return this.conflictsWith=this.conflictsWith.concat(W),this}implies(W){let $=W;if(typeof W==="string")$={[W]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(W){return this.envVar=W,this}argParser(W){return this.parseArg=W,this}makeOptionMandatory(W=!0){return this.mandatory=!!W,this}hideHelp(W=!0){return this.hidden=!!W,this}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new r$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return O9(this.name().replace(/^no-/,""));return O9(this.name())}helpGroup(W){return this.helpGroupHeading=W,this}is(W){return this.short===W||this.long===W}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class B9{constructor(W){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,W.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,Z)=>{if(this.positiveOptions.has(Z))this.dualOptions.add(Z)})}valueFromOption(W,$){let Z=$.attributeName();if(!this.dualOptions.has(Z))return!0;let J=this.negativeOptions.get(Z).presetArg,X=J!==void 0?J:!1;return $.negate===(X===W)}}function O9(W){return W.split("-").reduce(($,Z)=>{return $+Z[0].toUpperCase()+Z.slice(1)})}function o$(W){let $,Z,J=/^-[^-]$/,X=/^--[^-]/,Y=W.split(/[ |,]+/).concat("guard");if(J.test(Y[0]))$=Y.shift();if(X.test(Y[0]))Z=Y.shift();if(!$&&J.test(Y[0]))$=Y.shift();if(!$&&X.test(Y[0]))$=Z,Z=Y.shift();if(Y[0].startsWith("-")){let L=Y[0],G=`option creation failed due to '${L}' in option flags '${W}'`;if(/^-[^-][^-]/.test(L))throw Error(`${G}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(J.test(M))throw Error(`${G}
10
- - too many short flags`);if(X.test(M))throw Error(`${G}
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(J.test(L))throw Error(`${G}
10
+ - too many short flags`);if(X.test(L))throw Error(`${G}
11
11
  - too many long flags`);throw Error(`${G}
12
- - unrecognised flag format`)}if($===void 0&&Z===void 0)throw Error(`option creation failed due to no flags found in '${W}'.`);return{shortFlag:$,longFlag:Z}}n$.Option=O9;n$.DualOptions=x9});var B9=L8(($2)=>{function e$(W,$){if(Math.abs(W.length-$.length)>3)return Math.max(W.length,$.length);let Z=[];for(let J=0;J<=W.length;J++)Z[J]=[J];for(let J=0;J<=$.length;J++)Z[0][J]=J;for(let J=1;J<=$.length;J++)for(let X=1;X<=W.length;X++){let Y=1;if(W[X-1]===$[J-1])Y=0;else Y=1;if(Z[X][J]=Math.min(Z[X-1][J]+1,Z[X][J-1]+1,Z[X-1][J-1]+Y),X>1&&J>1&&W[X-1]===$[J-2]&&W[X-2]===$[J-1])Z[X][J]=Math.min(Z[X][J],Z[X-2][J-2]+1)}return Z[W.length][$.length]}function W2(W,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let Z=W.startsWith("--");if(Z)W=W.slice(2),$=$.map((M)=>M.slice(2));let J=[],X=3,Y=0.4;if($.forEach((M)=>{if(M.length<=1)return;let G=e$(W,M),V=Math.max(W.length,M.length);if((V-G)/V>Y){if(G<X)X=G,J=[M];else if(G===X)J.push(M)}}),J.sort((M,G)=>M.localeCompare(G)),Z)J=J.map((M)=>`--${M}`);if(J.length>1)return`
12
+ - unrecognised flag format`)}if($===void 0&&Z===void 0)throw Error(`option creation failed due to no flags found in '${W}'.`);return{shortFlag:$,longFlag:Z}}e$.Option=x9;e$.DualOptions=B9});var b9=K8((X2)=>{function Z2(W,$){if(Math.abs(W.length-$.length)>3)return Math.max(W.length,$.length);let Z=[];for(let J=0;J<=W.length;J++)Z[J]=[J];for(let J=0;J<=$.length;J++)Z[0][J]=J;for(let J=1;J<=$.length;J++)for(let X=1;X<=W.length;X++){let Y=1;if(W[X-1]===$[J-1])Y=0;else Y=1;if(Z[X][J]=Math.min(Z[X-1][J]+1,Z[X][J-1]+1,Z[X-1][J-1]+Y),X>1&&J>1&&W[X-1]===$[J-2]&&W[X-2]===$[J-1])Z[X][J]=Math.min(Z[X][J],Z[X-2][J-2]+1)}return Z[W.length][$.length]}function J2(W,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let Z=W.startsWith("--");if(Z)W=W.slice(2),$=$.map((L)=>L.slice(2));let J=[],X=3,Y=0.4;if($.forEach((L)=>{if(L.length<=1)return;let G=Z2(W,L),U=Math.max(W.length,L.length);if((U-G)/U>Y){if(G<X)X=G,J=[L];else if(G===X)J.push(L)}}),J.sort((L,G)=>L.localeCompare(G)),Z)J=J.map((L)=>`--${L}`);if(J.length>1)return`
13
13
  (Did you mean one of ${J.join(", ")}?)`;if(J.length===1)return`
14
- (Did you mean ${J[0]}?)`;return""}$2.suggestSimilar=W2});var g9=L8((M2)=>{var J2=LW("node:events").EventEmitter,$6=LW("node:child_process"),x0=LW("node:path"),eW=LW("node:fs"),H1=LW("node:process"),{Argument:X2,humanReadableArgName:Y2}=oW(),{CommanderError:Z6}=KW(),{Help:H2,stripColor:k2}=e4(),{Option:b9,DualOptions:G2}=W6(),{suggestSimilar:I9}=B9();class X6 extends J2{constructor(W){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=W||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:($)=>H1.stdout.write($),writeErr:($)=>H1.stderr.write($),outputError:($,Z)=>Z($),getOutHelpWidth:()=>H1.stdout.isTTY?H1.stdout.columns:void 0,getErrHelpWidth:()=>H1.stderr.isTTY?H1.stderr.columns:void 0,getOutHasColors:()=>J6()??(H1.stdout.isTTY&&H1.stdout.hasColors?.()),getErrHasColors:()=>J6()??(H1.stderr.isTTY&&H1.stderr.hasColors?.()),stripColor:($)=>k2($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(W){return this._outputConfiguration=W._outputConfiguration,this._helpOption=W._helpOption,this._helpCommand=W._helpCommand,this._helpConfiguration=W._helpConfiguration,this._exitCallback=W._exitCallback,this._storeOptionsAsProperties=W._storeOptionsAsProperties,this._combineFlagAndOptionalValue=W._combineFlagAndOptionalValue,this._allowExcessArguments=W._allowExcessArguments,this._enablePositionalOptions=W._enablePositionalOptions,this._showHelpAfterError=W._showHelpAfterError,this._showSuggestionAfterError=W._showSuggestionAfterError,this}_getCommandAndAncestors(){let W=[];for(let $=this;$;$=$.parent)W.push($);return W}command(W,$,Z){let J=$,X=Z;if(typeof J==="object"&&J!==null)X=J,J=null;X=X||{};let[,Y,M]=W.match(/([^ ]+) *(.*)/),G=this.createCommand(Y);if(J)G.description(J),G._executableHandler=!0;if(X.isDefault)this._defaultCommandName=G._name;if(G._hidden=!!(X.noHelp||X.hidden),G._executableFile=X.executableFile||null,M)G.arguments(M);if(this._registerCommand(G),G.parent=this,G.copyInheritedSettings(this),J)return this;return G}createCommand(W){return new X6(W)}createHelp(){return Object.assign(new H2,this.configureHelp())}configureHelp(W){if(W===void 0)return this._helpConfiguration;return this._helpConfiguration=W,this}configureOutput(W){if(W===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...W},this}showHelpAfterError(W=!0){if(typeof W!=="string")W=!!W;return this._showHelpAfterError=W,this}showSuggestionAfterError(W=!0){return this._showSuggestionAfterError=!!W,this}addCommand(W,$){if(!W._name)throw Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=W._name;if($.noHelp||$.hidden)W._hidden=!0;return this._registerCommand(W),W.parent=this,W._checkForBrokenPassThrough(),this}createArgument(W,$){return new X2(W,$)}argument(W,$,Z,J){let X=this.createArgument(W,$);if(typeof Z==="function")X.default(J).argParser(Z);else X.default(Z);return this.addArgument(X),this}arguments(W){return W.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(W){let $=this.registeredArguments.slice(-1)[0];if($?.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(W.required&&W.defaultValue!==void 0&&W.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${W.name()}'`);return this.registeredArguments.push(W),this}helpCommand(W,$){if(typeof W==="boolean"){if(this._addImplicitHelpCommand=W,W&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Z=W??"help [command]",[,J,X]=Z.match(/([^ ]+) *(.*)/),Y=$??"display help for command",M=this.createCommand(J);if(M.helpOption(!1),X)M.arguments(X);if(Y)M.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=M,W||$)this._initCommandGroup(M);return this}addHelpCommand(W,$){if(typeof W!=="object")return this.helpCommand(W,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=W,this._initCommandGroup(W),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(W,$){let Z=["preSubcommand","preAction","postAction"];if(!Z.includes(W))throw Error(`Unexpected value for event passed to hook : '${W}'.
16
- Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[W])this._lifeCycleHooks[W].push($);else this._lifeCycleHooks[W]=[$];return this}exitOverride(W){if(W)this._exitCallback=W;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(W,$,Z){if(this._exitCallback)this._exitCallback(new Z6(W,$,Z));H1.exit(W)}action(W){let $=(Z)=>{let J=this.registeredArguments.length,X=Z.slice(0,J);if(this._storeOptionsAsProperties)X[J]=this;else X[J]=this.opts();return X.push(this),W.apply(this,X)};return this._actionHandler=$,this}createOption(W,$){return new b9(W,$)}_callParseArg(W,$,Z,J){try{return W.parseArg($,Z)}catch(X){if(X.code==="commander.invalidArgument"){let Y=`${J} ${X.message}`;this.error(Y,{exitCode:X.exitCode,code:X.code})}throw X}}_registerOption(W){let $=W.short&&this._findOption(W.short)||W.long&&this._findOption(W.long);if($){let Z=W.long&&this._findOption(W.long)?W.long:W.short;throw Error(`Cannot add option '${W.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Z}'
17
- - already used by option '${$.flags}'`)}this._initOptionGroup(W),this.options.push(W)}_registerCommand(W){let $=(J)=>{return[J.name()].concat(J.aliases())},Z=$(W).find((J)=>this._findCommand(J));if(Z){let J=$(this._findCommand(Z)).join("|"),X=$(W).join("|");throw Error(`cannot add command '${X}' as already have command '${J}'`)}this._initCommandGroup(W),this.commands.push(W)}addOption(W){this._registerOption(W);let $=W.name(),Z=W.attributeName();if(W.negate){let X=W.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(Z,W.defaultValue===void 0?!0:W.defaultValue,"default")}else if(W.defaultValue!==void 0)this.setOptionValueWithSource(Z,W.defaultValue,"default");let J=(X,Y,M)=>{if(X==null&&W.presetArg!==void 0)X=W.presetArg;let G=this.getOptionValue(Z);if(X!==null&&W.parseArg)X=this._callParseArg(W,X,G,Y);else if(X!==null&&W.variadic)X=W._collectValue(X,G);if(X==null)if(W.negate)X=!1;else if(W.isBoolean()||W.optional)X=!0;else X="";this.setOptionValueWithSource(Z,X,M)};if(this.on("option:"+$,(X)=>{let Y=`error: option '${W.flags}' argument '${X}' is invalid.`;J(X,Y,"cli")}),W.envVar)this.on("optionEnv:"+$,(X)=>{let Y=`error: option '${W.flags}' value '${X}' from env '${W.envVar}' is invalid.`;J(X,Y,"env")});return this}_optionEx(W,$,Z,J,X){if(typeof $==="object"&&$ instanceof b9)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption($,Z);if(Y.makeOptionMandatory(!!W.mandatory),typeof J==="function")Y.default(X).argParser(J);else if(J instanceof RegExp){let M=J;J=(G,V)=>{let R=M.exec(G);return R?R[0]:V},Y.default(X).argParser(J)}else Y.default(J);return this.addOption(Y)}option(W,$,Z,J){return this._optionEx({},W,$,Z,J)}requiredOption(W,$,Z,J){return this._optionEx({mandatory:!0},W,$,Z,J)}combineFlagAndOptionalValue(W=!0){return this._combineFlagAndOptionalValue=!!W,this}allowUnknownOption(W=!0){return this._allowUnknownOption=!!W,this}allowExcessArguments(W=!0){return this._allowExcessArguments=!!W,this}enablePositionalOptions(W=!0){return this._enablePositionalOptions=!!W,this}passThroughOptions(W=!0){return this._passThroughOptions=!!W,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(W=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!W,this}getOptionValue(W){if(this._storeOptionsAsProperties)return this[W];return this._optionValues[W]}setOptionValue(W,$){return this.setOptionValueWithSource(W,$,void 0)}setOptionValueWithSource(W,$,Z){if(this._storeOptionsAsProperties)this[W]=$;else this._optionValues[W]=$;return this._optionValueSources[W]=Z,this}getOptionValueSource(W){return this._optionValueSources[W]}getOptionValueSourceWithGlobals(W){let $;return this._getCommandAndAncestors().forEach((Z)=>{if(Z.getOptionValueSource(W)!==void 0)$=Z.getOptionValueSource(W)}),$}_prepareUserArgs(W,$){if(W!==void 0&&!Array.isArray(W))throw Error("first parameter to parse must be array or undefined");if($=$||{},W===void 0&&$.from===void 0){if(H1.versions?.electron)$.from="electron";let J=H1.execArgv??[];if(J.includes("-e")||J.includes("--eval")||J.includes("-p")||J.includes("--print"))$.from="eval"}if(W===void 0)W=H1.argv;this.rawArgs=W.slice();let Z;switch($.from){case void 0:case"node":this._scriptPath=W[1],Z=W.slice(2);break;case"electron":if(H1.defaultApp)this._scriptPath=W[1],Z=W.slice(2);else Z=W.slice(1);break;case"user":Z=W.slice(0);break;case"eval":Z=W.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Z}parse(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return this._parseCommand([],Z),this}async parseAsync(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return await this._parseCommand([],Z),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
18
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(W,$,Z){if(eW.existsSync(W))return;let J=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",X=`'${W}' does not exist
14
+ (Did you mean ${J[0]}?)`;return""}X2.suggestSimilar=J2});var m9=K8((z2)=>{var H2=KW("node:events").EventEmitter,Z6=KW("node:child_process"),x0=KW("node:path"),W4=KW("node:fs"),H1=KW("node:process"),{Argument:k2,humanReadableArgName:G2}=eW(),{CommanderError:J6}=MW(),{Help:L2,stripColor:K2}=W6(),{Option:I9,DualOptions:M2}=$6(),{suggestSimilar:y9}=b9();class Y6 extends H2{constructor(W){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=W||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:($)=>H1.stdout.write($),writeErr:($)=>H1.stderr.write($),outputError:($,Z)=>Z($),getOutHelpWidth:()=>H1.stdout.isTTY?H1.stdout.columns:void 0,getErrHelpWidth:()=>H1.stderr.isTTY?H1.stderr.columns:void 0,getOutHasColors:()=>X6()??(H1.stdout.isTTY&&H1.stdout.hasColors?.()),getErrHasColors:()=>X6()??(H1.stderr.isTTY&&H1.stderr.hasColors?.()),stripColor:($)=>K2($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(W){return this._outputConfiguration=W._outputConfiguration,this._helpOption=W._helpOption,this._helpCommand=W._helpCommand,this._helpConfiguration=W._helpConfiguration,this._exitCallback=W._exitCallback,this._storeOptionsAsProperties=W._storeOptionsAsProperties,this._combineFlagAndOptionalValue=W._combineFlagAndOptionalValue,this._allowExcessArguments=W._allowExcessArguments,this._enablePositionalOptions=W._enablePositionalOptions,this._showHelpAfterError=W._showHelpAfterError,this._showSuggestionAfterError=W._showSuggestionAfterError,this}_getCommandAndAncestors(){let W=[];for(let $=this;$;$=$.parent)W.push($);return W}command(W,$,Z){let J=$,X=Z;if(typeof J==="object"&&J!==null)X=J,J=null;X=X||{};let[,Y,L]=W.match(/([^ ]+) *(.*)/),G=this.createCommand(Y);if(J)G.description(J),G._executableHandler=!0;if(X.isDefault)this._defaultCommandName=G._name;if(G._hidden=!!(X.noHelp||X.hidden),G._executableFile=X.executableFile||null,L)G.arguments(L);if(this._registerCommand(G),G.parent=this,G.copyInheritedSettings(this),J)return this;return G}createCommand(W){return new Y6(W)}createHelp(){return Object.assign(new L2,this.configureHelp())}configureHelp(W){if(W===void 0)return this._helpConfiguration;return this._helpConfiguration=W,this}configureOutput(W){if(W===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...W},this}showHelpAfterError(W=!0){if(typeof W!=="string")W=!!W;return this._showHelpAfterError=W,this}showSuggestionAfterError(W=!0){return this._showSuggestionAfterError=!!W,this}addCommand(W,$){if(!W._name)throw Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=W._name;if($.noHelp||$.hidden)W._hidden=!0;return this._registerCommand(W),W.parent=this,W._checkForBrokenPassThrough(),this}createArgument(W,$){return new k2(W,$)}argument(W,$,Z,J){let X=this.createArgument(W,$);if(typeof Z==="function")X.default(J).argParser(Z);else X.default(Z);return this.addArgument(X),this}arguments(W){return W.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(W){let $=this.registeredArguments.slice(-1)[0];if($?.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(W.required&&W.defaultValue!==void 0&&W.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${W.name()}'`);return this.registeredArguments.push(W),this}helpCommand(W,$){if(typeof W==="boolean"){if(this._addImplicitHelpCommand=W,W&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Z=W??"help [command]",[,J,X]=Z.match(/([^ ]+) *(.*)/),Y=$??"display help for command",L=this.createCommand(J);if(L.helpOption(!1),X)L.arguments(X);if(Y)L.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=L,W||$)this._initCommandGroup(L);return this}addHelpCommand(W,$){if(typeof W!=="object")return this.helpCommand(W,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=W,this._initCommandGroup(W),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(W,$){let Z=["preSubcommand","preAction","postAction"];if(!Z.includes(W))throw Error(`Unexpected value for event passed to hook : '${W}'.
16
+ Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[W])this._lifeCycleHooks[W].push($);else this._lifeCycleHooks[W]=[$];return this}exitOverride(W){if(W)this._exitCallback=W;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(W,$,Z){if(this._exitCallback)this._exitCallback(new J6(W,$,Z));H1.exit(W)}action(W){let $=(Z)=>{let J=this.registeredArguments.length,X=Z.slice(0,J);if(this._storeOptionsAsProperties)X[J]=this;else X[J]=this.opts();return X.push(this),W.apply(this,X)};return this._actionHandler=$,this}createOption(W,$){return new I9(W,$)}_callParseArg(W,$,Z,J){try{return W.parseArg($,Z)}catch(X){if(X.code==="commander.invalidArgument"){let Y=`${J} ${X.message}`;this.error(Y,{exitCode:X.exitCode,code:X.code})}throw X}}_registerOption(W){let $=W.short&&this._findOption(W.short)||W.long&&this._findOption(W.long);if($){let Z=W.long&&this._findOption(W.long)?W.long:W.short;throw Error(`Cannot add option '${W.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Z}'
17
+ - already used by option '${$.flags}'`)}this._initOptionGroup(W),this.options.push(W)}_registerCommand(W){let $=(J)=>{return[J.name()].concat(J.aliases())},Z=$(W).find((J)=>this._findCommand(J));if(Z){let J=$(this._findCommand(Z)).join("|"),X=$(W).join("|");throw Error(`cannot add command '${X}' as already have command '${J}'`)}this._initCommandGroup(W),this.commands.push(W)}addOption(W){this._registerOption(W);let $=W.name(),Z=W.attributeName();if(W.negate){let X=W.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(Z,W.defaultValue===void 0?!0:W.defaultValue,"default")}else if(W.defaultValue!==void 0)this.setOptionValueWithSource(Z,W.defaultValue,"default");let J=(X,Y,L)=>{if(X==null&&W.presetArg!==void 0)X=W.presetArg;let G=this.getOptionValue(Z);if(X!==null&&W.parseArg)X=this._callParseArg(W,X,G,Y);else if(X!==null&&W.variadic)X=W._collectValue(X,G);if(X==null)if(W.negate)X=!1;else if(W.isBoolean()||W.optional)X=!0;else X="";this.setOptionValueWithSource(Z,X,L)};if(this.on("option:"+$,(X)=>{let Y=`error: option '${W.flags}' argument '${X}' is invalid.`;J(X,Y,"cli")}),W.envVar)this.on("optionEnv:"+$,(X)=>{let Y=`error: option '${W.flags}' value '${X}' from env '${W.envVar}' is invalid.`;J(X,Y,"env")});return this}_optionEx(W,$,Z,J,X){if(typeof $==="object"&&$ instanceof I9)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption($,Z);if(Y.makeOptionMandatory(!!W.mandatory),typeof J==="function")Y.default(X).argParser(J);else if(J instanceof RegExp){let L=J;J=(G,U)=>{let D=L.exec(G);return D?D[0]:U},Y.default(X).argParser(J)}else Y.default(J);return this.addOption(Y)}option(W,$,Z,J){return this._optionEx({},W,$,Z,J)}requiredOption(W,$,Z,J){return this._optionEx({mandatory:!0},W,$,Z,J)}combineFlagAndOptionalValue(W=!0){return this._combineFlagAndOptionalValue=!!W,this}allowUnknownOption(W=!0){return this._allowUnknownOption=!!W,this}allowExcessArguments(W=!0){return this._allowExcessArguments=!!W,this}enablePositionalOptions(W=!0){return this._enablePositionalOptions=!!W,this}passThroughOptions(W=!0){return this._passThroughOptions=!!W,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(W=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!W,this}getOptionValue(W){if(this._storeOptionsAsProperties)return this[W];return this._optionValues[W]}setOptionValue(W,$){return this.setOptionValueWithSource(W,$,void 0)}setOptionValueWithSource(W,$,Z){if(this._storeOptionsAsProperties)this[W]=$;else this._optionValues[W]=$;return this._optionValueSources[W]=Z,this}getOptionValueSource(W){return this._optionValueSources[W]}getOptionValueSourceWithGlobals(W){let $;return this._getCommandAndAncestors().forEach((Z)=>{if(Z.getOptionValueSource(W)!==void 0)$=Z.getOptionValueSource(W)}),$}_prepareUserArgs(W,$){if(W!==void 0&&!Array.isArray(W))throw Error("first parameter to parse must be array or undefined");if($=$||{},W===void 0&&$.from===void 0){if(H1.versions?.electron)$.from="electron";let J=H1.execArgv??[];if(J.includes("-e")||J.includes("--eval")||J.includes("-p")||J.includes("--print"))$.from="eval"}if(W===void 0)W=H1.argv;this.rawArgs=W.slice();let Z;switch($.from){case void 0:case"node":this._scriptPath=W[1],Z=W.slice(2);break;case"electron":if(H1.defaultApp)this._scriptPath=W[1],Z=W.slice(2);else Z=W.slice(1);break;case"user":Z=W.slice(0);break;case"eval":Z=W.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Z}parse(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return this._parseCommand([],Z),this}async parseAsync(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return await this._parseCommand([],Z),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(W,$,Z){if(W4.existsSync(W))return;let J=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",X=`'${W}' does not exist
19
19
  - if '${Z}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${J}`;throw Error(X)}_executeSubCommand(W,$){$=$.slice();let Z=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function X(R,P){let w=x0.resolve(R,P);if(eW.existsSync(w))return w;if(J.includes(x0.extname(P)))return;let D=J.find((S)=>eW.existsSync(`${w}${S}`));if(D)return`${w}${D}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=W._executableFile||`${this._name}-${W._name}`,M=this._executableDir||"";if(this._scriptPath){let R;try{R=eW.realpathSync(this._scriptPath)}catch{R=this._scriptPath}M=x0.resolve(x0.dirname(R),M)}if(M){let R=X(M,Y);if(!R&&!W._executableFile&&this._scriptPath){let P=x0.basename(this._scriptPath,x0.extname(this._scriptPath));if(P!==this._name)R=X(M,`${P}-${W._name}`)}Y=R||Y}Z=J.includes(x0.extname(Y));let G;if(H1.platform!=="win32")if(Z)$.unshift(Y),$=y9(H1.execArgv).concat($),G=$6.spawn(H1.argv[0],$,{stdio:"inherit"});else G=$6.spawn(Y,$,{stdio:"inherit"});else this._checkForMissingExecutable(Y,M,W._name),$.unshift(Y),$=y9(H1.execArgv).concat($),G=$6.spawn(H1.execPath,$,{stdio:"inherit"});if(!G.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((P)=>{H1.on(P,()=>{if(G.killed===!1&&G.exitCode===null)G.kill(P)})});let V=this._exitCallback;G.on("close",(R)=>{if(R=R??1,!V)H1.exit(R);else V(new Z6(R,"commander.executeSubCommandAsync","(close)"))}),G.on("error",(R)=>{if(R.code==="ENOENT")this._checkForMissingExecutable(Y,M,W._name);else if(R.code==="EACCES")throw Error(`'${Y}' not executable`);if(!V)H1.exit(1);else{let P=new Z6(1,"commander.executeSubCommandAsync","(error)");P.nestedError=R,V(P)}}),this.runningCommand=G}_dispatchSubcommand(W,$,Z){let J=this._findCommand(W);if(!J)this.help({error:!0});J._prepareForParse();let X;return X=this._chainOrCallSubCommandHook(X,J,"preSubcommand"),X=this._chainOrCall(X,()=>{if(J._executableHandler)this._executeSubCommand(J,$.concat(Z));else return J._parseCommand($,Z)}),X}_dispatchHelpCommand(W){if(!W)this.help();let $=this._findCommand(W);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(W,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((W,$)=>{if(W.required&&this.args[$]==null)this.missingArgument(W.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let W=(Z,J,X)=>{let Y=J;if(J!==null&&Z.parseArg){let M=`error: command-argument value '${J}' is invalid for argument '${Z.name()}'.`;Y=this._callParseArg(Z,J,X,M)}return Y};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((Z,J)=>{let X=Z.defaultValue;if(Z.variadic){if(J<this.args.length){if(X=this.args.slice(J),Z.parseArg)X=X.reduce((Y,M)=>{return W(Z,M,Y)},Z.defaultValue)}else if(X===void 0)X=[]}else if(J<this.args.length){if(X=this.args[J],Z.parseArg)X=W(Z,X,Z.defaultValue)}$[J]=X}),this.processedArgs=$}_chainOrCall(W,$){if(W?.then&&typeof W.then==="function")return W.then(()=>$());return $()}_chainOrCallHooks(W,$){let Z=W,J=[];if(this._getCommandAndAncestors().reverse().filter((X)=>X._lifeCycleHooks[$]!==void 0).forEach((X)=>{X._lifeCycleHooks[$].forEach((Y)=>{J.push({hookedCommand:X,callback:Y})})}),$==="postAction")J.reverse();return J.forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X.callback(X.hookedCommand,this)})}),Z}_chainOrCallSubCommandHook(W,$,Z){let J=W;if(this._lifeCycleHooks[Z]!==void 0)this._lifeCycleHooks[Z].forEach((X)=>{J=this._chainOrCall(J,()=>{return X(this,$)})});return J}_parseCommand(W,$){let Z=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),W=W.concat(Z.operands),$=Z.unknown,this.args=W.concat($),W&&this._findCommand(W[0]))return this._dispatchSubcommand(W[0],W.slice(1),$);if(this._getHelpCommand()&&W[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(W[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,W,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Z.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(Z.unknown.length>0)this.unknownOption(Z.unknown[0])},X=`command:${this.name()}`;if(this._actionHandler){J(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(X,W,$)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent?.listenerCount(X))J(),this._processArguments(),this.parent.emit(X,W,$);else if(W.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",W,$);if(this.listenerCount("command:*"))this.emit("command:*",W,$);else if(this.commands.length)this.unknownCommand();else J(),this._processArguments()}else if(this.commands.length)J(),this.help({error:!0});else J(),this._processArguments()}_findCommand(W){if(!W)return;return this.commands.find(($)=>$._name===W||$._aliases.includes(W))}_findOption(W){return this.options.find(($)=>$.is(W))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((W)=>{W.options.forEach(($)=>{if($.mandatory&&W.getOptionValue($.attributeName())===void 0)W.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let W=this.options.filter((Z)=>{let J=Z.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});W.filter((Z)=>Z.conflictsWith.length>0).forEach((Z)=>{let J=W.find((X)=>Z.conflictsWith.includes(X.attributeName()));if(J)this._conflictingOption(Z,J)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((W)=>{W._checkForConflictingLocalOptions()})}parseOptions(W){let $=[],Z=[],J=$;function X(R){return R.length>1&&R[0]==="-"}let Y=(R)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(R))return!1;return!this._getCommandAndAncestors().some((P)=>P.options.map((w)=>w.short).some((w)=>/^-\d$/.test(w)))},M=null,G=null,V=0;while(V<W.length||G){let R=G??W[V++];if(G=null,R==="--"){if(J===Z)J.push(R);J.push(...W.slice(V));break}if(M&&(!X(R)||Y(R))){this.emit(`option:${M.name()}`,R);continue}if(M=null,X(R)){let P=this._findOption(R);if(P){if(P.required){let w=W[V++];if(w===void 0)this.optionMissingArgument(P);this.emit(`option:${P.name()}`,w)}else if(P.optional){let w=null;if(V<W.length&&(!X(W[V])||Y(W[V])))w=W[V++];this.emit(`option:${P.name()}`,w)}else this.emit(`option:${P.name()}`);M=P.variadic?P:null;continue}}if(R.length>2&&R[0]==="-"&&R[1]!=="-"){let P=this._findOption(`-${R[1]}`);if(P){if(P.required||P.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${P.name()}`,R.slice(2));else this.emit(`option:${P.name()}`),G=`-${R.slice(2)}`;continue}}if(/^--[^=]+=/.test(R)){let P=R.indexOf("="),w=this._findOption(R.slice(0,P));if(w&&(w.required||w.optional)){this.emit(`option:${w.name()}`,R.slice(P+1));continue}}if(J===$&&X(R)&&!(this.commands.length===0&&Y(R)))J=Z;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&Z.length===0){if(this._findCommand(R)){$.push(R),Z.push(...W.slice(V));break}else if(this._getHelpCommand()&&R===this._getHelpCommand().name()){$.push(R,...W.slice(V));break}else if(this._defaultCommandName){Z.push(R,...W.slice(V));break}}if(this._passThroughOptions){J.push(R,...W.slice(V));break}J.push(R)}return{operands:$,unknown:Z}}opts(){if(this._storeOptionsAsProperties){let W={},$=this.options.length;for(let Z=0;Z<$;Z++){let J=this.options[Z].attributeName();W[J]=J===this._versionOptionName?this._version:this[J]}return W}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((W,$)=>Object.assign(W,$.opts()),{})}error(W,$){if(this._outputConfiguration.outputError(`${W}
21
+ - ${J}`;throw Error(X)}_executeSubCommand(W,$){$=$.slice();let Z=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function X(D,P){let w=x0.resolve(D,P);if(W4.existsSync(w))return w;if(J.includes(x0.extname(P)))return;let R=J.find((S)=>W4.existsSync(`${w}${S}`));if(R)return`${w}${R}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=W._executableFile||`${this._name}-${W._name}`,L=this._executableDir||"";if(this._scriptPath){let D;try{D=W4.realpathSync(this._scriptPath)}catch{D=this._scriptPath}L=x0.resolve(x0.dirname(D),L)}if(L){let D=X(L,Y);if(!D&&!W._executableFile&&this._scriptPath){let P=x0.basename(this._scriptPath,x0.extname(this._scriptPath));if(P!==this._name)D=X(L,`${P}-${W._name}`)}Y=D||Y}Z=J.includes(x0.extname(Y));let G;if(H1.platform!=="win32")if(Z)$.unshift(Y),$=g9(H1.execArgv).concat($),G=Z6.spawn(H1.argv[0],$,{stdio:"inherit"});else G=Z6.spawn(Y,$,{stdio:"inherit"});else this._checkForMissingExecutable(Y,L,W._name),$.unshift(Y),$=g9(H1.execArgv).concat($),G=Z6.spawn(H1.execPath,$,{stdio:"inherit"});if(!G.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((P)=>{H1.on(P,()=>{if(G.killed===!1&&G.exitCode===null)G.kill(P)})});let U=this._exitCallback;G.on("close",(D)=>{if(D=D??1,!U)H1.exit(D);else U(new J6(D,"commander.executeSubCommandAsync","(close)"))}),G.on("error",(D)=>{if(D.code==="ENOENT")this._checkForMissingExecutable(Y,L,W._name);else if(D.code==="EACCES")throw Error(`'${Y}' not executable`);if(!U)H1.exit(1);else{let P=new J6(1,"commander.executeSubCommandAsync","(error)");P.nestedError=D,U(P)}}),this.runningCommand=G}_dispatchSubcommand(W,$,Z){let J=this._findCommand(W);if(!J)this.help({error:!0});J._prepareForParse();let X;return X=this._chainOrCallSubCommandHook(X,J,"preSubcommand"),X=this._chainOrCall(X,()=>{if(J._executableHandler)this._executeSubCommand(J,$.concat(Z));else return J._parseCommand($,Z)}),X}_dispatchHelpCommand(W){if(!W)this.help();let $=this._findCommand(W);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(W,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((W,$)=>{if(W.required&&this.args[$]==null)this.missingArgument(W.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let W=(Z,J,X)=>{let Y=J;if(J!==null&&Z.parseArg){let L=`error: command-argument value '${J}' is invalid for argument '${Z.name()}'.`;Y=this._callParseArg(Z,J,X,L)}return Y};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((Z,J)=>{let X=Z.defaultValue;if(Z.variadic){if(J<this.args.length){if(X=this.args.slice(J),Z.parseArg)X=X.reduce((Y,L)=>{return W(Z,L,Y)},Z.defaultValue)}else if(X===void 0)X=[]}else if(J<this.args.length){if(X=this.args[J],Z.parseArg)X=W(Z,X,Z.defaultValue)}$[J]=X}),this.processedArgs=$}_chainOrCall(W,$){if(W?.then&&typeof W.then==="function")return W.then(()=>$());return $()}_chainOrCallHooks(W,$){let Z=W,J=[];if(this._getCommandAndAncestors().reverse().filter((X)=>X._lifeCycleHooks[$]!==void 0).forEach((X)=>{X._lifeCycleHooks[$].forEach((Y)=>{J.push({hookedCommand:X,callback:Y})})}),$==="postAction")J.reverse();return J.forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X.callback(X.hookedCommand,this)})}),Z}_chainOrCallSubCommandHook(W,$,Z){let J=W;if(this._lifeCycleHooks[Z]!==void 0)this._lifeCycleHooks[Z].forEach((X)=>{J=this._chainOrCall(J,()=>{return X(this,$)})});return J}_parseCommand(W,$){let Z=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),W=W.concat(Z.operands),$=Z.unknown,this.args=W.concat($),W&&this._findCommand(W[0]))return this._dispatchSubcommand(W[0],W.slice(1),$);if(this._getHelpCommand()&&W[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(W[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,W,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Z.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(Z.unknown.length>0)this.unknownOption(Z.unknown[0])},X=`command:${this.name()}`;if(this._actionHandler){J(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(X,W,$)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent?.listenerCount(X))J(),this._processArguments(),this.parent.emit(X,W,$);else if(W.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",W,$);if(this.listenerCount("command:*"))this.emit("command:*",W,$);else if(this.commands.length)this.unknownCommand();else J(),this._processArguments()}else if(this.commands.length)J(),this.help({error:!0});else J(),this._processArguments()}_findCommand(W){if(!W)return;return this.commands.find(($)=>$._name===W||$._aliases.includes(W))}_findOption(W){return this.options.find(($)=>$.is(W))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((W)=>{W.options.forEach(($)=>{if($.mandatory&&W.getOptionValue($.attributeName())===void 0)W.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let W=this.options.filter((Z)=>{let J=Z.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});W.filter((Z)=>Z.conflictsWith.length>0).forEach((Z)=>{let J=W.find((X)=>Z.conflictsWith.includes(X.attributeName()));if(J)this._conflictingOption(Z,J)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((W)=>{W._checkForConflictingLocalOptions()})}parseOptions(W){let $=[],Z=[],J=$;function X(D){return D.length>1&&D[0]==="-"}let Y=(D)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(D))return!1;return!this._getCommandAndAncestors().some((P)=>P.options.map((w)=>w.short).some((w)=>/^-\d$/.test(w)))},L=null,G=null,U=0;while(U<W.length||G){let D=G??W[U++];if(G=null,D==="--"){if(J===Z)J.push(D);J.push(...W.slice(U));break}if(L&&(!X(D)||Y(D))){this.emit(`option:${L.name()}`,D);continue}if(L=null,X(D)){let P=this._findOption(D);if(P){if(P.required){let w=W[U++];if(w===void 0)this.optionMissingArgument(P);this.emit(`option:${P.name()}`,w)}else if(P.optional){let w=null;if(U<W.length&&(!X(W[U])||Y(W[U])))w=W[U++];this.emit(`option:${P.name()}`,w)}else this.emit(`option:${P.name()}`);L=P.variadic?P:null;continue}}if(D.length>2&&D[0]==="-"&&D[1]!=="-"){let P=this._findOption(`-${D[1]}`);if(P){if(P.required||P.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${P.name()}`,D.slice(2));else this.emit(`option:${P.name()}`),G=`-${D.slice(2)}`;continue}}if(/^--[^=]+=/.test(D)){let P=D.indexOf("="),w=this._findOption(D.slice(0,P));if(w&&(w.required||w.optional)){this.emit(`option:${w.name()}`,D.slice(P+1));continue}}if(J===$&&X(D)&&!(this.commands.length===0&&Y(D)))J=Z;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&Z.length===0){if(this._findCommand(D)){$.push(D),Z.push(...W.slice(U));break}else if(this._getHelpCommand()&&D===this._getHelpCommand().name()){$.push(D,...W.slice(U));break}else if(this._defaultCommandName){Z.push(D,...W.slice(U));break}}if(this._passThroughOptions){J.push(D,...W.slice(U));break}J.push(D)}return{operands:$,unknown:Z}}opts(){if(this._storeOptionsAsProperties){let W={},$=this.options.length;for(let Z=0;Z<$;Z++){let J=this.options[Z].attributeName();W[J]=J===this._versionOptionName?this._version:this[J]}return W}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((W,$)=>Object.assign(W,$.opts()),{})}error(W,$){if(this._outputConfiguration.outputError(`${W}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0});let Z=$||{},J=Z.exitCode||1,X=Z.code||"commander.error";this._exit(J,X,W)}_parseOptionsEnv(){this.options.forEach((W)=>{if(W.envVar&&W.envVar in H1.env){let $=W.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(W.required||W.optional)this.emit(`optionEnv:${W.name()}`,H1.env[W.envVar]);else this.emit(`optionEnv:${W.name()}`)}})}_parseOptionsImplied(){let W=new G2(this.options),$=(Z)=>{return this.getOptionValue(Z)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Z))};this.options.filter((Z)=>Z.implied!==void 0&&$(Z.attributeName())&&W.valueFromOption(this.getOptionValue(Z.attributeName()),Z)).forEach((Z)=>{Object.keys(Z.implied).filter((J)=>!$(J)).forEach((J)=>{this.setOptionValueWithSource(J,Z.implied[J],"implied")})})}missingArgument(W){let $=`error: missing required argument '${W}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(W){let $=`error: option '${W.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(W){let $=`error: required option '${W.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(W,$){let Z=(Y)=>{let M=Y.attributeName(),G=this.getOptionValue(M),V=this.options.find((P)=>P.negate&&M===P.attributeName()),R=this.options.find((P)=>!P.negate&&M===P.attributeName());if(V&&(V.presetArg===void 0&&G===!1||V.presetArg!==void 0&&G===V.presetArg))return V;return R||Y},J=(Y)=>{let M=Z(Y),G=M.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${M.envVar}'`;return`option '${M.flags}'`},X=`error: ${J(W)} cannot be used with ${J($)}`;this.error(X,{code:"commander.conflictingOption"})}unknownOption(W){if(this._allowUnknownOption)return;let $="";if(W.startsWith("--")&&this._showSuggestionAfterError){let J=[],X=this;do{let Y=X.createHelp().visibleOptions(X).filter((M)=>M.long).map((M)=>M.long);J=J.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);$=I9(W,J)}let Z=`error: unknown option '${W}'${$}`;this.error(Z,{code:"commander.unknownOption"})}_excessArguments(W){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,Z=$===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${Z} but got ${W.length}.`;this.error(X,{code:"commander.excessArguments"})}unknownCommand(){let W=this.args[0],$="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((X)=>{if(J.push(X.name()),X.alias())J.push(X.alias())}),$=I9(W,J)}let Z=`error: unknown command '${W}'${$}`;this.error(Z,{code:"commander.unknownCommand"})}version(W,$,Z){if(W===void 0)return this._version;this._version=W,$=$||"-V, --version",Z=Z||"output the version number";let J=this.createOption($,Z);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${W}
25
- `),this._exit(0,"commander.version",W)}),this}description(W,$){if(W===void 0&&$===void 0)return this._description;if(this._description=W,$)this._argsDescription=$;return this}summary(W){if(W===void 0)return this._summary;return this._summary=W,this}alias(W){if(W===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(W===$._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand(W);if(Z){let J=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${W}' to command '${this.name()}' as already have command '${J}'`)}return $._aliases.push(W),this}aliases(W){if(W===void 0)return this._aliases;return W.forEach(($)=>this.alias($)),this}usage(W){if(W===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((Z)=>{return Y2(Z)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=W,this}name(W){if(W===void 0)return this._name;return this._name=W,this}helpGroup(W){if(W===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=W,this}commandsGroup(W){if(W===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=W,this}optionsGroup(W){if(W===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=W,this}_initOptionGroup(W){if(this._defaultOptionGroup&&!W.helpGroupHeading)W.helpGroup(this._defaultOptionGroup)}_initCommandGroup(W){if(this._defaultCommandGroup&&!W.helpGroup())W.helpGroup(this._defaultCommandGroup)}nameFromFilename(W){return this._name=x0.basename(W,x0.extname(W)),this}executableDir(W){if(W===void 0)return this._executableDir;return this._executableDir=W,this}helpInformation(W){let $=this.createHelp(),Z=this._getOutputContext(W);$.prepareContext({error:Z.error,helpWidth:Z.helpWidth,outputHasColors:Z.hasColors});let J=$.formatHelp(this,$);if(Z.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(W){W=W||{};let $=!!W.error,Z,J,X;if($)Z=(M)=>this._outputConfiguration.writeErr(M),J=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else Z=(M)=>this._outputConfiguration.writeOut(M),J=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(M)=>{if(!J)M=this._outputConfiguration.stripColor(M);return Z(M)},hasColors:J,helpWidth:X}}outputHelp(W){let $;if(typeof W==="function")$=W,W=void 0;let Z=this._getOutputContext(W),J={error:Z.error,write:Z.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let X=this.helpInformation({error:Z.error});if($){if(X=$(X),typeof X!=="string"&&!Buffer.isBuffer(X))throw Error("outputHelp callback must return a string or a Buffer")}if(Z.write(X),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((Y)=>Y.emit("afterAllHelp",J))}helpOption(W,$){if(typeof W==="boolean"){if(W){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(W??"-h, --help",$??"display help for command"),W||$)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(W){return this._helpOption=W,this._initOptionGroup(W),this}help(W){this.outputHelp(W);let $=Number(H1.exitCode??0);if($===0&&W&&typeof W!=="function"&&W.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(W,$){let Z=["beforeAll","before","after","afterAll"];if(!Z.includes(W))throw Error(`Unexpected value for position to addHelpText.
24
+ `),this.outputHelp({error:!0});let Z=$||{},J=Z.exitCode||1,X=Z.code||"commander.error";this._exit(J,X,W)}_parseOptionsEnv(){this.options.forEach((W)=>{if(W.envVar&&W.envVar in H1.env){let $=W.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(W.required||W.optional)this.emit(`optionEnv:${W.name()}`,H1.env[W.envVar]);else this.emit(`optionEnv:${W.name()}`)}})}_parseOptionsImplied(){let W=new M2(this.options),$=(Z)=>{return this.getOptionValue(Z)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Z))};this.options.filter((Z)=>Z.implied!==void 0&&$(Z.attributeName())&&W.valueFromOption(this.getOptionValue(Z.attributeName()),Z)).forEach((Z)=>{Object.keys(Z.implied).filter((J)=>!$(J)).forEach((J)=>{this.setOptionValueWithSource(J,Z.implied[J],"implied")})})}missingArgument(W){let $=`error: missing required argument '${W}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(W){let $=`error: option '${W.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(W){let $=`error: required option '${W.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(W,$){let Z=(Y)=>{let L=Y.attributeName(),G=this.getOptionValue(L),U=this.options.find((P)=>P.negate&&L===P.attributeName()),D=this.options.find((P)=>!P.negate&&L===P.attributeName());if(U&&(U.presetArg===void 0&&G===!1||U.presetArg!==void 0&&G===U.presetArg))return U;return D||Y},J=(Y)=>{let L=Z(Y),G=L.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${L.envVar}'`;return`option '${L.flags}'`},X=`error: ${J(W)} cannot be used with ${J($)}`;this.error(X,{code:"commander.conflictingOption"})}unknownOption(W){if(this._allowUnknownOption)return;let $="";if(W.startsWith("--")&&this._showSuggestionAfterError){let J=[],X=this;do{let Y=X.createHelp().visibleOptions(X).filter((L)=>L.long).map((L)=>L.long);J=J.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);$=y9(W,J)}let Z=`error: unknown option '${W}'${$}`;this.error(Z,{code:"commander.unknownOption"})}_excessArguments(W){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,Z=$===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${Z} but got ${W.length}.`;this.error(X,{code:"commander.excessArguments"})}unknownCommand(){let W=this.args[0],$="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((X)=>{if(J.push(X.name()),X.alias())J.push(X.alias())}),$=y9(W,J)}let Z=`error: unknown command '${W}'${$}`;this.error(Z,{code:"commander.unknownCommand"})}version(W,$,Z){if(W===void 0)return this._version;this._version=W,$=$||"-V, --version",Z=Z||"output the version number";let J=this.createOption($,Z);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${W}
25
+ `),this._exit(0,"commander.version",W)}),this}description(W,$){if(W===void 0&&$===void 0)return this._description;if(this._description=W,$)this._argsDescription=$;return this}summary(W){if(W===void 0)return this._summary;return this._summary=W,this}alias(W){if(W===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(W===$._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand(W);if(Z){let J=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${W}' to command '${this.name()}' as already have command '${J}'`)}return $._aliases.push(W),this}aliases(W){if(W===void 0)return this._aliases;return W.forEach(($)=>this.alias($)),this}usage(W){if(W===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((Z)=>{return G2(Z)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=W,this}name(W){if(W===void 0)return this._name;return this._name=W,this}helpGroup(W){if(W===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=W,this}commandsGroup(W){if(W===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=W,this}optionsGroup(W){if(W===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=W,this}_initOptionGroup(W){if(this._defaultOptionGroup&&!W.helpGroupHeading)W.helpGroup(this._defaultOptionGroup)}_initCommandGroup(W){if(this._defaultCommandGroup&&!W.helpGroup())W.helpGroup(this._defaultCommandGroup)}nameFromFilename(W){return this._name=x0.basename(W,x0.extname(W)),this}executableDir(W){if(W===void 0)return this._executableDir;return this._executableDir=W,this}helpInformation(W){let $=this.createHelp(),Z=this._getOutputContext(W);$.prepareContext({error:Z.error,helpWidth:Z.helpWidth,outputHasColors:Z.hasColors});let J=$.formatHelp(this,$);if(Z.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(W){W=W||{};let $=!!W.error,Z,J,X;if($)Z=(L)=>this._outputConfiguration.writeErr(L),J=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else Z=(L)=>this._outputConfiguration.writeOut(L),J=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(L)=>{if(!J)L=this._outputConfiguration.stripColor(L);return Z(L)},hasColors:J,helpWidth:X}}outputHelp(W){let $;if(typeof W==="function")$=W,W=void 0;let Z=this._getOutputContext(W),J={error:Z.error,write:Z.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let X=this.helpInformation({error:Z.error});if($){if(X=$(X),typeof X!=="string"&&!Buffer.isBuffer(X))throw Error("outputHelp callback must return a string or a Buffer")}if(Z.write(X),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((Y)=>Y.emit("afterAllHelp",J))}helpOption(W,$){if(typeof W==="boolean"){if(W){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(W??"-h, --help",$??"display help for command"),W||$)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(W){return this._helpOption=W,this._initOptionGroup(W),this}help(W){this.outputHelp(W);let $=Number(H1.exitCode??0);if($===0&&W&&typeof W!=="function"&&W.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(W,$){let Z=["beforeAll","before","after","afterAll"];if(!Z.includes(W))throw Error(`Unexpected value for position to addHelpText.
26
26
  Expecting one of '${Z.join("', '")}'`);let J=`${W}Help`;return this.on(J,(X)=>{let Y;if(typeof $==="function")Y=$({error:X.error,command:X.command});else Y=$;if(Y)X.write(`${Y}
27
- `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function y9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let Z,J="127.0.0.1",X="9229",Y;if((Y=$.match(/^(--inspect(-brk)?)$/))!==null)Z=Y[1];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else J=Y[3];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=Y[1],J=Y[3],X=Y[4];if(Z&&X!=="0")return`${Z}=${J}:${parseInt(X)+1}`;return $})}function J6(){if(H1.env.NO_COLOR||H1.env.FORCE_COLOR==="0"||H1.env.FORCE_COLOR==="false")return!1;if(H1.env.FORCE_COLOR||H1.env.CLICOLOR_FORCE!==void 0)return!0;return}M2.Command=X6;M2.useColor=J6});var l9=L8((V2)=>{var{Argument:m9}=oW(),{Command:Y6}=g9(),{CommanderError:z2,InvalidArgumentError:c9}=KW(),{Help:U2}=e4(),{Option:u9}=W6();V2.program=new Y6;V2.createCommand=(W)=>new Y6(W);V2.createOption=(W,$)=>new u9(W,$);V2.createArgument=(W,$)=>new m9(W,$);V2.Command=Y6;V2.Option=u9;V2.Argument=m9;V2.Help=U2;V2.CommanderError=z2;V2.InvalidArgumentError=c9;V2.InvalidOptionArgumentError=c9});var p9=x$(l9(),1),{program:mJ,createCommand:cJ,createArgument:uJ,createOption:lJ,CommanderError:pJ,InvalidArgumentError:iJ,InvalidOptionArgumentError:tJ,Command:i9,Argument:aJ,Option:dJ,Help:sJ}=p9.default;import i4 from"path";import{fileURLToPath as TJ}from"url";import{createRequire as fJ}from"module";import{execSync as jJ,spawn as AJ}from"child_process";function n1(W){return typeof W>"u"||W===void 0}function a(W){return typeof W==="string"}function d0(W){return typeof W==="number"}function K8(W){return typeof W==="boolean"}function E8(W){return W===null}function t9(W){return W instanceof Date}function h8(W){return typeof W==="bigint"}function R1(W){return typeof W==="function"}function Q1(W){return typeof W==="object"&&W!==null}function a9(W){return W[W.length-1]}function k(W){return Object.freeze(W)}function zW(W){if(y1(W))return W;else return[W]}function y1(W){return Array.isArray(W)}function N1(W){return W}function d9(W){return W instanceof Error?W.message:String(W)}var $1=k({is(W){return W.kind==="AlterTableNode"},create(W){return k({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return k({...W,...$})},cloneWithColumnAlteration(W,$){return k({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var l=k({is(W){return W.kind==="IdentifierNode"},create(W){return k({kind:"IdentifierNode",name:W})}});var H0=k({is(W){return W.kind==="CreateIndexNode"},create(W){return k({kind:"CreateIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});var W4=k({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return k({kind:"CreateSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var s9=["preserve rows","delete rows","drop"],C1=k({is(W){return W.kind==="CreateTableNode"},create(W){return k({kind:"CreateTableNode",table:W,columns:k([])})},cloneWithColumn(W,$){return k({...W,columns:k([...W.columns,$])})},cloneWithConstraint(W,$){return k({...W,constraints:W.constraints?k([...W.constraints,$]):k([$])})},cloneWithIndex(W,$){return k({...W,indexes:W.indexes?k([...W.indexes,$]):k([$])})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWith(W,$){return k({...W,...$})}});var g1=k({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return k({kind:"SchemableIdentifierNode",identifier:l.create(W)})},createWithSchema(W,$){return k({kind:"SchemableIdentifierNode",schema:l.create(W),identifier:l.create($)})}});var s0=k({is(W){return W.kind==="DropIndexNode"},create(W,$){return k({kind:"DropIndexNode",name:g1.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var UW=k({is(W){return W.kind==="DropSchemaNode"},create(W,$){return k({kind:"DropSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var T8=k({is(W){return W.kind==="DropTableNode"},create(W,$){return k({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return k({...W,...$})}});var q1=k({is(W){return W.kind==="AliasNode"},create(W,$){return k({kind:"AliasNode",node:W,alias:$})}});var u1=k({is(W){return W.kind==="TableNode"},create(W){return k({kind:"TableNode",table:g1.create(W)})},createWithSchema(W,$){return k({kind:"TableNode",table:g1.createWithSchema(W,$)})}});function G1(W){return Q1(W)&&R1(W.toOperationNode)}function $4(W){return Q1(W)&&"expressionType"in W&&G1(W)}function n9(W){return Q1(W)&&"expression"in W&&a(W.alias)&&G1(W)}var _0=k({is(W){return W.kind==="SelectModifierNode"},create(W,$){return k({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return k({kind:"SelectModifierNode",rawModifier:W})}});var l1=k({is(W){return W.kind==="AndNode"},create(W,$){return k({kind:"AndNode",left:W,right:$})}});var k0=k({is(W){return W.kind==="OrNode"},create(W,$){return k({kind:"OrNode",left:W,right:$})}});var Z4=k({is(W){return W.kind==="OnNode"},create(W){return k({kind:"OnNode",on:W})},cloneWithOperation(W,$,Z){return k({...W,on:$==="And"?l1.create(W.on,Z):k0.create(W.on,Z)})}});var G0=k({is(W){return W.kind==="JoinNode"},create(W,$){return k({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,Z){return k({kind:"JoinNode",joinType:W,table:$,on:Z4.create(Z)})},cloneWithOn(W,$){return k({...W,on:W.on?Z4.cloneWithOperation(W.on,"And",$):Z4.create($)})}});var n0=k({is(W){return W.kind==="BinaryOperationNode"},create(W,$,Z){return k({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:Z})}});var r9=k({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),a3=Object.keys(r9),o9=k({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),d3=Object.keys(o9),e9=k({"->":!0,"->>":!0}),T2=Object.keys(e9),W5=k({...r9,...o9,"||":!0}),f2=Object.keys(W5),$5=k({exists:!0,"not exists":!0}),s3=Object.keys($5),Z5=k({...$5,"-":!0,not:!0}),j2=Object.keys(Z5),n3=[...f2,...T2,...j2,"between","between symmetric"],r1=k({is(W){return W.kind==="OperatorNode"},create(W){return k({kind:"OperatorNode",operator:W})}});function J5(W){return a(W)&&W5[W]}function X5(W){return a(W)&&e9[W]}function Y5(W){return a(W)&&Z5[W]}var e=k({is(W){return W.kind==="ColumnNode"},create(W){return k({kind:"ColumnNode",column:l.create(W)})}});var f8=k({is(W){return W.kind==="SelectAllNode"},create(){return k({kind:"SelectAllNode"})}});var j8=k({is(W){return W.kind==="ReferenceNode"},create(W,$){return k({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return k({kind:"ReferenceNode",table:W,column:f8.create()})}});class H6{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return k6(this.#W)}}function J4(W){return Q1(W)&&G1(W)&&a(W.dynamicReference)}var M0=k({is(W){return W.kind==="OrderByItemNode"},create(W,$){return k({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return k({...W,...$})}});var X1=k({is(W){return W.kind==="RawNode"},create(W,$){return k({kind:"RawNode",sqlFragments:k(W),parameters:k($)})},createWithSql(W){return X1.create([W],[])},createWithChild(W){return X1.create(["",""],[W])},createWithChildren(W){return X1.create(Array(W.length+1).fill(""),W)}});var H5=k({is(W){return W.kind==="CollateNode"},create(W){return k({kind:"CollateNode",collation:l.create(W)})}});class r0{#W;constructor(W){this.#W=k(W)}desc(){return new r0({node:M0.cloneWith(this.#W.node,{direction:X1.createWithSql("desc")})})}asc(){return new r0({node:M0.cloneWith(this.#W.node,{direction:X1.createWithSql("asc")})})}nullsLast(){return new r0({node:M0.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new r0({node:M0.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new r0({node:M0.cloneWith(this.#W.node,{collation:H5.create(W)})})}toOperationNode(){return this.#W.node}}var k5=new Set;function A8(W){if(k5.has(W))return;k5.add(W),console.log(W)}function M6(W){return W==="asc"||W==="desc"}function o1(W){if(W.length===2)return[G6(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return A8("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((Z)=>G6(Z));return[G6($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function G6(W,$){let Z=A2(W);if(M0.is(Z)){if($)throw Error("Cannot specify direction twice!");return Z}return G5(Z,$)}function A2(W){if(B0(W))return O1(W);if(J4(W))return W.toOperationNode();let[$,Z]=W.split(" ");if(Z)return A8("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),G5(p1($),Z);return p1(W)}function G5(W,$){if(typeof $==="string"){if(!M6($))throw Error(`Invalid order by direction: ${$}`);return M0.create(W,X1.createWithSql($))}if($4($))return A8("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),M0.create(W,$.toOperationNode());let Z=M0.create(W);if(!$)return Z;return $(new r0({node:Z})).toOperationNode()}var N8=k({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return k({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return k({...W,traversal:$})}});var X4=k({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return k({kind:"JSONOperatorChainNode",operator:W,values:k([])})},cloneWithValue(W,$){return k({...W,values:k([...W.values,$])})}});var o0=k({is(W){return W.kind==="JSONPathNode"},create(W){return k({kind:"JSONPathNode",inOperator:W,pathLegs:k([])})},cloneWithLeg(W,$){return k({...W,pathLegs:k([...W.pathLegs,$])})}});function k6(W){if(a(W))return p1(W);return W.toOperationNode()}function b0(W){if(y1(W))return W.map(($)=>T1($));else return[T1(W)]}function T1(W){if(B0(W))return O1(W);return k6(W)}function M5(W,$){if(X5($))return N8.create(p1(W),X4.create(r1.create($)));if($==="->$"||$==="->>$")return N8.create(p1(W),o0.create(r1.create($.slice(0,-1))));throw Error(`Invalid JSON operator: ${$}`)}function p1(W){if(!W.includes("."))return j8.create(e.create(W));let Z=W.split(".").map(K6);if(Z.length===3)return N2(Z);if(Z.length===2)return C2(Z);throw Error(`invalid column reference ${W}`)}function L5(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(K6);return q1.create(p1(Z),l.create(J))}else return p1(W)}function L6(W){return e.create(W)}function C8(W){if(W.includes(" ")){let[Z,J]=W.split(" ").map(K6);if(!M6(J))throw Error(`invalid order direction "${J}" next to "${Z}"`);return o1([Z,J])[0]}else return L6(W)}function N2(W){let[$,Z,J]=W;return j8.create(e.create(J),u1.createWithSchema($,Z))}function C2(W){let[$,Z]=W;return j8.create(e.create(Z),u1.create($))}function K6(W){return W.trim()}var Y4=k({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return k({kind:"PrimitiveValueListNode",values:k([...W])})}});var e0=k({is(W){return W.kind==="ValueListNode"},create(W){return k({kind:"ValueListNode",values:k(W)})}});var D1=k({is(W){return W.kind==="ValueNode"},create(W){return k({kind:"ValueNode",value:W})},createImmediate(W){return k({kind:"ValueNode",value:W,immediate:!0})}});function K5(W){if(y1(W))return q2(W);return M1(W)}function M1(W){if(B0(W))return O1(W);return D1.create(W)}function H4(W){return d0(W)||K8(W)||E8(W)}function VW(W){if(!H4(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return D1.createImmediate(W)}function q2(W){if(W.some(B0))return e0.create(W.map(($)=>M1($)));return Y4.create(W)}var e1=k({is(W){return W.kind==="ParensNode"},create(W){return k({kind:"ParensNode",node:W})}});function K1(W){if(W.length===3)return k4(W[0],W[1],W[2]);else if(W.length===1)return M1(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function k4(W,$,Z){if(O2($)&&U5(Z))return n0.create(T1(W),z6($),D1.createImmediate(Z));return n0.create(T1(W),z6($),K5(Z))}function E1(W,$,Z){return n0.create(T1(W),z6($),T1(Z))}function U6(W,$){return q8(Object.entries(W).filter(([,Z])=>!n1(Z)).map(([Z,J])=>k4(Z,U5(J)?"is":"=",J)),$)}function q8(W,$,Z=!0){let J=$==="and"?l1.create:k0.create;if(W.length===0)return n0.create(D1.createImmediate(1),r1.create("="),D1.createImmediate($==="and"?1:0));let X=z5(W[0]);for(let Y=1;Y<W.length;++Y)X=J(X,z5(W[Y]));if(W.length>1&&Z)return e1.create(X);return X}function O2(W){return W==="is"||W==="is not"}function U5(W){return E8(W)||K8(W)}function z6(W){if(J5(W))return r1.create(W);if(G1(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function z5(W){return G1(W)?W.toOperationNode():W}var I0=k({is(W){return W.kind==="OrderByNode"},create(W){return k({kind:"OrderByNode",items:k([...W])})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var V6=k({is(W){return W.kind==="PartitionByNode"},create(W){return k({kind:"PartitionByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var PW=k({is(W){return W.kind==="OverNode"},create(){return k({kind:"OverNode"})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithPartitionByItems(W,$){return k({...W,partitionBy:W.partitionBy?V6.cloneWithItems(W.partitionBy,$):V6.create($)})}});var z8=k({is(W){return W.kind==="FromNode"},create(W){return k({kind:"FromNode",froms:k(W)})},cloneWithFroms(W,$){return k({...W,froms:k([...W.froms,...$])})}});var P6=k({is(W){return W.kind==="GroupByNode"},create(W){return k({kind:"GroupByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var F6=k({is(W){return W.kind==="HavingNode"},create(W){return k({kind:"HavingNode",having:W})},cloneWithOperation(W,$,Z){return k({...W,having:$==="And"?l1.create(W.having,Z):k0.create(W.having,Z)})}});var S1=k({is(W){return W.kind==="InsertQueryNode"},create(W,$,Z){return k({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:Z})},createWithoutInto(){return k({kind:"InsertQueryNode"})},cloneWith(W,$){return k({...W,...$})}});var G4=k({is(W){return W.kind==="ListNode"},create(W){return k({kind:"ListNode",items:k(W)})}});var v0=k({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return k({kind:"UpdateQueryNode",table:W.length===1?W[0]:G4.create(W),...$&&{with:$}})},createWithoutTable(){return k({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return k({...W,from:W.from?z8.cloneWithFroms(W.from,$):z8.create($)})},cloneWithUpdates(W,$){return k({...W,updates:W.updates?k([...W.updates,...$]):$})},cloneWithLimit(W,$){return k({...W,limit:$})}});var FW=k({is(W){return W.kind==="UsingNode"},create(W){return k({kind:"UsingNode",tables:k(W)})},cloneWithTables(W,$){return k({...W,tables:k([...W.tables,...$])})}});var W8=k({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return k({kind:"DeleteQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithUsing(W,$){return k({...W,using:W.using!==void 0?FW.cloneWithTables(W.using,$):FW.create($)})}});var b1=k({is(W){return W.kind==="WhereNode"},create(W){return k({kind:"WhereNode",where:W})},cloneWithOperation(W,$,Z){return k({...W,where:$==="And"?l1.create(W.where,Z):k0.create(W.where,Z)})}});var R6=k({is(W){return W.kind==="ReturningNode"},create(W){return k({kind:"ReturningNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var V5=k({is(W){return W.kind==="ExplainNode"},create(W,$){return k({kind:"ExplainNode",format:W,options:$})}});var i1=k({is(W){return W.kind==="WhenNode"},create(W){return k({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return k({...W,result:$})}});var W0=k({is(W){return W.kind==="MergeQueryNode"},create(W,$){return k({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return k({...W,using:$})},cloneWithWhen(W,$){return k({...W,whens:W.whens?k([...W.whens,$]):k([$])})},cloneWithThen(W,$){return k({...W,whens:W.whens?k([...W.whens.slice(0,-1),i1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var D6=k({is(W){return W.kind==="OutputNode"},create(W){return k({kind:"OutputNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var y=k({is(W){return k1.is(W)||S1.is(W)||v0.is(W)||W8.is(W)||W0.is(W)},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWithWhere(W,$){return k({...W,where:W.where?b1.cloneWithOperation(W.where,"And",$):b1.create($)})},cloneWithJoin(W,$){return k({...W,joins:W.joins?k([...W.joins,$]):k([$])})},cloneWithReturning(W,$){return k({...W,returning:W.returning?R6.cloneWithSelections(W.returning,$):R6.create($)})},cloneWithoutReturning(W){return k({...W,returning:void 0})},cloneWithoutWhere(W){return k({...W,where:void 0})},cloneWithExplain(W,$,Z){return k({...W,explain:V5.create($,Z?.toOperationNode())})},cloneWithTop(W,$){return k({...W,top:$})},cloneWithOutput(W,$){return k({...W,output:W.output?D6.cloneWithSelections(W.output,$):D6.create($)})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithoutOrderBy(W){return k({...W,orderBy:void 0})}});var k1=k({is(W){return W.kind==="SelectQueryNode"},create(W){return k({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return k({kind:"SelectQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})},cloneWithDistinctOn(W,$){return k({...W,distinctOn:W.distinctOn?k([...W.distinctOn,...$]):k($)})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return k({...W,groupBy:W.groupBy?P6.cloneWithItems(W.groupBy,$):P6.create($)})},cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithOffset(W,$){return k({...W,offset:$})},cloneWithFetch(W,$){return k({...W,fetch:$})},cloneWithHaving(W,$){return k({...W,having:W.having?F6.cloneWithOperation(W.having,"And",$):F6.create($)})},cloneWithSetOperations(W,$){return k({...W,setOperations:W.setOperations?k([...W.setOperations,...$]):k([...$])})},cloneWithoutSelections(W){return k({...W,selections:[]})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithoutOffset(W){return k({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return k({...W,groupBy:void 0})}});class O8{#W;constructor(W){this.#W=k(W)}on(...W){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,K1(W))})}onRef(W,$,Z){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,E1(W,$,Z))})}onTrue(){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,X1.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var P5=k({is(W){return W.kind==="PartitionByItemNode"},create(W){return k({kind:"PartitionByItemNode",partitionBy:W})}});function F5(W){return b0(W).map(P5.create)}class x8{#W;constructor(W){this.#W=k(W)}orderBy(...W){return new x8({overNode:PW.cloneWithOrderByItems(this.#W.overNode,o1(W))})}clearOrderBy(){return new x8({overNode:y.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new x8({overNode:PW.cloneWithPartitionByItems(this.#W.overNode,F5(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var B8=k({is(W){return W.kind==="SelectionNode"},create(W){return k({kind:"SelectionNode",selection:W})},createSelectAll(){return k({kind:"SelectionNode",selection:f8.create()})},createSelectAllFromTable(W){return k({kind:"SelectionNode",selection:j8.createSelectAll(W)})}});function j1(W){if(R1(W))return j1(W(L0()));else if(y1(W))return W.map(($)=>R5($));else return[R5(W)]}function R5(W){if(a(W))return B8.create(L5(W));else if(J4(W))return B8.create(W.toOperationNode());else return B8.create(M4(W))}function x1(W){if(!W)return[B8.createSelectAll()];else if(Array.isArray(W))return W.map(D5);else return[D5(W)]}function D5(W){if(a(W))return B8.createSelectAllFromTable(Z1(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var w5=k({is(W){return W.kind==="ValuesNode"},create(W){return k({kind:"ValuesNode",values:k(W)})}});var Q5=k({is(W){return W.kind==="DefaultInsertValueNode"},create(){return k({kind:"DefaultInsertValueNode"})}});function L4(W){let $=R1(W)?W(L0()):W,Z=y1($)?$:k([$]);return x2(Z)}function x2(W){let $=B2(W);return[k([...$.keys()].map(e.create)),w5.create(W.map((Z)=>b2(Z,$)))]}function B2(W){let $=new Map;for(let Z of W){let J=Object.keys(Z);for(let X of J)if(!$.has(X)&&Z[X]!==void 0)$.set(X,$.size)}return $}function b2(W,$){let Z=Object.keys(W),J=Array.from({length:$.size}),X=!1,Y=Z.length;for(let G of Z){let V=$.get(G);if(n1(V)){Y--;continue}let R=W[G];if(n1(R)||B0(R))X=!0;J[V]=R}if(Y<$.size||X){let G=Q5.create();return e0.create(J.map((V)=>n1(V)?G:M1(V)))}return Y4.create(J)}var w6=k({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return k({kind:"ColumnUpdateNode",column:W,value:$})}});function S5(...W){if(W.length===2)return[w6.create(T1(W[0]),M1(W[1]))];return RW(W[0])}function RW(W){let $=R1(W)?W(L0()):W;return Object.entries($).filter(([Z,J])=>J!==void 0).map(([Z,J])=>{return w6.create(e.create(Z),M1(J))})}var _5=k({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return k({kind:"OnDuplicateKeyNode",updates:W})}});class Q6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class K0 extends Error{node;constructor(W){super("no result");this.node=W}}function E0(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var m1=k({is(W){return W.kind==="OnConflictNode"},create(){return k({kind:"OnConflictNode"})},cloneWith(W,$){return k({...W,...$})},cloneWithIndexWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"And",$):b1.create($)})},cloneWithIndexOrWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"Or",$):b1.create($)})},cloneWithUpdateWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"And",$):b1.create($)})},cloneWithUpdateOrWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"Or",$):b1.create($)})},cloneWithoutIndexWhere(W){return k({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return k({...W,updateWhere:void 0})}});class h0{#W;constructor(W){this.#W=k(W)}column(W){let $=e.create(W);return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,$]):k([$])})})}columns(W){let $=W.map(e.create);return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,...$]):k($)})})}constraint(W){return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{constraint:l.create(W)})})}expression(W){return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new h0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,K1(W))})}whereRef(W,$,Z){return new h0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,E1(W,$,Z))})}clearWhere(){return new h0({...this.#W,onConflictNode:m1.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new v5({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new DW({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{updates:RW(W)})})}$call(W){return W(this)}}class v5{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.onConflictNode}}class DW{#W;constructor(W){this.#W=k(W)}where(...W){return new DW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,K1(W))})}whereRef(W,$,Z){return new DW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,E1(W,$,Z))})}clearWhere(){return new DW({...this.#W,onConflictNode:m1.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var E5=k({is(W){return W.kind==="TopNode"},create(W,$){return k({kind:"TopNode",expression:W,modifiers:$})}});function z0(W,$){if(!d0(W)&&!h8(W))throw Error(`Invalid top expression: ${W}`);if(!n1($)&&!I2($))throw Error(`Invalid top modifiers: ${$}`);return E5.create(W,$)}function I2(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var U8=k({is(W){return W.kind==="OrActionNode"},create(W){return k({kind:"OrActionNode",action:W})}});class L1{#W;constructor(W){this.#W=k(W)}values(W){let[$,Z]=L4(W);return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:$,values:Z})})}columns(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:k(W.map(e.create))})})}expression(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{values:O1(W)})})}defaultValues(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new L1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orIgnore(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orAbort(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("abort")})})}orFail(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("fail")})})}orReplace(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("replace")})})}orRollback(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("rollback")})})}top(W,$){return new L1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}onConflict(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onConflict:W(new h0({onConflictNode:m1.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onDuplicateKey:_5.create(RW(W))})})}returning(W){return new L1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(){return new L1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1())})}output(W){return new L1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new L1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new L1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new L1({...this.#W})}$castTo(){return new L1(this.#W)}$narrowType(){return new L1(this.#W)}$assertType(){return new L1(this.#W)}withPlugin(W){return new L1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new Q6(Z.insertId,Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new L1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class S6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var b8=k({is(W){return W.kind==="LimitNode"},create(W){return k({kind:"LimitNode",limit:W})}});var _1;class K4{#W;constructor(W){this.#W=k(W)}where(...W){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}clearWhere(){return new _1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new _1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(W){return new _1({...this.#W,queryNode:W8.cloneWithUsing(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new _1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}returning(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new _1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new _1({...this.#W,queryNode:W8.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new _1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new _1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new _1({...this.#W,queryNode:W8.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}modifyEnd(W){return new _1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new _1({...this.#W})}$castTo(){return new _1(this.#W)}$narrowType(){return new _1(this.#W)}$assertType(){return new _1(this.#W)}withPlugin(W){return new _1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new S6(Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new _1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}_1=K4;class _6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}var v1;class I8{#W;constructor(W){this.#W=k(W)}where(...W){return new v1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new v1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}clearWhere(){return new v1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new v1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}from(W){return new v1({...this.#W,queryNode:v0.cloneWithFromItems(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new v1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new v1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new v1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new v1({...this.#W,queryNode:v0.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}set(...W){return new v1({...this.#W,queryNode:v0.cloneWithUpdates(this.#W.queryNode,S5(...W))})}returning(W){return new v1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new v1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new v1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new v1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}modifyEnd(W){return new v1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new v1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new v1({...this.#W})}$castTo(){return new v1(this.#W)}$narrowType(){return new v1(this.#W)}$assertType(){return new v1(this.#W)}withPlugin(W){return new v1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new _6(Z.numAffectedRows??BigInt(0),Z.numChangedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new v1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}v1=I8;var v6=k({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return k({kind:"CommonTableExpressionNameNode",table:u1.create(W),columns:$?k($.map(e.create)):void 0})}});var y8=k({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return k({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return k({...W,...$})}});class wW{#W;constructor(W){this.#W=k(W)}materialized(){return new wW({...this.#W,node:y8.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new wW({...this.#W,node:y8.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function E6(W,$){let Z=G1($)?$.toOperationNode():$(T5()).toOperationNode();if(R1(W))return W(y2(Z)).toOperationNode();return y8.create(h5(W),Z)}function y2(W){return($)=>{return new wW({node:y8.create(h5($),W)})}}function h5(W){if(W.includes("(")){let $=W.split(/[\(\)]/),Z=$[0],J=$[1].split(",").map((X)=>X.trim());return v6.create(Z,J)}else return v6.create(W)}var QW=k({is(W){return W.kind==="WithNode"},create(W,$){return k({kind:"WithNode",expressions:k([W]),...$})},cloneWithExpression(W,$){return k({...W,expressions:k([...W.expressions,$])})}});var f5=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function j5(W){let $="";for(let Z=0;Z<W;++Z)$+=g2();return $}function g2(){return f5[~~(Math.random()*f5.length)]}function W1(){return new A5}class A5{#W;get queryId(){if(this.#W===void 0)this.#W=j5(8);return this.#W}}class SW{nodeStack=[];#W=k({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let Z=this.transformNodeImpl(W,$);return this.nodeStack.pop(),k(Z)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return k(W.map((Z)=>this.transformNode(Z,$)))}transformSelectQuery(W,$){return{kind:"SelectQueryNode",from:this.transformNode(W.from,$),selections:this.transformNodeList(W.selections,$),distinctOn:this.transformNodeList(W.distinctOn,$),joins:this.transformNodeList(W.joins,$),groupBy:this.transformNode(W.groupBy,$),orderBy:this.transformNode(W.orderBy,$),where:this.transformNode(W.where,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),limit:this.transformNode(W.limit,$),offset:this.transformNode(W.offset,$),with:this.transformNode(W.with,$),having:this.transformNode(W.having,$),explain:this.transformNode(W.explain,$),setOperations:this.transformNodeList(W.setOperations,$),fetch:this.transformNode(W.fetch,$),top:this.transformNode(W.top,$)}}transformSelection(W,$){return{kind:"SelectionNode",selection:this.transformNode(W.selection,$)}}transformColumn(W,$){return{kind:"ColumnNode",column:this.transformNode(W.column,$)}}transformAlias(W,$){return{kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)}}transformTable(W,$){return{kind:"TableNode",table:this.transformNode(W.table,$)}}transformFrom(W,$){return{kind:"FromNode",froms:this.transformNodeList(W.froms,$)}}transformReference(W,$){return{kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)}}transformAnd(W,$){return{kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformOr(W,$){return{kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformValueList(W,$){return{kind:"ValueListNode",values:this.transformNodeList(W.values,$)}}transformParens(W,$){return{kind:"ParensNode",node:this.transformNode(W.node,$)}}transformJoin(W,$){return{kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)}}transformRaw(W,$){return{kind:"RawNode",sqlFragments:k([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)}}transformWhere(W,$){return{kind:"WhereNode",where:this.transformNode(W.where,$)}}transformInsertQuery(W,$){return{kind:"InsertQueryNode",into:this.transformNode(W.into,$),columns:this.transformNodeList(W.columns,$),values:this.transformNode(W.values,$),returning:this.transformNode(W.returning,$),onConflict:this.transformNode(W.onConflict,$),onDuplicateKey:this.transformNode(W.onDuplicateKey,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orAction:this.transformNode(W.orAction,$),replace:W.replace,explain:this.transformNode(W.explain,$),defaultValues:W.defaultValues,top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformValues(W,$){return{kind:"ValuesNode",values:this.transformNodeList(W.values,$)}}transformDeleteQuery(W,$){return{kind:"DeleteQueryNode",from:this.transformNode(W.from,$),using:this.transformNode(W.using,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orderBy:this.transformNode(W.orderBy,$),limit:this.transformNode(W.limit,$),explain:this.transformNode(W.explain,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformReturning(W,$){return{kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)}}transformCreateTable(W,$){return{kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),indexes:this.transformNodeList(W.indexes,$),temporary:W.temporary,ifNotExists:W.ifNotExists,onCommit:W.onCommit,frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),selectQuery:this.transformNode(W.selectQuery,$)}}transformColumnDefinition(W,$){return{kind:"ColumnDefinitionNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),references:this.transformNode(W.references,$),primaryKey:W.primaryKey,autoIncrement:W.autoIncrement,unique:W.unique,notNull:W.notNull,unsigned:W.unsigned,defaultTo:this.transformNode(W.defaultTo,$),check:this.transformNode(W.check,$),generated:this.transformNode(W.generated,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),nullsNotDistinct:W.nullsNotDistinct,identity:W.identity,ifNotExists:W.ifNotExists}}transformAddColumn(W,$){return{kind:"AddColumnNode",column:this.transformNode(W.column,$)}}transformDropTable(W,$){return{kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade,temporary:W.temporary}}transformOrderBy(W,$){return{kind:"OrderByNode",items:this.transformNodeList(W.items,$)}}transformOrderByItem(W,$){return{kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls}}transformGroupBy(W,$){return{kind:"GroupByNode",items:this.transformNodeList(W.items,$)}}transformGroupByItem(W,$){return{kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)}}transformUpdateQuery(W,$){return{kind:"UpdateQueryNode",table:this.transformNode(W.table,$),from:this.transformNode(W.from,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),updates:this.transformNodeList(W.updates,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),explain:this.transformNode(W.explain,$),limit:this.transformNode(W.limit,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$),orderBy:this.transformNode(W.orderBy,$)}}transformColumnUpdate(W,$){return{kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)}}transformLimit(W,$){return{kind:"LimitNode",limit:this.transformNode(W.limit,$)}}transformOffset(W,$){return{kind:"OffsetNode",offset:this.transformNode(W.offset,$)}}transformOnConflict(W,$){return{kind:"OnConflictNode",columns:this.transformNodeList(W.columns,$),constraint:this.transformNode(W.constraint,$),indexExpression:this.transformNode(W.indexExpression,$),indexWhere:this.transformNode(W.indexWhere,$),updates:this.transformNodeList(W.updates,$),updateWhere:this.transformNode(W.updateWhere,$),doNothing:W.doNothing}}transformOnDuplicateKey(W,$){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)}}transformCreateIndex(W,$){return{kind:"CreateIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists,where:this.transformNode(W.where,$),nullsNotDistinct:W.nullsNotDistinct}}transformList(W,$){return{kind:"ListNode",items:this.transformNodeList(W.items,$)}}transformDropIndex(W,$){return{kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade}}transformPrimaryKeyConstraint(W,$){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformUniqueConstraint(W,$){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformForeignKeyConstraint(W,$){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(W.columns,$),references:this.transformNode(W.references,$),name:this.transformNode(W.name,$),onDelete:W.onDelete,onUpdate:W.onUpdate,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformSetOperation(W,$){return{kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all}}transformReferences(W,$){return{kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate}}transformCheckConstraint(W,$){return{kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)}}transformWith(W,$){return{kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive}}transformCommonTableExpression(W,$){return{kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)}}transformCommonTableExpressionName(W,$){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)}}transformHaving(W,$){return{kind:"HavingNode",having:this.transformNode(W.having,$)}}transformCreateSchema(W,$){return{kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists}}transformDropSchema(W,$){return{kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade}}transformAlterTable(W,$){return{kind:"AlterTableNode",table:this.transformNode(W.table,$),renameTo:this.transformNode(W.renameTo,$),setSchema:this.transformNode(W.setSchema,$),columnAlterations:this.transformNodeList(W.columnAlterations,$),addConstraint:this.transformNode(W.addConstraint,$),dropConstraint:this.transformNode(W.dropConstraint,$),renameConstraint:this.transformNode(W.renameConstraint,$),addIndex:this.transformNode(W.addIndex,$),dropIndex:this.transformNode(W.dropIndex,$)}}transformDropColumn(W,$){return{kind:"DropColumnNode",column:this.transformNode(W.column,$),ifExists:W.ifExists}}transformRenameColumn(W,$){return{kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)}}transformAlterColumn(W,$){return{kind:"AlterColumnNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),dataTypeExpression:this.transformNode(W.dataTypeExpression,$),setDefault:this.transformNode(W.setDefault,$),dropDefault:W.dropDefault,setNotNull:W.setNotNull,dropNotNull:W.dropNotNull}}transformModifyColumn(W,$){return{kind:"ModifyColumnNode",column:this.transformNode(W.column,$)}}transformAddConstraint(W,$){return{kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)}}transformDropConstraint(W,$){return{kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier}}transformRenameConstraint(W,$){return{kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)}}transformCreateView(W,$){return{kind:"CreateViewNode",name:this.transformNode(W.name,$),temporary:W.temporary,orReplace:W.orReplace,ifNotExists:W.ifNotExists,materialized:W.materialized,columns:this.transformNodeList(W.columns,$),as:this.transformNode(W.as,$)}}transformRefreshMaterializedView(W,$){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData}}transformDropView(W,$){return{kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade}}transformGenerated(W,$){return{kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)}}transformDefaultValue(W,$){return{kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)}}transformOn(W,$){return{kind:"OnNode",on:this.transformNode(W.on,$)}}transformSelectModifier(W,$){return{kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)}}transformCreateType(W,$){return{kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)}}transformDropType(W,$){return{kind:"DropTypeNode",name:this.transformNode(W.name,$),additionalNames:this.transformNodeList(W.additionalNames,$),cascade:W.cascade,ifExists:W.ifExists}}transformExplain(W,$){return{kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)}}transformSchemableIdentifier(W,$){return{kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)}}transformAggregateFunction(W,$){return{kind:"AggregateFunctionNode",func:W.func,aggregated:this.transformNodeList(W.aggregated,$),distinct:W.distinct,orderBy:this.transformNode(W.orderBy,$),withinGroup:this.transformNode(W.withinGroup,$),filter:this.transformNode(W.filter,$),over:this.transformNode(W.over,$)}}transformOver(W,$){return{kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)}}transformPartitionBy(W,$){return{kind:"PartitionByNode",items:this.transformNodeList(W.items,$)}}transformPartitionByItem(W,$){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)}}transformBinaryOperation(W,$){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)}}transformUnaryOperation(W,$){return{kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)}}transformUsing(W,$){return{kind:"UsingNode",tables:this.transformNodeList(W.tables,$)}}transformFunction(W,$){return{kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)}}transformCase(W,$){return{kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement}}transformWhen(W,$){return{kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)}}transformJSONReference(W,$){return{kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)}}transformJSONPath(W,$){return{kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)}}transformJSONPathLeg(W,$){return{kind:"JSONPathLegNode",type:W.type,value:W.value}}transformJSONOperatorChain(W,$){return{kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)}}transformTuple(W,$){return{kind:"TupleNode",values:this.transformNodeList(W.values,$)}}transformMergeQuery(W,$){return{kind:"MergeQueryNode",into:this.transformNode(W.into,$),using:this.transformNode(W.using,$),whens:this.transformNodeList(W.whens,$),with:this.transformNode(W.with,$),top:this.transformNode(W.top,$),endModifiers:this.transformNodeList(W.endModifiers,$),output:this.transformNode(W.output,$),returning:this.transformNode(W.returning,$)}}transformMatched(W,$){return{kind:"MatchedNode",not:W.not,bySource:W.bySource}}transformAddIndex(W,$){return{kind:"AddIndexNode",name:this.transformNode(W.name,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists}}transformCast(W,$){return{kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)}}transformFetch(W,$){return{kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier}}transformTop(W,$){return{kind:"TopNode",expression:W.expression,modifiers:W.modifiers}}transformOutput(W,$){return{kind:"OutputNode",selections:this.transformNodeList(W.selections,$)}}transformAlterType(W,$){return{kind:"AlterTypeNode",name:this.transformNode(W.name,$),addValue:this.transformNode(W.addValue,$),renameTo:this.transformNode(W.renameTo,$),renameValue:this.transformNode(W.renameValue,$),setSchema:this.transformNode(W.setSchema,$)}}transformAddValue(W,$){return{kind:"AddValueNode",value:this.transformNode(W.value,$),ifNotExists:W.ifNotExists,isBefore:W.isBefore,neighborValue:this.transformNode(W.neighborValue,$)}}transformRenameValue(W,$){return{kind:"RenameValueNode",oldValue:this.transformNode(W.oldValue,$),newValue:this.transformNode(W.newValue,$)}}transformDataType(W,$){return W}transformSelectAll(W,$){return W}transformIdentifier(W,$){return W}transformValue(W,$){return W}transformPrimitiveValueList(W,$){return W}transformOperator(W,$){return W}transformDefaultInsertValue(W,$){return W}transformOrAction(W,$){return W}transformCollate(W,$){return W}}function N5(W){return Q1(W)&&a(W.kind)}var m2={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function C5(W){return N5(W)&&m2[W.kind]===!0}var c2=k({json_agg:!0,to_json:!0});class h6 extends SW{#W;#$=new Set;#Z=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!C5(W))return super.transformNodeImpl(W,$);let Z=this.#k(W);for(let Y of Z)this.#Z.add(Y);let J=this.#Y(W);for(let Y of J)this.#$.add(Y);let X=super.transformNodeImpl(W,$);for(let Y of J)this.#$.delete(Y);for(let Y of Z)this.#Z.delete(Y);return X}transformSchemableIdentifier(W,$){let Z=super.transformSchemableIdentifier(W,$);if(Z.schema||!this.#$.has(W.identifier.name))return Z;return{...Z,schema:l.create(this.#W)}}transformReferences(W,$){let Z=super.transformReferences(W,$);if(Z.table.table.schema)return Z;return{...Z,table:u1.createWithSchema(this.#W,Z.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#X(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#X(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((Z)=>u1.is(Z)&&!Z.table.schema?{...Z,table:this.transformIdentifier(Z.table.identifier,$)}:this.transformNode(Z,$))}}#X(W,$,Z){return c2[W.func]?W[Z].map((J)=>!u1.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[Z],$)}#Y(W){let $=new Set;if("name"in W&&W.name&&g1.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let Z of W.from.froms)this.#J(Z,$);if("into"in W&&W.into)this.#J(W.into,$);if("table"in W&&W.table)this.#J(W.table,$);if("joins"in W&&W.joins)for(let Z of W.joins)this.#J(Z.table,$);if("using"in W&&W.using)if(G0.is(W.using))this.#J(W.using.table,$);else this.#J(W.using,$);return $}#k(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#J(W,$){if(u1.is(W))return this.#H(W.table,$);if(q1.is(W)&&u1.is(W.node))return this.#H(W.node.table,$);if(G4.is(W)){for(let Z of W.items)this.#J(Z,$);return}if(FW.is(W)){for(let Z of W.tables)this.#J(Z,$);return}}#H(W,$){let Z=W.identifier.name;if(!this.#$.has(Z)&&!this.#Z.has(Z))$.add(Z)}#G(W,$){for(let Z of W.expressions){let J=Z.name.table.table.identifier.name;if(!this.#Z.has(J))$.add(J)}}}class V0{#W;constructor(W){this.#W=new h6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var q5=k({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return k({kind:"MatchedNode",not:W,bySource:$})}});function T6(W,$,Z){return i1.create(q8([q5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&Z?E1($[0],$[1],$[2]):K1($)]:[]],"and",!1))}function g8(W){if(a(W))return X1.create([W],[]);if(G1(W))return W.toOperationNode();return W}class y0{#W;#$;#Z;constructor(){this.#W=new Promise((W,$)=>{this.#Z=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{this.#$?.(W),this.#$=this.#Z=void 0};reject=(W)=>{this.#Z?.(W),this.#Z=this.#$=void 0}}async function m8(W,$){let Z=new y0,J=new y0;return W.provideConnection(async(X)=>{return Z.resolve(X),await J.promise},$).catch((X)=>Z.reject(X)),k({connection:await Z.promise,release:J.resolve})}function x5(W="ignore query",$,Z){if(W==="ignore query")return;if(W==="cancel query"){let J=$.cancelQuery;if(!J)O5(W,$.killSession?"kill session":void 0);return J.bind($)}if(W==="kill session"){let J=$.killSession;if(!J)O5(W,$.cancelQuery?"cancel query":void 0);return J.bind($)}throw Z(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${W}"`)}function O5(W,$){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${W}". Use "ignore query"${$?` or "${$}"`:""} instead.`)}function g0(W,$,Z){if(W?.aborted)Z?.(),Z8(W.reason,$)}function Z8(W,$){throw u2(W,$),W}var $0={};async function c8(W,$,Z,J){if(!$)return W;g0($,`before ${Z}`,J);let{promise:X,resolve:Y}=new y0,M=()=>Y($0);$.addEventListener("abort",M);try{g0($,`before ${Z}`,J);let G=await Promise.race([W,X]);if(G!==$0)return G;J?.(),Z8($.reason,`during ${Z}`)}finally{$.removeEventListener("abort",M),Y($0)}}function T0(W){return($)=>console.error(`\`${W}\` failed in the background after abortion: ${d9($)}`)}function u2(W,$){if(W!==null&&typeof W==="object"&&!Object.isFrozen(W))Object.defineProperty(W,"__kysely_timing__",{configurable:!0,enumerable:!1,value:$,writable:!1})}var l2=k([]);class _W{#W;constructor(W=l2){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let Z of this.#W){let J=Z.transformQuery({node:W,queryId:$});if(J.kind===W.kind)W=J;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${W.kind}`,`but it returned a ${J.kind}`].join(" "))}return W}async executeQuery(W,$){let{inflightQueryAbortStrategy:Z="ignore query",signal:J}=$||{};if(!J){let P=await this.provideConnection(async(w)=>{return await w.executeQuery(W)},$);return await this.#$(P,W.queryId)}g0(J,"before query execution"),$=k({signal:J});let{connection:X,release:Y}=await m8(this,$),M=this.provideConnection.bind(this),{promise:G,resolve:V}=new y0,R=()=>V($0);J.addEventListener("abort",R,{once:!0});try{g0(J,"before query execution",Y);let P=x5(Z,X,Y);if(P&&X.collectSessionInfo){g0(J,"before query execution",Y);let L=X.collectSessionInfo();if(await Promise.race([G,L]).catch((_)=>{throw Y(),_})===$0)L.catch(T0("collectSessionInfo")).finally(Y),Z8(J.reason,"before query execution")}let w=X.executeQuery(W,$),D=await Promise.race([G,w]).catch((L)=>{throw Y(),L});if(D===$0)Promise.allSettled([w.catch(T0("query")),P?.(M).catch(T0("inflightQueryAbortHandler"))]).finally(Y),Z8(J.reason,"during query execution");else Y();let S=this.#$(D,W.queryId,$),F=await Promise.race([G,S]);if(F===$0)S.catch(T0("plugins.transformResult")),Z8(J.reason,"during result transformation");return F}finally{V($0),J.removeEventListener("abort",R)}}async*stream(W,$,Z){let{signal:J}=Z||{};if(!J){let{connection:D,release:S}=await m8(this);try{for await(let F of D.streamQuery(W,$))yield await this.#$(F,W.queryId,Z)}finally{S()}return}Z=k({signal:J}),g0(J,"before connection acquisition");let{connection:X,release:Y}=await m8(this,Z),{promise:M,resolve:G}=new y0,V=()=>G($0);J.addEventListener("abort",V,{once:!0});let R,P;g0(J,"before query streaming",Y);let{queryId:w}=W;try{R=X.streamQuery(W,$,Z);while(!0){g0(J,"during query streaming");let D=R.next(),S=await Promise.race([M,D]);if(S===$0)P=D.catch(T0("iterator.next")),Z8(J.reason,"during query streaming");if(S.done)break;let F=this.#$(S.value,w,Z),L=await Promise.race([M,F]);if(L===$0)P=F.catch(T0("plugins.transformResult")),Z8(J.reason,"during result transformation");yield L}}finally{G($0),J.removeEventListener("abort",V);let D=(R?.return?.()||Promise.resolve()).finally(()=>P).finally(Y);if(!P)await D}}async#$(W,$,Z){let{signal:J}=Z||{};for(let X of this.#W)W=await X.transformResult(k({queryId:$,result:W,signal:J}));return W}}class u8 extends _W{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(W){return new u8([...this.plugins,W])}withPlugins(W){return new u8([...this.plugins,...W])}withPluginAtFront(W){return new u8([W,...this.plugins])}withoutPlugins(){return new u8([])}}var J8=new u8;class f6{numChangedRows;constructor(W){this.numChangedRows=W}}class m0{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new m0({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new m0({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(...W){return new t1({...this.#W,queryNode:W0.cloneWithUsing(this.#W.queryNode,$8("Using",W))})}returning(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}}class t1{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new t1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new t1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,Z){return this.#$([W,$,Z],!0)}#$(W,$){return new j6({...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,T6({isMatched:!0},W,$))})}whenNotMatched(){return this.#Z([])}whenNotMatchedAnd(...W){return this.#Z(W)}whenNotMatchedAndRef(W,$,Z){return this.#Z([W,$,Z],!0)}whenNotMatchedBySource(){return this.#Z([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#Z(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,Z){return this.#Z([W,$,Z],!0,!0)}returning(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}#Z(W,$=!1,Z=!1){let J={...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,T6({isMatched:!1,bySource:Z},W,$))};return new(Z?j6:B5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new t1({...this.#W})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new f6(Z.numAffectedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}}class j6{#W;constructor(W){this.#W=k(W)}thenDelete(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("delete"))})}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("do nothing"))})}thenUpdate(W){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8(W(new I8({queryId:this.#W.queryId,executor:J8,queryNode:v0.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class B5{#W;constructor(W){this.#W=k(W)}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("do nothing"))})}thenInsertValues(W){let[$,Z]=L4(W);return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8(S1.cloneWith(S1.createWithoutInto(),{columns:$,values:Z})))})}}class f0{#W;constructor(W){this.#W=k(W)}selectFrom(W){return vW({queryId:W1(),executor:this.#W.executor,queryNode:k1.createFrom(U0(W),this.#W.withNode)})}selectNoFrom(W){return vW({queryId:W1(),executor:this.#W.executor,queryNode:k1.cloneWithSelections(k1.create(this.#W.withNode),j1(W))})}insertInto(W){return new L1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode)})}replaceInto(W){return new L1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode,!0)})}deleteFrom(W){return new K4({queryId:W1(),executor:this.#W.executor,queryNode:W8.create(U0(W),this.#W.withNode)})}updateTable(W){return new I8({queryId:W1(),executor:this.#W.executor,queryNode:v0.create(U0(W),this.#W.withNode)})}mergeInto(W){return new m0({queryId:W1(),executor:this.#W.executor,queryNode:W0.create(A6(W),this.#W.withNode)})}with(W,$){let Z=E6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z)})}withRecursive(W,$){let Z=E6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z,{recursive:!0})})}withPlugin(W){return new f0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new f0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new f0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}}function T5(){return new f0({executor:J8})}function b5(W,$){return new O8({joinNode:G0.create(W,V8($))})}function I5(){return new x8({overNode:PW.create()})}function $8(W,$){if($.length===3)return i2(W,$[0],$[1],$[2]);else if($.length===2)return p2(W,$[0],$[1]);else if($.length===1)return t2(W,$[0]);else throw Error("not implemented")}function p2(W,$,Z){return Z(b5(W,$)).toOperationNode()}function i2(W,$,Z,J){return G0.createWithOn(W,V8($),E1(Z,"=",J))}function t2(W,$){return G0.create(W,V8($))}var y5=k({is(W){return W.kind==="OffsetNode"},create(W){return k({kind:"OffsetNode",offset:W})}});var g5=k({is(W){return W.kind==="GroupByItemNode"},create(W){return k({kind:"GroupByItemNode",groupBy:W})}});function m5(W){return W=R1(W)?W(L0()):W,b0(W).map(g5.create)}var z4=k({is(W){return W.kind==="SetOperationNode"},create(W,$,Z){return k({kind:"SetOperationNode",operator:W,expression:$,all:Z})}});function P8(W,$,Z){if(R1($))$=$(N6());if(!y1($))$=[$];return $.map((J)=>z4.create(W,O1(J),Z))}class Y1{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}or(...W){return new U4(k0.create(this.#W,K1(W)))}and(...W){return new V4(l1.create(this.#W,K1(W)))}$castTo(){return new Y1(this.#W)}$notNull(){return new Y1(this.#W)}toOperationNode(){return this.#W}}class P4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}class U4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}or(...W){return new U4(k0.create(this.#W,K1(W)))}$castTo(){return new U4(this.#W)}toOperationNode(){return e1.create(this.#W)}}class V4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}and(...W){return new V4(l1.create(this.#W,K1(W)))}$castTo(){return new V4(this.#W)}toOperationNode(){return e1.create(this.#W)}}var c5=k({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:D1.create(W),modifier:$}}});function u5(W,$){if(!d0(W)&&!h8(W))throw Error(`Invalid fetch row count: ${W}`);if(!a2($))throw Error(`Invalid fetch modifier: ${$}`);return c5.create(W,$)}function a2(W){return W==="only"||W==="with ties"}var n;class C6{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}having(...W){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,K1(W))})}havingRef(W,$,Z){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,E1(W,$,Z))})}select(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,j1(W))})}distinctOn(W){return new n({...this.#W,queryNode:k1.cloneWithDistinctOn(this.#W.queryNode,b0(W))})}modifyFront(W){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}distinct(){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.create("Distinct"))})}forUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForUpdate",W?zW(W).map(Z1):void 0))})}forShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForShare",W?zW(W).map(Z1):void 0))})}forKeyShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForKeyShare",W?zW(W).map(Z1):void 0))})}forNoKeyUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForNoKeyUpdate",W?zW(W).map(Z1):void 0))})}skipLocked(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("SkipLocked"))})}noWait(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("NoWait"))})}selectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,x1(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}crossJoin(...W){return this.#$("CrossJoin",W)}innerJoinLateral(...W){return this.#$("LateralInnerJoin",W)}leftJoinLateral(...W){return this.#$("LateralLeftJoin",W)}crossJoinLateral(...W){return this.#$("LateralCrossJoin",W)}crossApply(...W){return this.#$("CrossApply",W)}outerApply(...W){return this.#$("OuterApply",W)}#$(W,$){return new n({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new n({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}groupBy(W){return new n({...this.#W,queryNode:k1.cloneWithGroupByItems(this.#W.queryNode,m5(W))})}limit(W){return new n({...this.#W,queryNode:k1.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}offset(W){return new n({...this.#W,queryNode:k1.cloneWithOffset(this.#W.queryNode,y5.create(M1(W)))})}fetch(W,$="only"){return new n({...this.#W,queryNode:k1.cloneWithFetch(this.#W.queryNode,u5(W,$))})}top(W,$){return new n({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}union(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!1))})}unionAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!0))})}intersect(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!1))})}intersectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!0))})}except(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!1))})}exceptAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!0))})}as(W){return new l5(this,W)}clearSelect(){return new n({...this.#W,queryNode:k1.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new n({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new n({...this.#W,queryNode:k1.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new n({...this.#W,queryNode:k1.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new n({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new n({...this.#W,queryNode:k1.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new n({...this.#W})}$castTo(){return new n(this.#W)}$narrowType(){return new n(this.#W)}$assertType(){return new n(this.#W)}$asTuple(){return new Y1(this.toOperationNode())}$asScalar(){return new Y1(this.toOperationNode())}withPlugin(W){return new n({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile();return(await this.#W.executor.executeQuery($,W)).rows}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new n({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}n=C6;function vW(W){return new C6(W)}class l5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}var j0=k({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return k({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return k({...W,distinct:!0})},cloneWithOrderBy(W,$,Z=!1){let J=Z?"withinGroup":"orderBy";return k({...W,[J]:W[J]?I0.cloneWithItems(W[J],$):I0.create($)})},cloneWithFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"And",$):b1.create($)})},cloneWithOrFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"Or",$):b1.create($)})},cloneWithOver(W,$){return k({...W,over:$})}});var q6=k({is(W){return W.kind==="FunctionNode"},create(W,$){return k({kind:"FunctionNode",func:W,arguments:$})}});class a1{#W;constructor(W){this.#W=k(W)}get expressionType(){return}as(W){return new p5(this,W)}distinct(){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithOrderByItems(this.#W.aggregateFunctionNode,o1(W))})}clearOrderBy(){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOrderBy(this.#W.aggregateFunctionNode,o1(W),!0)})}filterWhere(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,K1(W))})}filterWhereRef(W,$,Z){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,E1(W,$,Z))})}over(W){let $=I5();return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new a1(this.#W)}$notNull(){return new a1(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class p5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}function F4(){let W=(Z,J)=>{return new Y1(q6.create(Z,b0(J??[])))},$=(Z,J)=>{return new a1({aggregateFunctionNode:j0.create(Z,J?b0(J):void 0)})};return Object.assign(W,{agg:$,avg(Z){return $("avg",[Z])},coalesce(...Z){return W("coalesce",Z)},count(Z){return $("count",[Z])},countAll(Z){return new a1({aggregateFunctionNode:j0.create("count",x1(Z))})},max(Z){return $("max",[Z])},min(Z){return $("min",[Z])},sum(Z){return $("sum",[Z])},any(Z){return W("any",[Z])},jsonAgg(Z){return new a1({aggregateFunctionNode:j0.create("json_agg",[a(Z)?Z1(Z):Z.toOperationNode()])})},toJson(Z){return new Y1(q6.create("to_json",[a(Z)?Z1(Z):Z.toOperationNode()]))}})}var i5=k({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return k({kind:"UnaryOperationNode",operator:W,operand:$})}});function t5(W,$){if(Y5(W))return i5.create(r1.create(W),T1($));throw Error(`invalid unary operator ${JSON.stringify(W)}`)}var I1=k({is(W){return W.kind==="CaseNode"},create(W){return k({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return k({...W,when:k(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return k({...W,when:W.when?k([...W.when.slice(0,-1),i1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return k({...W,...$})}});class hW{#W;constructor(W){this.#W=k(W)}when(...W){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(K1(W)))})}whenRef(W,$,Z){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(E1(W,$,Z)))})}}class EW{#W;constructor(W){this.#W=k(W)}then(W){return new O6({...this.#W,node:I1.cloneWithThen(this.#W.node,H4(W)?VW(W):M1(W))})}thenRef(W){return new O6({...this.#W,node:I1.cloneWithThen(this.#W.node,T1(W))})}}class O6{#W;constructor(W){this.#W=k(W)}when(...W){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(K1(W)))})}whenRef(W,$,Z){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(E1(W,$,Z)))})}else(W){return new x6({...this.#W,node:I1.cloneWith(this.#W.node,{else:H4(W)?VW(W):M1(W)})})}elseRef(W){return new x6({...this.#W,node:I1.cloneWith(this.#W.node,{else:T1(W)})})}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}class x6{#W;constructor(W){this.#W=k(W)}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}var B6=k({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return k({kind:"JSONPathLegNode",type:W,value:$})}});var d2=/^#-\d+$/;class fW{#W;constructor(W){this.#W=W}at(W){if(typeof W!=="number"&&typeof W!=="string"||typeof W==="number"&&!Number.isInteger(W)||typeof W==="string"&&W!=="last"&&!d2.test(W))throw Error(`Unexpected index value in .at(...): ${W}`);return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(N8.is(this.#W))return new TW(N8.cloneWithTraversal(this.#W,o0.is(this.#W.traversal)?o0.cloneWithLeg(this.#W.traversal,B6.create(W,$)):X4.cloneWithValue(this.#W.traversal,D1.createImmediate($))));return new TW(o0.cloneWithLeg(this.#W,B6.create(W,$)))}}class TW extends fW{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new a5(this,W)}$castTo(){return new TW(this.#W)}$notNull(){return new TW(this.#W)}toOperationNode(){return this.#W}}class a5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var b6=k({is(W){return W.kind==="TupleNode"},create(W){return k({kind:"TupleNode",values:k(W)})}});var s2=k({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),n2=k([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),d5=k({is(W){return W.kind==="DataTypeNode"},create(W){return k({kind:"DataTypeNode",dataType:W})}});function s5(W){return s2[W]||n2.some(($)=>$.test(W))}function P0(W){if(G1(W))return W.toOperationNode();if(s5(W))return d5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var n5=k({is(W){return W.kind==="CastNode"},create(W,$){return k({kind:"CastNode",expression:W,dataType:$})}});function N6(W=J8){function $(X,Y,M){return new Y1(k4(X,Y,M))}function Z(X,Y){return new Y1(t5(X,Y))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(X){return vW({queryId:W1(),executor:W,queryNode:k1.createFrom(U0(X))})},case(X){return new hW({node:I1.create(n1(X)?void 0:T1(X))})},ref(X,Y){if(n1(Y))return new Y1(p1(X));return new fW(M5(X,Y))},jsonPath(){return new fW(o0.create())},table(X){return new Y1(Z1(X))},val(X){return new Y1(M1(X))},refTuple(...X){return new Y1(b6.create(X.map(T1)))},tuple(...X){return new Y1(b6.create(X.map(M1)))},lit(X){return new Y1(VW(X))},unary:Z,not(X){return Z("not",X)},exists(X){return Z("exists",X)},neg(X){return Z("-",X)},between(X,Y,M){return new Y1(n0.create(T1(X),r1.create("between"),l1.create(M1(Y),M1(M))))},betweenSymmetric(X,Y,M){return new Y1(n0.create(T1(X),r1.create("between symmetric"),l1.create(M1(Y),M1(M))))},and(X){if(y1(X))return new Y1(q8(X,"and"));return new Y1(U6(X,"and"))},or(X){if(y1(X))return new Y1(q8(X,"or"));return new Y1(U6(X,"or"))},parens(...X){let Y=K1(X);if(e1.is(Y))return new Y1(Y);else return new Y1(e1.create(Y))},cast(X,Y){return new Y1(n5.create(T1(X),P0(Y)))}});return J.fn=F4(),J.eb=J,J}function L0(W){return N6()}function O1(W){if(G1(W))return W.toOperationNode();else if(R1(W))return W(L0()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function M4(W){if(G1(W))return W.toOperationNode();else if(R1(W))return W(L0()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function B0(W){return $4(W)||n9(W)||R1(W)}class I6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new r5(this.#W,W)}}class r5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return q1.create(Z1(this.#W),l.create(this.#$))}}function o5(W){return Q1(W)&&G1(W)&&a(W.table)&&a(W.alias)}function U0(W){if(y1(W))return W.map(($)=>V8($));else return[V8(W)]}function V8(W){if(a(W))return A6(W);else if(o5(W))return W.toOperationNode();else return M4(W)}function A6(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(e5);return q1.create(Z1(Z),l.create(J))}else return Z1(W)}function Z1(W){if(W.includes(".")){let[Z,J]=W.split(".").map(e5);return u1.createWithSchema(Z,J)}else return u1.create(W)}function e5(W){return W.trim()}var y6=k({is(W){return W.kind==="AddColumnNode"},create(W){return k({kind:"AddColumnNode",column:W})}});var z1=k({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return k({kind:"ColumnDefinitionNode",column:e.create(W),dataType:$})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):[$]})},cloneWith(W,$){return k({...W,...$})}});var jW=k({is(W){return W.kind==="DropColumnNode"},create(W){return k({kind:"DropColumnNode",column:e.create(W)})},cloneWith(W,$){return k({...W,...$})}});var g6=k({is(W){return W.kind==="RenameColumnNode"},create(W,$){return k({kind:"RenameColumnNode",column:e.create(W),renameTo:e.create($)})}});var l8=k({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return k({kind:"CheckConstraintNode",expression:W,name:$?l.create($):void 0})}});var W7=k({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),$V=Object.keys(W7),p8=k({is(W){return W.kind==="ReferencesNode"},create(W,$){return k({kind:"ReferencesNode",table:W,columns:k([...$])})},cloneWithOnDelete(W,$){return k({...W,onDelete:$})},cloneWithOnUpdate(W,$){return k({...W,onUpdate:$})}});function $7(W){return a(W)&&W7[W]}function R4(W){return G1(W)?W.toOperationNode():D1.createImmediate(W)}var AW=k({is(W){return W.kind==="GeneratedNode"},create(W){return k({kind:"GeneratedNode",...W})},createWithExpression(W){return k({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return k({...W,...$})}});var Z7=k({is(W){return W.kind==="DefaultValueNode"},create(W){return k({kind:"DefaultValueNode",defaultValue:W})}});function i8(W){if($7(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class U1{#W;constructor(W){this.#W=W}autoIncrement(){return new U1(z1.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new U1(z1.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new U1(z1.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=p1(W);if(!$.table||f8.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new U1(z1.cloneWith(this.#W,{references:p8.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:p8.cloneWithOnDelete(this.#W.references,i8(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:p8.cloneWithOnUpdate(this.#W.references,i8(W))}))}unique(){return new U1(z1.cloneWith(this.#W,{unique:!0}))}notNull(){return new U1(z1.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new U1(z1.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new U1(z1.cloneWith(this.#W,{defaultTo:Z7.create(R4(W))}))}check(W){return new U1(z1.cloneWith(this.#W,{check:l8.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new U1(z1.cloneWith(this.#W,{generated:AW.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new U1(z1.cloneWith(this.#W,{generated:AW.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new U1(z1.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new U1(z1.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new U1(z1.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new U1(z1.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var m6=k({is(W){return W.kind==="ModifyColumnNode"},create(W){return k({kind:"ModifyColumnNode",column:W})}});var F0=k({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,Z,J){return k({kind:"ForeignKeyConstraintNode",columns:W,references:p8.create($,Z),name:J?l.create(J):void 0})},cloneWith(W,$){return k({...W,...$})}});class R0{#W;constructor(W){this.#W=W}onDelete(W){return new R0(F0.cloneWith(this.#W,{onDelete:i8(W)}))}onUpdate(W){return new R0(F0.cloneWith(this.#W,{onUpdate:i8(W)}))}deferrable(){return new R0(F0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new R0(F0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new R0(F0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new R0(F0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var t8=k({is(W){return W.kind==="AddConstraintNode"},create(W){return k({kind:"AddConstraintNode",constraint:W})}});var A0=k({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,Z){if(a(W.at(0)))A8("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),W=W.map(e.create);return k({kind:"UniqueConstraintNode",columns:k(W),name:$?l.create($):void 0,nullsNotDistinct:Z})},cloneWith(W,$){return k({...W,...$})}});var a8=k({is(W){return W.kind==="DropConstraintNode"},create(W){return k({kind:"DropConstraintNode",constraintName:l.create(W)})},cloneWith(W,$){return k({...W,...$})}});var d8=k({is(W){return W.kind==="AlterColumnNode"},create(W,$,Z){return k({kind:"AlterColumnNode",column:e.create(W),[$]:Z})}});class D4{#W;constructor(W){this.#W=W}setDataType(W){return new s8(d8.create(this.#W,"dataType",P0(W)))}setDefault(W){return new s8(d8.create(this.#W,"setDefault",R4(W)))}dropDefault(){return new s8(d8.create(this.#W,"dropDefault",!0))}setNotNull(){return new s8(d8.create(this.#W,"setNotNull",!0))}dropNotNull(){return new s8(d8.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class s8{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class X8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class c0{#W;constructor(W){this.#W=k(W)}onDelete(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class F8{#W;constructor(W){this.#W=k(W)}ifExists(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{modifier:"restrict"})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var u0=k({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return k({kind:"PrimaryKeyConstraintNode",columns:k(W.map(e.create)),name:$?l.create($):void 0})},cloneWith(W,$){return k({...W,...$})}});var Z0=k({is(W){return W.kind==="AddIndexNode"},create(W){return k({kind:"AddIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});class Y8{#W;constructor(W){this.#W=k(W)}unique(){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[a(W)?C8(W):W.toOperationNode()])})})}columns(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,W.map(($)=>a($)?C8($):$.toOperationNode()))})})}expression(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{using:X1.createWithSql(W)})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class N0{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N0(A0.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class l0{#W;constructor(W){this.#W=W}deferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class NW{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var J7=k({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return k({kind:"RenameConstraintNode",oldName:l.create(W),newName:l.create($)})}});class CW{#W;constructor(W){this.#W=k({...W})}ifExists(){return new CW({...this.#W,node:jW.cloneWith(this.#W.node,{ifExists:!0})})}toOperationNode(){return this.#W.node}}class c6{#W;constructor(W){this.#W=k(W)}renameTo(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameTo:Z1(W)})})}setSchema(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{setSchema:l.create(W)})})}alterColumn(W,$){let Z=$(new D4(W));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,y6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(l8.create($.toOperationNode(),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new R0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c0({...this.#W,constraintBuilder:Y})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}dropConstraint(W){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.create(W)})})}renameConstraint(W,$){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameConstraint:J7.create(W,$)})})}addIndex(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.create(W)})})}dropIndex(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropIndex:s0.create(W)})})}$call(W){return W(this)}}class D0{#W;constructor(W){this.#W=k(W)}alterColumn(W,$){let Z=$(new D4(W));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,y6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(J.toOperationNode()))})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class qW extends SW{transformPrimitiveValueList(W){return e0.create(W.values.map(D1.createImmediate))}transformValue(W){return D1.createImmediate(W.value)}}class J0{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{table:Z1(W)})})}column(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[a(W)?C8(W):W.toOperationNode()])})}columns(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,W.map(($)=>a($)?C8($):$.toOperationNode()))})}expression(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{using:X1.createWithSql(W)})})}where(...W){let $=new qW;return new J0({...this.#W,node:y.cloneWithWhere(this.#W.node,$.transformNode(K1(W),this.#W.queryId))})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class w4{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new w4({...this.#W,node:W4.cloneWith(this.#W.node,{ifNotExists:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function X7(W){if(s9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class Q4{#W;constructor(W){this.#W=W}using(W){return new Q4(Z0.cloneWith(this.#W,{using:X1.createWithSql(W)}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class c1{#W;constructor(W){this.#W=k(W)}temporary(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{onCommit:X7(W)})})}ifNotExists(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new c1({...this.#W,node:C1.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addIndex(W,$,Z=N1){let J=Z(new Q4(Z0.cloneWithColumns(Z0.create(W),$.map((X)=>a(X)?e.create(X):O1(X)))));return new c1({...this.#W,node:C1.cloneWithIndex(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(l8.create($.toOperationNode(),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new R0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,Y.toOperationNode())})}modifyFront(W){return new c1({...this.#W,node:C1.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new c1({...this.#W,node:C1.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{selectQuery:O1(W)})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class n8{#W;constructor(W){this.#W=k(W)}on(W){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{table:Z1(W)})})}ifExists(){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class OW{#W;constructor(W){this.#W=k(W)}ifExists(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class r8{#W;constructor(W){this.#W=k(W)}temporary(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{temporary:!0})})}ifExists(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var w0=k({is(W){return W.kind==="CreateViewNode"},create(W){return k({kind:"CreateViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class u6{#W=new qW;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class p0{#W;constructor(W){this.#W=k(W)}temporary(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{columns:W.map(L6)})})}as(W){let $=W.withPlugin(new u6).toOperationNode();return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{as:$})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var o8=k({is(W){return W.kind==="DropViewNode"},create(W){return k({kind:"DropViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class e8{#W;constructor(W){this.#W=k(W)}materialized(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var S4=k({is(W){return W.kind==="CreateTypeNode"},create(W){return k({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return k({...W,enum:e0.create($.map(D1.createImmediate))})}});class _4{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new _4({...this.#W,node:S4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var xW=k({is(W){return W.kind==="DropTypeNode"},create(W){if(!Array.isArray(W))W=[W];return k({kind:"DropTypeNode",name:W[0],additionalNames:W.slice(1)})},cloneWith(W,$){return k({...W,...$})}});class BW{#W;constructor(W){this.#W=k(W)}ifExists(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function v4(W){if(W.includes(".")){let Z=W.split(".").map(r2);if(Z.length===2)return g1.createWithSchema(Z[0],Z[1]);else throw Error(`invalid schemable identifier ${W}`)}else return g1.create(W)}function Y7(W){if(!Array.isArray(W))W=[W];return W.map(v4)}function r2(W){return W.trim()}var WW=k({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return k({kind:"RefreshMaterializedViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class $W{#W;constructor(W){this.#W=k(W)}concurrently(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{withNoData:!0,concurrently:!1})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var C0=k({is(W){return W.kind==="AlterTypeNode"},create(W){return k({kind:"AlterTypeNode",name:W})},cloneWith(W,$){return k({...W,...$})}});var bW=k({is(W){return W.kind==="AddValueNode"},create(W){return k({kind:"AddValueNode",value:W})},cloneWith(W,$){return k({...W,...$})}});class R8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){return await this.#W.executor.executeQuery(this.compile(),W)}}var l6;class E4 extends R8{#W;constructor(W){super(W);this.#W=W}ifNotExists(){return new l6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{ifNotExists:!0})})})}before(W){return this.#$(W,!0)}after(W){return this.#$(W,!1)}#$(W,$){return new l6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{isBefore:$,neighborValue:D1.createImmediate(W)})})})}}l6=E4;var H7=k({is(W){return W.kind==="RenameValueNode"},create(W,$){return k({kind:"RenameValueNode",oldValue:W,newValue:$})}});class p6{#W;constructor(W){this.#W=k(W)}addValue(W){return new E4({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.create(D1.createImmediate(W))})})}renameTo(W){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{renameTo:l.create(W)})})}renameValue(W,$){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{renameValue:H7.create(D1.createImmediate(W),D1.createImmediate($))})})}setSchema(W){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{setSchema:l.create(W)})})}}class ZW{#W;constructor(W){this.#W=W}createTable(W){return new c1({queryId:W1(),executor:this.#W,node:C1.create(Z1(W))})}dropTable(W){return new r8({queryId:W1(),executor:this.#W,node:T8.create(Z1(W))})}createIndex(W){return new J0({queryId:W1(),executor:this.#W,node:H0.create(W)})}dropIndex(W){return new n8({queryId:W1(),executor:this.#W,node:s0.create(W)})}createSchema(W){return new w4({queryId:W1(),executor:this.#W,node:W4.create(W)})}dropSchema(W){return new OW({queryId:W1(),executor:this.#W,node:UW.create(W)})}alterTable(W){return new c6({queryId:W1(),executor:this.#W,node:$1.create(Z1(W))})}createView(W){return new p0({queryId:W1(),executor:this.#W,node:w0.create(W)})}refreshMaterializedView(W){return new $W({queryId:W1(),executor:this.#W,node:WW.create(W)})}dropView(W){return new e8({queryId:W1(),executor:this.#W,node:o8.create(W)})}createType(W){return new _4({queryId:W1(),executor:this.#W,node:S4.create(v4(W))})}alterType(W){return new p6({executor:this.#W,node:C0.create(v4(W)),queryId:W1()})}dropType(W){return new BW({queryId:W1(),executor:this.#W,node:xW.create(Y7(W))})}withPlugin(W){return new ZW(this.#W.withPlugin(W))}withoutPlugins(){return new ZW(this.#W.withoutPlugins())}withSchema(W){return new ZW(this.#W.withPluginAtFront(new V0(W)))}}class i6{ref(W){return new H6(W)}table(W){return new I6(W)}}class t6{#W;constructor(W){this.#W=W}async provideConnection(W,$){let Z=await this.#W.acquireConnection($);try{return await W(Z)}finally{await this.#W.releaseConnection(Z,$)}}}class H8 extends _W{#W;#$;#Z;constructor(W,$,Z,J=[]){super(J);this.#W=W,this.#$=$,this.#Z=Z}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#Z.provideConnection(W,$)}withPlugins(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,...W])}withPlugin(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,W])}withPluginAtFront(W){return new H8(this.#W,this.#$,this.#Z,[W,...this.plugins])}withConnectionProvider(W){return new H8(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new H8(this.#W,this.#$,this.#Z,[])}}function h4(){if(typeof performance<"u"&&R1(performance.now))return performance.now();else return Date.now()}class a6{#W;#$;async obtainLock(){while(this.#W)await this.#W;this.#W=new Promise((W)=>{this.#$=W})}releaseLock(){let W=this.#$;this.#W=void 0,this.#$=void 0,W?.()}}class d6{#W;#$;#Z;#X;#Y;#k=new WeakSet;#J;constructor(W,$,Z){if(this.#W=W,this.#X=!1,this.#$=Z,$.supportsMultipleConnections===!1)this.#J=new a6}async init(W){if(this.#Y)throw Error("driver has already been destroyed");this.#Z??=this.#W.init(W).then(()=>{this.#X=!0}).catch(($)=>{throw this.#Z=void 0,$}),await c8(this.#Z,W?.signal,"init")}async acquireConnection(W){if(this.#Y)throw Error("driver has already been destroyed");if(!this.#X)await this.init(W);if(this.#J){let J=this.#J.obtainLock();await c8(J,W?.signal,"acquireConnection:mutex",()=>J.then(()=>this.#J?.releaseLock()))}let $=this.#W.acquireConnection(W),Z=await c8($,W?.signal,"acquireConnection:acquire",()=>$?.then((J)=>this.releaseConnection(J).catch(T0("driver.releaseConnection"))).catch(T0("driver.acquireConnection")));if(!this.#k.has(Z)){if(this.#H())this.#G(Z);this.#k.add(Z)}return Z}async releaseConnection(W,$){await this.#W.releaseConnection(W,$),this.#J?.releaseLock()}async beginTransaction(W,$){return await this.#W.beginTransaction(W,$)}async commitTransaction(W){return await this.#W.commitTransaction(W)}async rollbackTransaction(W){return await this.#W.rollbackTransaction(W)}async savepoint(W,$,Z){if(this.#W.savepoint)return await this.#W.savepoint(W,$,Z);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(W,$,Z){if(this.#W.rollbackToSavepoint)return await this.#W.rollbackToSavepoint(W,$,Z);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(W,$,Z){if(this.#W.releaseSavepoint)return await this.#W.releaseSavepoint(W,$,Z);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(W){if(!this.#Z)return;await c8(this.#Z,W?.signal,"destroy:initPromise"),this.#Y??=this.#W.destroy(W).catch(($)=>{throw this.#Y=void 0,$}),await c8(this.#Y,W?.signal,"destroy")}#H(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#G(W){let{executeQuery:$,streamQuery:Z}=W,J=this;W.executeQuery=async(X,Y)=>{let M,G=h4();try{return await $.call(W,X,Y)}catch(V){throw M=V,await J.#K(V,X,G),V}finally{if(!M)await J.#z(X,G)}},W.streamQuery=async function*(X,Y,M){let G,V=h4();try{for await(let R of Z.call(W,X,Y,M))yield R}catch(R){throw G=R,await J.#K(R,X,V),R}finally{if(!G)await J.#z(X,V,!0)}}}async#K(W,$,Z){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#M(Z)}))}async#z(W,$,Z=!1){await this.#$.query(()=>({level:"query",isStream:Z,query:W,queryDurationMillis:this.#M($)}))}#M(W){return h4()-W}}var o2=()=>{};class IW{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch(o2);return this.#$=this.#Z(W).finally(()=>{this.#$=void 0}),this.#$}async#Z(W){return await W(this.#W)}}var e2=["read only","read write"],WZ=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function s6(W){if(W.accessMode&&!e2.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!WZ.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var $Z=["query","error"],$w=k($Z);class n6{#W;#$;constructor(W){if(R1(W))this.#$=W,this.#W=k({query:!0,error:!0});else this.#$=ZZ,this.#W=k({query:W.includes("query"),error:W.includes("error")})}isLevelEnabled(W){return this.#W[W]}async query(W){if(this.#W.query)await this.#$(W())}async error(W){if(this.#W.error)await this.#$(W())}}function ZZ(W){if(W.level==="query"){let $=`kysely:query:${W.isStream?"stream:":""}`;console.log(`${$} ${W.query.sql}`),console.log(`${$} duration: ${W.queryDurationMillis.toFixed(1)}ms`)}else if(W.level==="error")if(W.error instanceof Error)console.error(`kysely:error: ${W.error.stack??W.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:W.error,query:W.query.sql,queryDurationMillis:W.queryDurationMillis})}`)}function k7(W){return Q1(W)&&R1(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class Q0 extends f0{#W;constructor(W){let $,Z;if(JZ(W))$={executor:W.executor},Z={...W};else{let J=W.dialect,X=J.createDriver(),Y=J.createQueryCompiler(),M=J.createAdapter(),G=new n6(W.log??[]),V=new d6(X,M,G),R=new t6(V),P=new H8(Y,M,R,W.plugins??[]);$={executor:P},Z={config:W,executor:P,dialect:J,driver:V}}super($);this.#W=k(Z)}get schema(){return new ZW(this.#W.executor)}get dynamic(){return new i6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new hW({node:I1.create(n1(W)?void 0:O1(W))})}get fn(){return F4()}transaction(){return new T4({...this.#W})}startTransaction(){return new f4({...this.#W})}connection(){return new G7({...this.#W})}withPlugin(W){return new Q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new Q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new Q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}$extendTables(){return new Q0({...this.#W})}$omitTables(){return new Q0({...this.#W})}$pickTables(){return new Q0({...this.#W})}withTables(){return this.$extendTables()}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}async executeQuery(W,$){let Z=k7(W)?W.compile():W;return await this.#W.executor.executeQuery(Z,$)}async[Symbol.asyncDispose](){await this.destroy()}}class q0 extends Q0{#W;constructor(W){super(W);this.#W=W}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new q0({...this.#W})}$extendTables(){return new q0({...this.#W})}$omitTables(){return new q0({...this.#W})}$pickTables(){return new q0({...this.#W})}}function JZ(W){return Q1(W)&&Q1(W.config)&&Q1(W.driver)&&Q1(W.executor)&&Q1(W.dialect)}class G7{#W;constructor(W){this.#W=k(W)}async execute(W,$){return this.#W.executor.provideConnection(async(Z)=>{let J=this.#W.executor.withConnectionProvider(new IW(Z)),X=new Q0({...this.#W,executor:J});return await W(X)},k({signal:$?.signal}))}}class T4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new T4({...this.#W,accessMode:W})}setIsolationLevel(W){return new T4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:Z,...J}=this.#W,X={isolationLevel:$,accessMode:Z};return s6(X),this.#W.executor.provideConnection(async(Y)=>{let M={isCommitted:!1,isRolledBack:!1},G=new i0(this.#W.executor.withConnectionProvider(new IW(Y)),M),V=new q0({...J,executor:G}),R=!1;try{await this.#W.driver.beginTransaction(Y,X),R=!0;let P=await W(V);return await this.#W.driver.commitTransaction(Y),M.isCommitted=!0,P}catch(P){if(R)await this.#W.driver.rollbackTransaction(Y),M.isRolledBack=!0;throw P}})}}class f4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new f4({...this.#W,accessMode:W})}setIsolationLevel(W){return new f4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...Z}=this.#W,J={isolationLevel:W,accessMode:$};s6(J);let X=await m8(this.#W.executor);return await this.#W.driver.beginTransaction(X.connection,J),new X0({...Z,connection:X,executor:this.#W.executor.withConnectionProvider(new IW(X.connection))})}}class X0 extends q0{#W;#$;#Z;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new i0(W.executor,$)};let{connection:Z,...J}=W;super(J);this.#W=k(W),this.#Z=$;let X=W1();this.#$=(Y)=>W.executor.compileQuery(Y,X)}get isCommitted(){return this.#Z.isCommitted}get isRolledBack(){return this.#Z.isRolledBack}commit(){return D8(this.#Z),new JW(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#Z.isCommitted=!0,this.#W.connection.release()})}rollback(){return D8(this.#Z),new JW(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#Z.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}rollbackToSavepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}releaseSavepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}withPlugin(W){return new X0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new X0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new X0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new X0({...this.#W})}$extendTables(){return new X0({...this.#W})}$omitTables(){return new X0({...this.#W})}$pickTables(){return new X0({...this.#W})}}class JW{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function D8(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class i0{#W;#$;constructor(W,$){this.#W=W instanceof i0?W.#W:W,this.#$=$}get adapter(){return this.#W.adapter}get plugins(){return this.#W.plugins}transformQuery(W,$){return this.#W.transformQuery(W,$)}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#W.provideConnection(W,$)}executeQuery(W,$){return D8(this.#$),this.#W.executeQuery(W,$)}stream(W,$,Z){return D8(this.#$),this.#W.stream(W,$,Z)}withConnectionProvider(W){return new i0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new i0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new i0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new i0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new i0(this.#W.withoutPlugins(),this.#$)}}class yW{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new M7(this,W)}$castTo(){return new yW({...this.#W})}$notNull(){return new yW(this.#W)}withPlugin(W){return new yW({...this.#W,plugins:this.#W.plugins!==void 0?k([...this.#W.plugins,W]):k([W])})}toOperationNode(){return this.#Z(this.#$())}compile(W){return this.#X(this.#$(W))}async execute(W,$){let Z=this.#$(W);return Z.executeQuery(this.#X(Z),$)}#$(W){let $=W!==void 0?W.getExecutor():J8;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#Z(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#X(W){return W.compileQuery(this.#Z(W),this.#W.queryId)}}function t0(W){return new yW(W)}class M7{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var k8=Object.assign((W,...$)=>{return t0({queryId:W1(),rawNode:X1.create(W,$?.map(L7)??[])})},{ref(W){return t0({queryId:W1(),rawNode:X1.createWithChild(p1(W))})},val(W){return t0({queryId:W1(),rawNode:X1.createWithChild(M1(W))})},table(W){return t0({queryId:W1(),rawNode:X1.createWithChild(Z1(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",t0({queryId:W1(),rawNode:X1.create($,W.map(l.create))})},lit(W){return t0({queryId:W1(),rawNode:X1.createWithChild(D1.createImmediate(W))})},raw(W){return t0({queryId:W1(),rawNode:X1.createWithSql(W)})},join(W,$=k8`, `){let Z=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let X=0;X<W.length;++X)if(Z[2*X]=L7(W[X]),X!==W.length-1)Z[2*X+1]=J;return t0({queryId:W1(),rawNode:X1.createWithChildren(Z)})}});function L7(W){if(G1(W))return W.toOperationNode();return M1(W)}class r6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=k({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var XZ=/'/g,YZ=/['"]/g;class o6 extends r6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),k({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!S1.is(this.parentNode)&&!C1.is(this.parentNode)&&!w0.is(this.parentNode)&&!z4.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("select"),W.distinctOn)this.append(" "),this.compileDistinctOn(W.distinctOn);if(W.frontModifiers?.length)this.append(" "),this.compileList(W.frontModifiers," ");if(W.top)this.append(" "),this.visitNode(W.top);if(W.selections)this.append(" "),this.compileList(W.selections);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.groupBy)this.append(" "),this.visitNode(W.groupBy);if(W.having)this.append(" "),this.visitNode(W.having);if(W.setOperations)this.append(" "),this.compileList(W.setOperations," ");if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.offset)this.append(" "),this.visitNode(W.offset);if(W.fetch)this.append(" "),this.visitNode(W.fetch);if(W.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers(W.endModifiers)," ");if($)this.append(")")}visitFrom(W){this.append("from "),this.compileList(W.froms)}visitSelection(W){this.visitNode(W.selection)}visitColumn(W){this.visitNode(W.column)}compileDistinctOn(W){this.append("distinct on ("),this.compileList(W),this.append(")")}compileList(W,$=", "){let Z=W.length-1;for(let J=0;J<=Z;J++)if(this.visitNode(W[J]),J<Z)this.append($)}visitWhere(W){this.append("where "),this.visitNode(W.where)}visitHaving(W){this.append("having "),this.visitNode(W.having)}visitInsertQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append(W.replace?"replace":"insert"),W.orAction)this.append(" "),this.visitNode(W.orAction);if(W.top)this.append(" "),this.visitNode(W.top);if(W.into)this.append(" into "),this.visitNode(W.into);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.output)this.append(" "),this.visitNode(W.output);if(W.values)this.append(" "),this.visitNode(W.values);if(W.defaultValues)this.append(" "),this.append("default values");if(W.onConflict)this.append(" "),this.visitNode(W.onConflict);if(W.onDuplicateKey)this.append(" "),this.visitNode(W.onDuplicateKey);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitValues(W){this.append("values "),this.compileList(W.values)}visitDeleteQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("delete "),W.top)this.visitNode(W.top),this.append(" ");if(this.visitNode(W.from),W.output)this.append(" "),this.visitNode(W.output);if(W.using)this.append(" "),this.visitNode(W.using);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitReturning(W){this.append("returning "),this.compileList(W.selections)}visitAlias(W){this.visitNode(W.node),this.append(" as "),this.visitNode(W.alias)}visitReference(W){if(W.table)this.visitNode(W.table),this.append(".");this.visitNode(W.column)}visitSelectAll(W){this.append("*")}visitIdentifier(W){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(W),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(W){if(!a(W.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(W.name))}visitAnd(W){this.visitNode(W.left),this.append(" and "),this.visitNode(W.right)}visitOr(W){this.visitNode(W.left),this.append(" or "),this.visitNode(W.right)}visitValue(W){if(W.immediate)this.appendImmediateValue(W.value);else this.appendValue(W.value)}visitValueList(W){this.append("("),this.compileList(W.values),this.append(")")}visitTuple(W){this.append("("),this.compileList(W.values),this.append(")")}visitPrimitiveValueList(W){this.append("(");let{values:$}=W;for(let Z=0;Z<$.length;++Z)if(this.appendValue($[Z]),Z!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(kZ[W.joinType]),this.append(" "),this.visitNode(W.table),W.on)this.append(" "),this.visitNode(W.on)}visitOn(W){this.append("on "),this.visitNode(W.on)}visitRaw(W){let{sqlFragments:$,parameters:Z}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),Z.length>J)this.visitNode(Z[J])}visitOperator(W){this.append(W.operator)}visitTable(W){this.visitNode(W.table)}visitSchemableIdentifier(W){if(W.schema)this.visitNode(W.schema),this.append(".");this.visitNode(W.identifier)}visitCreateTable(W){if(this.append("create "),W.frontModifiers?.length)this.compileList(W.frontModifiers," "),this.append(" ");if(W.temporary)this.append("temporary ");if(this.append("table "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.table),!W.selectQuery)this.append(" ("),this.compileList([...W.columns,...W.constraints??[],...W.indexes??[]]),this.append(")");if(W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ");if(W.selectQuery)this.append(" as "),this.visitNode(W.selectQuery)}visitColumnDefinition(W){if(W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.column),this.append(" "),this.visitNode(W.dataType),W.unsigned)this.append(" unsigned");if(W.frontModifiers&&W.frontModifiers.length>0)this.append(" "),this.compileList(W.frontModifiers," ");if(W.generated)this.append(" "),this.visitNode(W.generated);if(W.identity)this.append(" identity");if(W.defaultTo)this.append(" "),this.visitNode(W.defaultTo);if(W.notNull)this.append(" not null");if(W.unique)this.append(" unique");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.primaryKey)this.append(" primary key");if(W.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(W.references)this.append(" "),this.visitNode(W.references);if(W.check)this.append(" "),this.visitNode(W.check);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(W){if(this.append("references "),this.visitNode(W.table),this.append(" ("),this.compileList(W.columns),this.append(")"),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate)}visitDropTable(W){if(this.append("drop "),W.temporary)this.append("temporary ");if(this.append("table "),W.ifExists)this.append("if exists ");if(this.visitNode(W.table),W.cascade)this.append(" cascade")}visitDataType(W){this.append(W.dataType)}visitOrderBy(W){this.append("order by "),this.compileList(W.items)}visitOrderByItem(W){if(this.visitNode(W.orderBy),W.collation)this.append(" "),this.visitNode(W.collation);if(W.direction)this.append(" "),this.visitNode(W.direction);if(W.nulls)this.append(" nulls "),this.append(W.nulls)}visitGroupBy(W){this.append("group by "),this.compileList(W.items)}visitGroupByItem(W){this.visitNode(W.groupBy)}visitUpdateQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("update "),W.top)this.visitNode(W.top),this.append(" ");if(W.table)this.visitNode(W.table),this.append(" ");if(this.append("set "),W.updates)this.compileList(W.updates);if(W.output)this.append(" "),this.visitNode(W.output);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins){if(!W.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(W.joins," ")}if(W.where)this.append(" "),this.visitNode(W.where);if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitColumnUpdate(W){this.visitNode(W.column),this.append(" = "),this.visitNode(W.value)}visitLimit(W){this.append("limit "),this.visitNode(W.limit)}visitOffset(W){this.append("offset "),this.visitNode(W.offset)}visitOnConflict(W){if(this.append("on conflict"),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");else if(W.constraint)this.append(" on constraint "),this.visitNode(W.constraint);else if(W.indexExpression)this.append(" ("),this.visitNode(W.indexExpression),this.append(")");if(W.indexWhere)this.append(" "),this.visitNode(W.indexWhere);if(W.doNothing===!0)this.append(" do nothing");else if(W.updates){if(this.append(" do update set "),this.compileList(W.updates),W.updateWhere)this.append(" "),this.visitNode(W.updateWhere)}}visitOnDuplicateKey(W){this.append("on duplicate key update "),this.compileList(W.updates)}visitCreateIndex(W){if(this.append("create "),W.unique)this.append("unique ");if(this.append("index "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.using)this.append(" using "),this.visitNode(W.using);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.where)this.append(" "),this.visitNode(W.where)}visitDropIndex(W){if(this.append("drop index "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.cascade)this.append(" cascade")}visitCreateSchema(W){if(this.append("create schema "),W.ifNotExists)this.append("if not exists ");this.visitNode(W.schema)}visitDropSchema(W){if(this.append("drop schema "),W.ifExists)this.append("if exists ");if(this.visitNode(W.schema),W.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("primary key ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}buildDeferrable(W){if(W.deferrable!==void 0)if(W.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(W.initiallyDeferred!==void 0)if(W.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("unique"),W.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}visitCheckConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("check ("),this.visitNode(W.expression),this.append(")")}visitForeignKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("foreign key ("),this.compileList(W.columns),this.append(") "),this.visitNode(W.references),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate);this.buildDeferrable(W)}visitList(W){this.compileList(W.items)}visitWith(W){if(this.append("with "),W.recursive)this.append("recursive ");this.compileList(W.expressions)}visitCommonTableExpression(W){if(this.visitNode(W.name),this.append(" as "),K8(W.materialized)){if(!W.materialized)this.append("not ");this.append("materialized ")}this.visitNode(W.expression)}visitCommonTableExpressionName(W){if(this.visitNode(W.table),W.columns)this.append("("),this.compileList(W.columns),this.append(")")}visitAlterTable(W){if(this.append("alter table "),this.visitNode(W.table),this.append(" "),W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema);if(W.addConstraint)this.visitNode(W.addConstraint);if(W.dropConstraint)this.visitNode(W.dropConstraint);if(W.renameConstraint)this.visitNode(W.renameConstraint);if(W.columnAlterations)this.compileColumnAlterations(W.columnAlterations);if(W.addIndex)this.visitNode(W.addIndex);if(W.dropIndex)this.visitNode(W.dropIndex)}visitAddColumn(W){this.append("add column "),this.visitNode(W.column)}visitRenameColumn(W){this.append("rename column "),this.visitNode(W.column),this.append(" to "),this.visitNode(W.renameTo)}visitDropColumn(W){if(this.append("drop column "),W.ifExists)this.append("if exists ");this.visitNode(W.column)}visitAlterColumn(W){if(this.append("alter column "),this.visitNode(W.column),this.append(" "),W.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(W.dataType),W.dataTypeExpression)this.append("using "),this.visitNode(W.dataTypeExpression)}if(W.setDefault)this.append("set default "),this.visitNode(W.setDefault);if(W.dropDefault)this.append("drop default");if(W.setNotNull)this.append("set not null");if(W.dropNotNull)this.append("drop not null")}visitModifyColumn(W){this.append("modify column "),this.visitNode(W.column)}visitAddConstraint(W){this.append("add "),this.visitNode(W.constraint)}visitDropConstraint(W){if(this.append("drop constraint "),W.ifExists)this.append("if exists ");if(this.visitNode(W.constraintName),W.modifier==="cascade")this.append(" cascade");else if(W.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(W){this.append("rename constraint "),this.visitNode(W.oldName),this.append(" to "),this.visitNode(W.newName)}visitSetOperation(W){if(this.append(W.operator),this.append(" "),W.all)this.append("all ");this.visitNode(W.expression)}visitCreateView(W){if(this.append("create "),W.orReplace)this.append("or replace ");if(W.materialized)this.append("materialized ");if(W.temporary)this.append("temporary ");if(this.append("view "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),this.append(" "),W.columns)this.append("("),this.compileList(W.columns),this.append(") ");if(W.as)this.append("as "),this.visitNode(W.as)}visitRefreshMaterializedView(W){if(this.append("refresh materialized view "),W.concurrently)this.append("concurrently ");if(this.visitNode(W.name),W.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(W){if(this.append("drop "),W.materialized)this.append("materialized ");if(this.append("view "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.cascade)this.append(" cascade")}visitGenerated(W){if(this.append("generated "),W.always)this.append("always ");if(W.byDefault)this.append("by default ");if(this.append("as "),W.identity)this.append("identity");if(W.expression)this.append("("),this.visitNode(W.expression),this.append(")");if(W.stored)this.append(" stored")}visitDefaultValue(W){this.append("default "),this.visitNode(W.defaultValue)}visitSelectModifier(W){if(W.rawModifier)this.visitNode(W.rawModifier);else this.append(HZ[W.modifier]);if(W.of)this.append(" of "),this.compileList(W.of,", ")}visitCreateType(W){if(this.append("create type "),this.visitNode(W.name),W.enum)this.append(" as enum "),this.visitNode(W.enum)}visitDropType(W){if(this.append("drop type "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.additionalNames?.length)this.append(", "),this.compileList(W.additionalNames);if(W.cascade)this.append(" cascade")}visitAlterType(W){if(this.append("alter type "),this.visitNode(W.name),this.append(" "),W.addValue)this.visitNode(W.addValue);else if(W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);else if(W.renameValue)this.visitNode(W.renameValue);else if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema)}visitAddValue(W){if(this.append("add value "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.value),W.neighborValue)this.append(W.isBefore?" before ":" after "),this.visitNode(W.neighborValue)}visitRenameValue(W){this.append("rename value "),this.visitNode(W.oldValue),this.append(" to "),this.visitNode(W.newValue)}visitExplain(W){if(this.append("explain"),W.options||W.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),W.options){if(this.visitNode(W.options),W.format)this.append(this.getExplainOptionsDelimiter())}if(W.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(W.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(W){this.append("default")}visitAggregateFunction(W){if(this.append(W.func),this.append("("),W.distinct)this.append("distinct ");if(this.compileList(W.aggregated),W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(this.append(")"),W.withinGroup)this.append(" within group ("),this.visitNode(W.withinGroup),this.append(")");if(W.filter)this.append(" filter("),this.visitNode(W.filter),this.append(")");if(W.over)this.append(" "),this.visitNode(W.over)}visitOver(W){if(this.append("over("),W.partitionBy){if(this.visitNode(W.partitionBy),W.orderBy)this.append(" ")}if(W.orderBy)this.visitNode(W.orderBy);this.append(")")}visitPartitionBy(W){this.append("partition by "),this.compileList(W.items)}visitPartitionByItem(W){this.visitNode(W.partitionBy)}visitBinaryOperation(W){this.visitNode(W.leftOperand),this.append(" "),this.visitNode(W.operator),this.append(" "),this.visitNode(W.rightOperand)}visitUnaryOperation(W){if(this.visitNode(W.operator),!this.isMinusOperator(W.operator))this.append(" ");this.visitNode(W.operand)}isMinusOperator(W){return r1.is(W)&&W.operator==="-"}visitUsing(W){this.append("using "),this.compileList(W.tables)}visitFunction(W){this.append(W.func),this.append("("),this.compileList(W.arguments),this.append(")")}visitCase(W){if(this.append("case"),W.value)this.append(" "),this.visitNode(W.value);if(W.when)this.append(" "),this.compileList(W.when," ");if(W.else)this.append(" else "),this.visitNode(W.else);if(this.append(" end"),W.isStatement)this.append(" case")}visitWhen(W){if(this.append("when "),this.visitNode(W.condition),W.result)this.append(" then "),this.visitNode(W.result)}visitJSONReference(W){this.visitNode(W.reference),this.visitNode(W.traversal)}visitJSONPath(W){if(W.inOperator)this.visitNode(W.inOperator);this.append("'$");for(let $ of W.pathLegs)this.visitNode($);this.append("'")}visitJSONPathLeg(W){let $=W.type==="ArrayLocation",Z=String(W.value);if($)this.append("["),this.append(this.sanitizeStringLiteral(Z)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(Z)),this.append('"')}visitJSONOperatorChain(W){for(let $=0,Z=W.values.length;$<Z;$++){if($===Z-1)this.visitNode(W.operator);else this.append("->");this.visitNode(W.values[$])}}visitMergeQuery(W){if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("merge "),W.top)this.visitNode(W.top),this.append(" ");if(this.append("into "),this.visitNode(W.into),W.using)this.append(" "),this.visitNode(W.using);if(W.whens)this.append(" "),this.compileList(W.whens," ");if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.output)this.append(" "),this.visitNode(W.output);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitMatched(W){if(W.not)this.append("not ");if(this.append("matched"),W.bySource)this.append(" by source")}visitAddIndex(W){if(!this.parentNode||!C1.is(this.parentNode))this.append("add ");if(W.unique)this.append("unique ");if(this.append("index "),this.visitNode(W.name),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.using)this.append(" using "),this.visitNode(W.using)}visitCast(W){this.append("cast("),this.visitNode(W.expression),this.append(" as "),this.visitNode(W.dataType),this.append(")")}visitFetch(W){this.append("fetch next "),this.visitNode(W.rowCount),this.append(` rows ${W.modifier}`)}visitOutput(W){this.append("output "),this.compileList(W.selections)}visitTop(W){if(this.append(`top(${W.expression})`),W.modifiers)this.append(` ${W.modifiers}`)}visitOrAction(W){this.append(W.action)}visitCollate(W){this.append("collate "),this.visitNode(W.collation)}append(W){this.#W+=W}appendValue(W){this.addParameter(W),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(W){let $=this.getLeftIdentifierWrapper(),Z=this.getRightIdentifierWrapper(),J="";for(let X of W)if(J+=X,X===$)J+=$;else if(X===Z)J+=Z;return J}sanitizeStringLiteral(W){return W.replace(XZ,"''")}sanitizeJSONPathMemberValue(W){return W.replace(YZ,($)=>$==="'"?"''":"\\\"")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(a(W))this.appendStringLiteral(W);else if(d0(W)||K8(W)||h8(W))this.append(W.toString());else if(E8(W))this.append("null");else if(t9(W))this.appendImmediateValue(W.toISOString());else throw Error(`invalid immediate value ${W}`)}appendStringLiteral(W){this.append("'"),this.append(this.sanitizeStringLiteral(W)),this.append("'")}sortSelectModifiers(W){return k(W.toSorted(($,Z)=>$.modifier&&Z.modifier?K7[$.modifier]-K7[Z.modifier]:1))}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var HZ=k({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),K7=k({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),kZ=k({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var gW=k({raw(W,$=[]){return k({sql:W,query:X1.createWithSql(W),parameters:k($),queryId:W1()})}});class e6{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class W9{transformQuery(W){return W.node}async transformResult(W){return W.result}}var Z9="kysely_migration",A4="kysely_migration_lock",GZ=!1,$9="migration_lock",GQ=k({__noMigrations__:!0});class J9{#W;constructor(W){this.#W=k(W)}async getMigrations(){let $=await this.#L(this.#X)?await this.#W.db.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#P()).map(({name:J,...X})=>{let Y=$.find((M)=>M.name===J);return{name:J,migration:X,executedAt:Y?new Date(Y.timestamp):void 0}})}async migrateToLatest(W){return this.#$(()=>({direction:"Up",step:1/0}),W)}async migrateTo(W,$){return this.#$(({migrations:Z,executedMigrations:J,pendingMigrations:X})=>{if(Q1(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!Z.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Y=J.indexOf(W),M=X.findIndex((G)=>G.name===W);if(Y!==-1)return{direction:"Down",step:J.length-Y-1};if(M!==-1)return{direction:"Up",step:M+1};throw Error(`migration "${W}" isn't executed or pending`)},$)}async migrateUp(W){return this.#$(()=>({direction:"Up",step:1}),W)}async migrateDown(W){return this.#$(()=>({direction:"Down",step:1}),W)}async#$(W,$){try{return await this.#H(),await this.#G(),await this.#K(),await this.#z(),await this.#F(W,$)}catch(Z){if(Z instanceof j4)return Z.resultSet;return{error:Z}}}get#Z(){return this.#W.migrationTableSchema}get#X(){return this.#W.migrationTableName??Z9}get#Y(){return this.#W.migrationLockTableName??A4}get#k(){return this.#W.allowUnorderedMigrations??GZ}get#J(){if(this.#Z)return new V0(this.#Z);return new W9}async#H(){if(!this.#Z)return;if(await this.#M())return;try{await this.#U(this.#W.db.schema.createSchema(this.#Z))}catch($){if(!await this.#M())throw $}}async#G(){if(await this.#L(this.#X))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#X).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#L(this.#X))throw $}}async#K(){if(await this.#L(this.#Y))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#Y).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#L(this.#Y))throw $}}async#z(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#J).insertInto(this.#Y).values({id:$9,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#M(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#Z)}async#L(W){let $=this.#Z;return(await this.#W.db.introspection.getTables({withInternalKyselyTables:!0})).some((J)=>J.name===W&&(!$||J.schema===$))}async#V(){return!!await this.#W.db.withPlugin(this.#J).selectFrom(this.#Y).where("id","=",$9).select("id").executeTakeFirst()}async#F(W,$){let Z=this.#W.db.getExecutor().adapter,J=k({lockTable:this.#W.migrationLockTableName??A4,lockRowId:$9,lockTableSchema:this.#W.migrationTableSchema}),X=async(M)=>{try{await Z.acquireMigrationLock(M,J);let G=await this.#R(M);if(G.migrations.length===0)return{results:[]};let{direction:V,step:R}=W(G);if(R<=0)return{results:[]};if(V==="Down")return await this.#_(M,G,R);else if(V==="Up")return await this.#v(M,G,R);return{results:[]}}finally{await Z.releaseMigrationLock(M,J)}},Y=$?.disableTransactions??this.#W.disableTransactions;if(this.#W.db.isTransaction){if(!Z.supportsTransactionalDdl)throw Error("Transactional DDL is not supported in this dialect. Passing a transaction to this migrator would result in failure or unexpected behavior.");if(Y)throw Error("`disableTransactions` is true but the migrator was given a transaction. Passing a transaction to this migrator would result in failure or unexpected behavior.");return X(this.#W.db)}if(Z.supportsTransactionalDdl&&!Y)return this.#W.db.transaction().execute(X);return this.#W.db.connection().execute(X)}async#R(W){let $=await this.#P(),Z=await this.#w(W);if(this.#Q($,Z),!this.#k)this.#S($,Z);let J=this.#D($,Z);return k({migrations:$,executedMigrations:Z,lastMigration:a9(Z),pendingMigrations:J})}#D(W,$){return W.filter((Z)=>{return!$.includes(Z.name)})}async#P(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#w(W){let $=await W.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute(),Z=this.#W.nameComparator||((J,X)=>J.localeCompare(X));return $.sort((J,X)=>{if(J.timestamp===X.timestamp)return Z(J.name,X.name);return new Date(J.timestamp).getTime()-new Date(X.timestamp).getTime()}).map((J)=>J.name)}#Q(W,$){for(let Z of $)if(!W.some((J)=>J.name===Z))throw Error(`corrupted migrations: previously executed migration ${Z} is missing`)}#S(W,$){for(let Z=0;Z<$.length;++Z)if(W[Z].name!==$[Z])throw Error(`corrupted migrations: expected previously executed migration ${$[Z]} to be at index ${Z} but ${W[Z].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#_(W,$,Z){let J=$.executedMigrations.toReversed().slice(0,Z).map((Y)=>{return $.migrations.find((M)=>M.name===Y)}),X=J.map((Y)=>{return{migrationName:Y.name,direction:"Down",status:"NotExecuted"}});for(let Y=0;Y<X.length;++Y){let M=J[Y];try{if(M.down)await M.down(W),await W.withPlugin(this.#J).deleteFrom(this.#X).where("name","=",M.name).execute(),X[Y]={migrationName:M.name,direction:"Down",status:"Success"}}catch(G){throw X[Y]={migrationName:M.name,direction:"Down",status:"Error"},new j4({error:G,results:X})}}return{results:X}}async#v(W,$,Z){let X=$.pendingMigrations.slice(0,Z).map((Y)=>{return{migrationName:Y.name,direction:"Up",status:"NotExecuted"}});for(let Y=0;Y<X.length;Y++){let M=$.pendingMigrations[Y];try{await M.up(W),await W.withPlugin(this.#J).insertInto(this.#X).values({name:M.name,timestamp:new Date().toISOString()}).execute(),X[Y]={migrationName:M.name,direction:"Up",status:"Success"}}catch(G){throw X[Y]={migrationName:M.name,direction:"Up",status:"Error"},new j4({error:G,results:X})}}return{results:X}}async#U(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class j4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}class mW{#W;constructor(W){this.#W=W}async getSchemas(){return(await this.#W.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(($)=>({name:$.nspname}))}async getTables(W={withInternalKyselyTables:!1}){let $=this.#W.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",k8`col_description(a.attrelid, a.attnum)`.as("column_description"),k8`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p","f"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k8`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!W.withInternalKyselyTables)$=$.where("c.relname","!=",Z9).where("c.relname","!=",A4);let Z=await $.execute();return this.#$(Z)}#$(W){let $=[],Z=new Map;for(let J of W){let X=Z.get(J.schema);if(!X)X=new Map,Z.set(J.schema,X);let Y=X.get(J.table);if(!Y)Y=k({columns:[],isForeign:J.table_type==="f",isView:J.table_type==="v",name:J.table,schema:J.schema}),X.set(J.table,Y),$.push(Y);Y.columns.push(k({comment:J.column_description??void 0,dataType:J.type,dataTypeSchema:J.type_schema,hasDefaultValue:J.has_default,isAutoIncrementing:J.auto_incrementing!==null,isNullable:!J.not_null,name:J.column}))}return $}}var MZ=/"/g;class cW extends o6{sanitizeIdentifier(W){return W.replace(MZ,'""')}}var LZ=BigInt("3853314791062309107");class uW extends e6{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k8`select pg_advisory_xact_lock(${k8.lit(LZ)})`.execute(W)}async releaseMigrationLock(W,$){}}var{create:KZ,defineProperty:YW,getOwnPropertyDescriptor:zZ,getOwnPropertyNames:UZ,getPrototypeOf:VZ}=Object,PZ=Object.prototype.hasOwnProperty,FZ=(W,$,Z)=>($ in W)?YW(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,U=(W,$)=>YW(W,"name",{value:$,configurable:!0}),d1=(W,$)=>()=>(W&&($=W(W=0)),$),o=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),S0=(W,$)=>{for(var Z in $)YW(W,Z,{get:$[Z],enumerable:!0})},D7=(W,$,Z,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let X of UZ($))!PZ.call(W,X)&&X!==Z&&YW(W,X,{get:()=>$[X],enumerable:!(J=zZ($,X))||J.enumerable});return W},Q8=(W,$,Z)=>(Z=W!=null?KZ(VZ(W)):{},D7($||!W||!W.__esModule?YW(Z,"default",{value:W,enumerable:!0}):Z,W)),B1=(W)=>D7(YW({},"__esModule",{value:!0}),W),t=(W,$,Z)=>FZ(W,typeof $!="symbol"?$+"":$,Z),RZ=o((W)=>{u(),W.byteLength=V,W.toByteArray=P,W.fromByteArray=S;var $=[],Z=[],J=typeof Uint8Array<"u"?Uint8Array:Array,X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Y=0,M=X.length;Y<M;++Y)$[Y]=X[Y],Z[X.charCodeAt(Y)]=Y;var Y,M;Z[45]=62,Z[95]=63;function G(F){var L=F.length;if(L%4>0)throw Error("Invalid string. Length must be a multiple of 4");var Q=F.indexOf("=");Q===-1&&(Q=L);var _=Q===L?0:4-Q%4;return[Q,_]}U(G,"getLens");function V(F){var L=G(F),Q=L[0],_=L[1];return(Q+_)*3/4-_}U(V,"byteLength");function R(F,L,Q){return(L+Q)*3/4-Q}U(R,"_byteLength");function P(F){var L,Q=G(F),_=Q[0],v=Q[1],T=new J(R(F,_,v)),x=0,q=v>0?_-4:_,E;for(E=0;E<q;E+=4)L=Z[F.charCodeAt(E)]<<18|Z[F.charCodeAt(E+1)]<<12|Z[F.charCodeAt(E+2)]<<6|Z[F.charCodeAt(E+3)],T[x++]=L>>16&255,T[x++]=L>>8&255,T[x++]=L&255;return v===2&&(L=Z[F.charCodeAt(E)]<<2|Z[F.charCodeAt(E+1)]>>4,T[x++]=L&255),v===1&&(L=Z[F.charCodeAt(E)]<<10|Z[F.charCodeAt(E+1)]<<4|Z[F.charCodeAt(E+2)]>>2,T[x++]=L>>8&255,T[x++]=L&255),T}U(P,"toByteArray");function w(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}U(w,"tripletToBase64");function D(F,L,Q){for(var _,v=[],T=L;T<Q;T+=3)_=(F[T]<<16&16711680)+(F[T+1]<<8&65280)+(F[T+2]&255),v.push(w(_));return v.join("")}U(D,"encodeChunk");function S(F){for(var L,Q=F.length,_=Q%3,v=[],T=16383,x=0,q=Q-_;x<q;x+=T)v.push(D(F,x,x+T>q?q:x+T));return _===1?(L=F[Q-1],v.push($[L>>2]+$[L<<4&63]+"==")):_===2&&(L=(F[Q-2]<<8)+F[Q-1],v.push($[L>>10]+$[L>>4&63]+$[L<<2&63]+"=")),v.join("")}U(S,"fromByteArray")}),DZ=o((W)=>{u(),W.read=function($,Z,J,X,Y){var M,G,V=Y*8-X-1,R=(1<<V)-1,P=R>>1,w=-7,D=J?Y-1:0,S=J?-1:1,F=$[Z+D];for(D+=S,M=F&(1<<-w)-1,F>>=-w,w+=V;w>0;M=M*256+$[Z+D],D+=S,w-=8);for(G=M&(1<<-w)-1,M>>=-w,w+=X;w>0;G=G*256+$[Z+D],D+=S,w-=8);if(M===0)M=1-P;else{if(M===R)return G?NaN:(F?-1:1)*(1/0);G=G+Math.pow(2,X),M=M-P}return(F?-1:1)*G*Math.pow(2,M-X)},W.write=function($,Z,J,X,Y,M){var G,V,R,P=M*8-Y-1,w=(1<<P)-1,D=w>>1,S=Y===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=X?0:M-1,L=X?1:-1,Q=Z<0||Z===0&&1/Z<0?1:0;for(Z=Math.abs(Z),isNaN(Z)||Z===1/0?(V=isNaN(Z)?1:0,G=w):(G=Math.floor(Math.log(Z)/Math.LN2),Z*(R=Math.pow(2,-G))<1&&(G--,R*=2),G+D>=1?Z+=S/R:Z+=S*Math.pow(2,1-D),Z*R>=2&&(G++,R/=2),G+D>=w?(V=0,G=w):G+D>=1?(V=(Z*R-1)*Math.pow(2,Y),G=G+D):(V=Z*Math.pow(2,D-1)*Math.pow(2,Y),G=0));Y>=8;$[J+F]=V&255,F+=L,V/=256,Y-=8);for(G=G<<Y|V,P+=Y;P>0;$[J+F]=G&255,F+=L,G/=256,P-=8);$[J+F-L]|=Q*128}}),wZ=o((W)=>{u();var $=RZ(),Z=DZ(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=G,W.SlowBuffer=v,W.INSPECT_MAX_BYTES=50;var X=2147483647;W.kMaxLength=X,G.TYPED_ARRAY_SUPPORT=Y(),!G.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Y(){try{let H=new Uint8Array(1),K={foo:U(function(){return 42},"foo")};return Object.setPrototypeOf(K,Uint8Array.prototype),Object.setPrototypeOf(H,K),H.foo()===42}catch{return!1}}U(Y,"typedArraySupport"),Object.defineProperty(G.prototype,"parent",{enumerable:!0,get:U(function(){if(G.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(G.prototype,"offset",{enumerable:!0,get:U(function(){if(G.isBuffer(this))return this.byteOffset},"get")});function M(H){if(H>X)throw RangeError('The value "'+H+'" is invalid for option "size"');let K=new Uint8Array(H);return Object.setPrototypeOf(K,G.prototype),K}U(M,"createBuffer");function G(H,K,z){if(typeof H=="number"){if(typeof K=="string")throw TypeError('The "string" argument must be of type string. Received type number');return w(H)}return V(H,K,z)}U(G,"Buffer"),G.poolSize=8192;function V(H,K,z){if(typeof H=="string")return D(H,K);if(ArrayBuffer.isView(H))return F(H);if(H==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H);if(Y0(H,ArrayBuffer)||H&&Y0(H.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Y0(H,SharedArrayBuffer)||H&&Y0(H.buffer,SharedArrayBuffer)))return L(H,K,z);if(typeof H=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let h=H.valueOf&&H.valueOf();if(h!=null&&h!==H)return G.from(h,K,z);let j=Q(H);if(j)return j;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof H[Symbol.toPrimitive]=="function")return G.from(H[Symbol.toPrimitive]("string"),K,z);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H)}U(V,"from"),G.from=function(H,K,z){return V(H,K,z)},Object.setPrototypeOf(G.prototype,Uint8Array.prototype),Object.setPrototypeOf(G,Uint8Array);function R(H){if(typeof H!="number")throw TypeError('"size" argument must be of type number');if(H<0)throw RangeError('The value "'+H+'" is invalid for option "size"')}U(R,"assertSize");function P(H,K,z){return R(H),H<=0?M(H):K!==void 0?typeof z=="string"?M(H).fill(K,z):M(H).fill(K):M(H)}U(P,"alloc"),G.alloc=function(H,K,z){return P(H,K,z)};function w(H){return R(H),M(H<0?0:_(H)|0)}U(w,"allocUnsafe"),G.allocUnsafe=function(H){return w(H)},G.allocUnsafeSlow=function(H){return w(H)};function D(H,K){if((typeof K!="string"||K==="")&&(K="utf8"),!G.isEncoding(K))throw TypeError("Unknown encoding: "+K);let z=T(H,K)|0,h=M(z),j=h.write(H,K);return j!==z&&(h=h.slice(0,j)),h}U(D,"fromString");function S(H){let K=H.length<0?0:_(H.length)|0,z=M(K);for(let h=0;h<K;h+=1)z[h]=H[h]&255;return z}U(S,"fromArrayLike");function F(H){if(Y0(H,Uint8Array)){let K=new Uint8Array(H);return L(K.buffer,K.byteOffset,K.byteLength)}return S(H)}U(F,"fromArrayView");function L(H,K,z){if(K<0||H.byteLength<K)throw RangeError('"offset" is outside of buffer bounds');if(H.byteLength<K+(z||0))throw RangeError('"length" is outside of buffer bounds');let h;return K===void 0&&z===void 0?h=new Uint8Array(H):z===void 0?h=new Uint8Array(H,K):h=new Uint8Array(H,K,z),Object.setPrototypeOf(h,G.prototype),h}U(L,"fromArrayBuffer");function Q(H){if(G.isBuffer(H)){let K=_(H.length)|0,z=M(K);return z.length===0||H.copy(z,0,0,K),z}if(H.length!==void 0)return typeof H.length!="number"||rW(H.length)?M(0):S(H);if(H.type==="Buffer"&&Array.isArray(H.data))return S(H.data)}U(Q,"fromObject");function _(H){if(H>=X)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+X.toString(16)+" bytes");return H|0}U(_,"checked");function v(H){return+H!=H&&(H=0),G.alloc(+H)}U(v,"SlowBuffer"),G.isBuffer=U(function(H){return H!=null&&H._isBuffer===!0&&H!==G.prototype},"isBuffer"),G.compare=U(function(H,K){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),Y0(K,Uint8Array)&&(K=G.from(K,K.offset,K.byteLength)),!G.isBuffer(H)||!G.isBuffer(K))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(H===K)return 0;let z=H.length,h=K.length;for(let j=0,O=Math.min(z,h);j<O;++j)if(H[j]!==K[j]){z=H[j],h=K[j];break}return z<h?-1:h<z?1:0},"compare"),G.isEncoding=U(function(H){switch(String(H).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},"isEncoding"),G.concat=U(function(H,K){if(!Array.isArray(H))throw TypeError('"list" argument must be an Array of Buffers');if(H.length===0)return G.alloc(0);let z;if(K===void 0)for(K=0,z=0;z<H.length;++z)K+=H[z].length;let h=G.allocUnsafe(K),j=0;for(z=0;z<H.length;++z){let O=H[z];if(Y0(O,Uint8Array))j+O.length>h.length?(G.isBuffer(O)||(O=G.from(O)),O.copy(h,j)):Uint8Array.prototype.set.call(h,O,j);else if(G.isBuffer(O))O.copy(h,j);else throw TypeError('"list" argument must be an Array of Buffers');j+=O.length}return h},"concat");function T(H,K){if(G.isBuffer(H))return H.length;if(ArrayBuffer.isView(H)||Y0(H,ArrayBuffer))return H.byteLength;if(typeof H!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof H);let z=H.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&z===0)return 0;let j=!1;for(;;)switch(K){case"ascii":case"latin1":case"binary":return z;case"utf8":case"utf-8":return nW(H).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z*2;case"hex":return z>>>1;case"base64":return r4(H).length;default:if(j)return h?-1:nW(H).length;K=(""+K).toLowerCase(),j=!0}}U(T,"byteLength"),G.byteLength=T;function x(H,K,z){let h=!1;if((K===void 0||K<0)&&(K=0),K>this.length||((z===void 0||z>this.length)&&(z=this.length),z<=0)||(z>>>=0,K>>>=0,z<=K))return"";for(H||(H="utf8");;)switch(H){case"hex":return s(this,K,z);case"utf8":case"utf-8":return b(this,K,z);case"ascii":return d(this,K,z);case"latin1":case"binary":return J1(this,K,z);case"base64":return m(this,K,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s1(this,K,z);default:if(h)throw TypeError("Unknown encoding: "+H);H=(H+"").toLowerCase(),h=!0}}U(x,"slowToString"),G.prototype._isBuffer=!0;function q(H,K,z){let h=H[K];H[K]=H[z],H[z]=h}U(q,"swap"),G.prototype.swap16=U(function(){let H=this.length;if(H%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let K=0;K<H;K+=2)q(this,K,K+1);return this},"swap16"),G.prototype.swap32=U(function(){let H=this.length;if(H%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let K=0;K<H;K+=4)q(this,K,K+3),q(this,K+1,K+2);return this},"swap32"),G.prototype.swap64=U(function(){let H=this.length;if(H%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let K=0;K<H;K+=8)q(this,K,K+7),q(this,K+1,K+6),q(this,K+2,K+5),q(this,K+3,K+4);return this},"swap64"),G.prototype.toString=U(function(){let H=this.length;return H===0?"":arguments.length===0?b(this,0,H):x.apply(this,arguments)},"toString"),G.prototype.toLocaleString=G.prototype.toString,G.prototype.equals=U(function(H){if(!G.isBuffer(H))throw TypeError("Argument must be a Buffer");return this===H?!0:G.compare(this,H)===0},"equals"),G.prototype.inspect=U(function(){let H="",K=W.INSPECT_MAX_BYTES;return H=this.toString("hex",0,K).replace(/(.{2})/g,"$1 ").trim(),this.length>K&&(H+=" ... "),"<Buffer "+H+">"},"inspect"),J&&(G.prototype[J]=G.prototype.inspect),G.prototype.compare=U(function(H,K,z,h,j){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),!G.isBuffer(H))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof H);if(K===void 0&&(K=0),z===void 0&&(z=H?H.length:0),h===void 0&&(h=0),j===void 0&&(j=this.length),K<0||z>H.length||h<0||j>this.length)throw RangeError("out of range index");if(h>=j&&K>=z)return 0;if(h>=j)return-1;if(K>=z)return 1;if(K>>>=0,z>>>=0,h>>>=0,j>>>=0,this===H)return 0;let O=j-h,I=z-K,P1=Math.min(O,I),A1=this.slice(h,j),w1=H.slice(K,z);for(let F1=0;F1<P1;++F1)if(A1[F1]!==w1[F1]){O=A1[F1],I=w1[F1];break}return O<I?-1:I<O?1:0},"compare");function E(H,K,z,h,j){if(H.length===0)return-1;if(typeof z=="string"?(h=z,z=0):z>2147483647?z=2147483647:z<-2147483648&&(z=-2147483648),z=+z,rW(z)&&(z=j?0:H.length-1),z<0&&(z=H.length+z),z>=H.length){if(j)return-1;z=H.length-1}else if(z<0)if(j)z=0;else return-1;if(typeof K=="string"&&(K=G.from(K,h)),G.isBuffer(K))return K.length===0?-1:N(H,K,z,h,j);if(typeof K=="number")return K=K&255,typeof Uint8Array.prototype.indexOf=="function"?j?Uint8Array.prototype.indexOf.call(H,K,z):Uint8Array.prototype.lastIndexOf.call(H,K,z):N(H,[K],z,h,j);throw TypeError("val must be string, number or Buffer")}U(E,"bidirectionalIndexOf");function N(H,K,z,h,j){let O=1,I=H.length,P1=K.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(H.length<2||K.length<2)return-1;O=2,I/=2,P1/=2,z/=2}function A1(F1,h1){return O===1?F1[h1]:F1.readUInt16BE(h1*O)}U(A1,"read");let w1;if(j){let F1=-1;for(w1=z;w1<I;w1++)if(A1(H,w1)===A1(K,F1===-1?0:w1-F1)){if(F1===-1&&(F1=w1),w1-F1+1===P1)return F1*O}else F1!==-1&&(w1-=w1-F1),F1=-1}else for(z+P1>I&&(z=I-P1),w1=z;w1>=0;w1--){let F1=!0;for(let h1=0;h1<P1;h1++)if(A1(H,w1+h1)!==A1(K,h1)){F1=!1;break}if(F1)return w1}return-1}U(N,"arrayIndexOf"),G.prototype.includes=U(function(H,K,z){return this.indexOf(H,K,z)!==-1},"includes"),G.prototype.indexOf=U(function(H,K,z){return E(this,H,K,z,!0)},"indexOf"),G.prototype.lastIndexOf=U(function(H,K,z){return E(this,H,K,z,!1)},"lastIndexOf");function A(H,K,z,h){z=Number(z)||0;let j=H.length-z;h?(h=Number(h),h>j&&(h=j)):h=j;let O=K.length;h>O/2&&(h=O/2);let I;for(I=0;I<h;++I){let P1=parseInt(K.substr(I*2,2),16);if(rW(P1))return I;H[z+I]=P1}return I}U(A,"hexWrite");function f(H,K,z,h){return MW(nW(K,H.length-z),H,z,h)}U(f,"utf8Write");function B(H,K,z,h){return MW(E9(K),H,z,h)}U(B,"asciiWrite");function C(H,K,z,h){return MW(r4(K),H,z,h)}U(C,"base64Write");function c(H,K,z,h){return MW(h9(K,H.length-z),H,z,h)}U(c,"ucs2Write"),G.prototype.write=U(function(H,K,z,h){if(K===void 0)h="utf8",z=this.length,K=0;else if(z===void 0&&typeof K=="string")h=K,z=this.length,K=0;else if(isFinite(K))K=K>>>0,isFinite(z)?(z=z>>>0,h===void 0&&(h="utf8")):(h=z,z=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let j=this.length-K;if((z===void 0||z>j)&&(z=j),H.length>0&&(z<0||K<0)||K>this.length)throw RangeError("Attempt to write outside buffer bounds");h||(h="utf8");let O=!1;for(;;)switch(h){case"hex":return A(this,H,K,z);case"utf8":case"utf-8":return f(this,H,K,z);case"ascii":case"latin1":case"binary":return B(this,H,K,z);case"base64":return C(this,H,K,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return c(this,H,K,z);default:if(O)throw TypeError("Unknown encoding: "+h);h=(""+h).toLowerCase(),O=!0}},"write"),G.prototype.toJSON=U(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function m(H,K,z){return K===0&&z===H.length?$.fromByteArray(H):$.fromByteArray(H.slice(K,z))}U(m,"base64Slice");function b(H,K,z){z=Math.min(H.length,z);let h=[],j=K;for(;j<z;){let O=H[j],I=null,P1=O>239?4:O>223?3:O>191?2:1;if(j+P1<=z){let A1,w1,F1,h1;switch(P1){case 1:O<128&&(I=O);break;case 2:A1=H[j+1],(A1&192)===128&&(h1=(O&31)<<6|A1&63,h1>127&&(I=h1));break;case 3:A1=H[j+1],w1=H[j+2],(A1&192)===128&&(w1&192)===128&&(h1=(O&15)<<12|(A1&63)<<6|w1&63,h1>2047&&(h1<55296||h1>57343)&&(I=h1));break;case 4:A1=H[j+1],w1=H[j+2],F1=H[j+3],(A1&192)===128&&(w1&192)===128&&(F1&192)===128&&(h1=(O&15)<<18|(A1&63)<<12|(w1&63)<<6|F1&63,h1>65535&&h1<1114112&&(I=h1))}}I===null?(I=65533,P1=1):I>65535&&(I-=65536,h.push(I>>>10&1023|55296),I=56320|I&1023),h.push(I),j+=P1}return p(h)}U(b,"utf8Slice");var g=4096;function p(H){let K=H.length;if(K<=g)return String.fromCharCode.apply(String,H);let z="",h=0;for(;h<K;)z+=String.fromCharCode.apply(String,H.slice(h,h+=g));return z}U(p,"decodeCodePointsArray");function d(H,K,z){let h="";z=Math.min(H.length,z);for(let j=K;j<z;++j)h+=String.fromCharCode(H[j]&127);return h}U(d,"asciiSlice");function J1(H,K,z){let h="";z=Math.min(H.length,z);for(let j=K;j<z;++j)h+=String.fromCharCode(H[j]);return h}U(J1,"latin1Slice");function s(H,K,z){let h=H.length;(!K||K<0)&&(K=0),(!z||z<0||z>h)&&(z=h);let j="";for(let O=K;O<z;++O)j+=T$[H[O]];return j}U(s,"hexSlice");function s1(H,K,z){let h=H.slice(K,z),j="";for(let O=0;O<h.length-1;O+=2)j+=String.fromCharCode(h[O]+h[O+1]*256);return j}U(s1,"utf16leSlice"),G.prototype.slice=U(function(H,K){let z=this.length;H=~~H,K=K===void 0?z:~~K,H<0?(H+=z,H<0&&(H=0)):H>z&&(H=z),K<0?(K+=z,K<0&&(K=0)):K>z&&(K=z),K<H&&(K=H);let h=this.subarray(H,K);return Object.setPrototypeOf(h,G.prototype),h},"slice");function V1(H,K,z){if(H%1!==0||H<0)throw RangeError("offset is not uint");if(H+K>z)throw RangeError("Trying to access beyond buffer length")}U(V1,"checkOffset"),G.prototype.readUintLE=G.prototype.readUIntLE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H],j=1,O=0;for(;++O<K&&(j*=256);)h+=this[H+O]*j;return h},"readUIntLE"),G.prototype.readUintBE=G.prototype.readUIntBE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H+--K],j=1;for(;K>0&&(j*=256);)h+=this[H+--K]*j;return h},"readUIntBE"),G.prototype.readUint8=G.prototype.readUInt8=U(function(H,K){return H=H>>>0,K||V1(H,1,this.length),this[H]},"readUInt8"),G.prototype.readUint16LE=G.prototype.readUInt16LE=U(function(H,K){return H=H>>>0,K||V1(H,2,this.length),this[H]|this[H+1]<<8},"readUInt16LE"),G.prototype.readUint16BE=G.prototype.readUInt16BE=U(function(H,K){return H=H>>>0,K||V1(H,2,this.length),this[H]<<8|this[H+1]},"readUInt16BE"),G.prototype.readUint32LE=G.prototype.readUInt32LE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),(this[H]|this[H+1]<<8|this[H+2]<<16)+this[H+3]*16777216},"readUInt32LE"),G.prototype.readUint32BE=G.prototype.readUInt32BE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]*16777216+(this[H+1]<<16|this[H+2]<<8|this[H+3])},"readUInt32BE"),G.prototype.readBigUInt64LE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=K+this[++H]*256+this[++H]*65536+this[++H]*16777216,j=this[++H]+this[++H]*256+this[++H]*65536+z*16777216;return BigInt(h)+(BigInt(j)<<BigInt(32))},"readBigUInt64LE")),G.prototype.readBigUInt64BE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=K*16777216+this[++H]*65536+this[++H]*256+this[++H],j=this[++H]*16777216+this[++H]*65536+this[++H]*256+z;return(BigInt(h)<<BigInt(32))+BigInt(j)},"readBigUInt64BE")),G.prototype.readIntLE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H],j=1,O=0;for(;++O<K&&(j*=256);)h+=this[H+O]*j;return j*=128,h>=j&&(h-=Math.pow(2,8*K)),h},"readIntLE"),G.prototype.readIntBE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=K,j=1,O=this[H+--h];for(;h>0&&(j*=256);)O+=this[H+--h]*j;return j*=128,O>=j&&(O-=Math.pow(2,8*K)),O},"readIntBE"),G.prototype.readInt8=U(function(H,K){return H=H>>>0,K||V1(H,1,this.length),this[H]&128?(255-this[H]+1)*-1:this[H]},"readInt8"),G.prototype.readInt16LE=U(function(H,K){H=H>>>0,K||V1(H,2,this.length);let z=this[H]|this[H+1]<<8;return z&32768?z|4294901760:z},"readInt16LE"),G.prototype.readInt16BE=U(function(H,K){H=H>>>0,K||V1(H,2,this.length);let z=this[H+1]|this[H]<<8;return z&32768?z|4294901760:z},"readInt16BE"),G.prototype.readInt32LE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]|this[H+1]<<8|this[H+2]<<16|this[H+3]<<24},"readInt32LE"),G.prototype.readInt32BE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]<<24|this[H+1]<<16|this[H+2]<<8|this[H+3]},"readInt32BE"),G.prototype.readBigInt64LE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=this[H+4]+this[H+5]*256+this[H+6]*65536+(z<<24);return(BigInt(h)<<BigInt(32))+BigInt(K+this[++H]*256+this[++H]*65536+this[++H]*16777216)},"readBigInt64LE")),G.prototype.readBigInt64BE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=(K<<24)+this[++H]*65536+this[++H]*256+this[++H];return(BigInt(h)<<BigInt(32))+BigInt(this[++H]*16777216+this[++H]*65536+this[++H]*256+z)},"readBigInt64BE")),G.prototype.readFloatLE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),Z.read(this,H,!0,23,4)},"readFloatLE"),G.prototype.readFloatBE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),Z.read(this,H,!1,23,4)},"readFloatBE"),G.prototype.readDoubleLE=U(function(H,K){return H=H>>>0,K||V1(H,8,this.length),Z.read(this,H,!0,52,8)},"readDoubleLE"),G.prototype.readDoubleBE=U(function(H,K){return H=H>>>0,K||V1(H,8,this.length),Z.read(this,H,!1,52,8)},"readDoubleBE");function f1(H,K,z,h,j,O){if(!G.isBuffer(H))throw TypeError('"buffer" argument must be a Buffer instance');if(K>j||K<O)throw RangeError('"value" argument is out of bounds');if(z+h>H.length)throw RangeError("Index out of range")}U(f1,"checkInt"),G.prototype.writeUintLE=G.prototype.writeUIntLE=U(function(H,K,z,h){if(H=+H,K=K>>>0,z=z>>>0,!h){let I=Math.pow(2,8*z)-1;f1(this,H,K,z,I,0)}let j=1,O=0;for(this[K]=H&255;++O<z&&(j*=256);)this[K+O]=H/j&255;return K+z},"writeUIntLE"),G.prototype.writeUintBE=G.prototype.writeUIntBE=U(function(H,K,z,h){if(H=+H,K=K>>>0,z=z>>>0,!h){let I=Math.pow(2,8*z)-1;f1(this,H,K,z,I,0)}let j=z-1,O=1;for(this[K+j]=H&255;--j>=0&&(O*=256);)this[K+j]=H/O&255;return K+z},"writeUIntBE"),G.prototype.writeUint8=G.prototype.writeUInt8=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,1,255,0),this[K]=H&255,K+1},"writeUInt8"),G.prototype.writeUint16LE=G.prototype.writeUInt16LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,65535,0),this[K]=H&255,this[K+1]=H>>>8,K+2},"writeUInt16LE"),G.prototype.writeUint16BE=G.prototype.writeUInt16BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,65535,0),this[K]=H>>>8,this[K+1]=H&255,K+2},"writeUInt16BE"),G.prototype.writeUint32LE=G.prototype.writeUInt32LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,4294967295,0),this[K+3]=H>>>24,this[K+2]=H>>>16,this[K+1]=H>>>8,this[K]=H&255,K+4},"writeUInt32LE"),G.prototype.writeUint32BE=G.prototype.writeUInt32BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,4294967295,0),this[K]=H>>>24,this[K+1]=H>>>16,this[K+2]=H>>>8,this[K+3]=H&255,K+4},"writeUInt32BE");function kW(H,K,z,h,j){n4(K,h,j,H,z,7);let O=Number(K&BigInt(4294967295));H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O;let I=Number(K>>BigInt(32)&BigInt(4294967295));return H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,z}U(kW,"wrtBigUInt64LE");function GW(H,K,z,h,j){n4(K,h,j,H,z,7);let O=Number(K&BigInt(4294967295));H[z+7]=O,O=O>>8,H[z+6]=O,O=O>>8,H[z+5]=O,O=O>>8,H[z+4]=O;let I=Number(K>>BigInt(32)&BigInt(4294967295));return H[z+3]=I,I=I>>8,H[z+2]=I,I=I>>8,H[z+1]=I,I=I>>8,H[z]=I,z+8}U(GW,"wrtBigUInt64BE"),G.prototype.writeBigUInt64LE=O0(U(function(H,K=0){return kW(this,H,K,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),G.prototype.writeBigUInt64BE=O0(U(function(H,K=0){return GW(this,H,K,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),G.prototype.writeIntLE=U(function(H,K,z,h){if(H=+H,K=K>>>0,!h){let P1=Math.pow(2,8*z-1);f1(this,H,K,z,P1-1,-P1)}let j=0,O=1,I=0;for(this[K]=H&255;++j<z&&(O*=256);)H<0&&I===0&&this[K+j-1]!==0&&(I=1),this[K+j]=(H/O>>0)-I&255;return K+z},"writeIntLE"),G.prototype.writeIntBE=U(function(H,K,z,h){if(H=+H,K=K>>>0,!h){let P1=Math.pow(2,8*z-1);f1(this,H,K,z,P1-1,-P1)}let j=z-1,O=1,I=0;for(this[K+j]=H&255;--j>=0&&(O*=256);)H<0&&I===0&&this[K+j+1]!==0&&(I=1),this[K+j]=(H/O>>0)-I&255;return K+z},"writeIntBE"),G.prototype.writeInt8=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,1,127,-128),H<0&&(H=255+H+1),this[K]=H&255,K+1},"writeInt8"),G.prototype.writeInt16LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,32767,-32768),this[K]=H&255,this[K+1]=H>>>8,K+2},"writeInt16LE"),G.prototype.writeInt16BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,32767,-32768),this[K]=H>>>8,this[K+1]=H&255,K+2},"writeInt16BE"),G.prototype.writeInt32LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,2147483647,-2147483648),this[K]=H&255,this[K+1]=H>>>8,this[K+2]=H>>>16,this[K+3]=H>>>24,K+4},"writeInt32LE"),G.prototype.writeInt32BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,2147483647,-2147483648),H<0&&(H=4294967295+H+1),this[K]=H>>>24,this[K+1]=H>>>16,this[K+2]=H>>>8,this[K+3]=H&255,K+4},"writeInt32BE"),G.prototype.writeBigInt64LE=O0(U(function(H,K=0){return kW(this,H,K,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),G.prototype.writeBigInt64BE=O0(U(function(H,K=0){return GW(this,H,K,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function t4(H,K,z,h,j,O){if(z+h>H.length)throw RangeError("Index out of range");if(z<0)throw RangeError("Index out of range")}U(t4,"checkIEEE754");function a4(H,K,z,h,j){return K=+K,z=z>>>0,j||t4(H,K,z,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),Z.write(H,K,z,h,23,4),z+4}U(a4,"writeFloat"),G.prototype.writeFloatLE=U(function(H,K,z){return a4(this,H,K,!0,z)},"writeFloatLE"),G.prototype.writeFloatBE=U(function(H,K,z){return a4(this,H,K,!1,z)},"writeFloatBE");function d4(H,K,z,h,j){return K=+K,z=z>>>0,j||t4(H,K,z,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),Z.write(H,K,z,h,52,8),z+8}U(d4,"writeDouble"),G.prototype.writeDoubleLE=U(function(H,K,z){return d4(this,H,K,!0,z)},"writeDoubleLE"),G.prototype.writeDoubleBE=U(function(H,K,z){return d4(this,H,K,!1,z)},"writeDoubleBE"),G.prototype.copy=U(function(H,K,z,h){if(!G.isBuffer(H))throw TypeError("argument should be a Buffer");if(z||(z=0),!h&&h!==0&&(h=this.length),K>=H.length&&(K=H.length),K||(K=0),h>0&&h<z&&(h=z),h===z||H.length===0||this.length===0)return 0;if(K<0)throw RangeError("targetStart out of bounds");if(z<0||z>=this.length)throw RangeError("Index out of range");if(h<0)throw RangeError("sourceEnd out of bounds");h>this.length&&(h=this.length),H.length-K<h-z&&(h=H.length-K+z);let j=h-z;return this===H&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(K,z,h):Uint8Array.prototype.set.call(H,this.subarray(z,h),K),j},"copy"),G.prototype.fill=U(function(H,K,z,h){if(typeof H=="string"){if(typeof K=="string"?(h=K,K=0,z=this.length):typeof z=="string"&&(h=z,z=this.length),h!==void 0&&typeof h!="string")throw TypeError("encoding must be a string");if(typeof h=="string"&&!G.isEncoding(h))throw TypeError("Unknown encoding: "+h);if(H.length===1){let O=H.charCodeAt(0);(h==="utf8"&&O<128||h==="latin1")&&(H=O)}}else typeof H=="number"?H=H&255:typeof H=="boolean"&&(H=Number(H));if(K<0||this.length<K||this.length<z)throw RangeError("Out of range index");if(z<=K)return this;K=K>>>0,z=z===void 0?this.length:z>>>0,H||(H=0);let j;if(typeof H=="number")for(j=K;j<z;++j)this[j]=H;else{let O=G.isBuffer(H)?H:G.from(H,h),I=O.length;if(I===0)throw TypeError('The value "'+H+'" is invalid for argument "value"');for(j=0;j<z-K;++j)this[j+K]=O[j%I]}return this},"fill");var _8={};function sW(H,K,z){var h;_8[H]=(h=class extends z{constructor(){super(),Object.defineProperty(this,"message",{value:K.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${H}]`,this.stack,delete this.name}get code(){return H}set code(j){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:j,writable:!0})}toString(){return`${this.name} [${H}]: ${this.message}`}},U(h,"NodeError"),h)}U(sW,"E"),sW("ERR_BUFFER_OUT_OF_BOUNDS",function(H){return H?`${H} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),sW("ERR_INVALID_ARG_TYPE",function(H,K){return`The "${H}" argument must be of type number. Received type ${typeof K}`},TypeError),sW("ERR_OUT_OF_RANGE",function(H,K,z){let h=`The value of "${H}" is out of range.`,j=z;return Number.isInteger(z)&&Math.abs(z)>4294967296?j=s4(String(z)):typeof z=="bigint"&&(j=String(z),(z>BigInt(2)**BigInt(32)||z<-(BigInt(2)**BigInt(32)))&&(j=s4(j)),j+="n"),h+=` It must be ${K}. Received ${j}`,h},RangeError);function s4(H){let K="",z=H.length,h=H[0]==="-"?1:0;for(;z>=h+4;z-=3)K=`_${H.slice(z-3,z)}${K}`;return`${H.slice(0,z)}${K}`}U(s4,"addNumericalSeparator");function _9(H,K,z){M8(K,"offset"),(H[K]===void 0||H[K+z]===void 0)&&v8(K,H.length-(z+1))}U(_9,"checkBounds");function n4(H,K,z,h,j,O){if(H>z||H<K){let I=typeof K=="bigint"?"n":"",P1;throw O>3?K===0||K===BigInt(0)?P1=`>= 0${I} and < 2${I} ** ${(O+1)*8}${I}`:P1=`>= -(2${I} ** ${(O+1)*8-1}${I}) and < 2 ** ${(O+1)*8-1}${I}`:P1=`>= ${K}${I} and <= ${z}${I}`,new _8.ERR_OUT_OF_RANGE("value",P1,H)}_9(h,j,O)}U(n4,"checkIntBI");function M8(H,K){if(typeof H!="number")throw new _8.ERR_INVALID_ARG_TYPE(K,"number",H)}U(M8,"validateNumber");function v8(H,K,z){throw Math.floor(H)!==H?(M8(H,z),new _8.ERR_OUT_OF_RANGE(z||"offset","an integer",H)):K<0?new _8.ERR_BUFFER_OUT_OF_BOUNDS:new _8.ERR_OUT_OF_RANGE(z||"offset",`>= ${z?1:0} and <= ${K}`,H)}U(v8,"boundsError");var h$=/[^+/0-9A-Za-z-_]/g;function v9(H){if(H=H.split("=")[0],H=H.trim().replace(h$,""),H.length<2)return"";for(;H.length%4!==0;)H=H+"=";return H}U(v9,"base64clean");function nW(H,K){K=K||1/0;let z,h=H.length,j=null,O=[];for(let I=0;I<h;++I){if(z=H.charCodeAt(I),z>55295&&z<57344){if(!j){if(z>56319){(K-=3)>-1&&O.push(239,191,189);continue}else if(I+1===h){(K-=3)>-1&&O.push(239,191,189);continue}j=z;continue}if(z<56320){(K-=3)>-1&&O.push(239,191,189),j=z;continue}z=(j-55296<<10|z-56320)+65536}else j&&(K-=3)>-1&&O.push(239,191,189);if(j=null,z<128){if((K-=1)<0)break;O.push(z)}else if(z<2048){if((K-=2)<0)break;O.push(z>>6|192,z&63|128)}else if(z<65536){if((K-=3)<0)break;O.push(z>>12|224,z>>6&63|128,z&63|128)}else if(z<1114112){if((K-=4)<0)break;O.push(z>>18|240,z>>12&63|128,z>>6&63|128,z&63|128)}else throw Error("Invalid code point")}return O}U(nW,"utf8ToBytes");function E9(H){let K=[];for(let z=0;z<H.length;++z)K.push(H.charCodeAt(z)&255);return K}U(E9,"asciiToBytes");function h9(H,K){let z,h,j,O=[];for(let I=0;I<H.length&&!((K-=2)<0);++I)z=H.charCodeAt(I),h=z>>8,j=z%256,O.push(j),O.push(h);return O}U(h9,"utf16leToBytes");function r4(H){return $.toByteArray(v9(H))}U(r4,"base64ToBytes");function MW(H,K,z,h){let j;for(j=0;j<h&&!(j+z>=K.length||j>=H.length);++j)K[j+z]=H[j];return j}U(MW,"blitBuffer");function Y0(H,K){return H instanceof K||H!=null&&H.constructor!=null&&H.constructor.name!=null&&H.constructor.name===K.name}U(Y0,"isInstance");function rW(H){return H!==H}U(rW,"numberIsNaN");var T$=function(){let H="0123456789abcdef",K=Array(256);for(let z=0;z<16;++z){let h=z*16;for(let j=0;j<16;++j)K[h+j]=H[z]+H[j]}return K}();function O0(H){return typeof BigInt>"u"?T9:H}U(O0,"defineBigIntMethod");function T9(){throw Error("BigInt not supported")}U(T9,"BufferBigIntNotDefined")}),x4,M9,QZ,i,r,u=d1(()=>{x4=globalThis,M9=globalThis.setImmediate??((W)=>setTimeout(W,0)),QZ=globalThis.clearImmediate??((W)=>clearTimeout(W)),i=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:wZ().Buffer,r=globalThis.process??{},r.env??(r.env={});try{r.nextTick(()=>{})}catch{let W=Promise.resolve();r.nextTick=W.then.bind(W)}}),S8=o((W,$)=>{u();var Z=typeof Reflect=="object"?Reflect:null,J=Z&&typeof Z.apply=="function"?Z.apply:U(function(E,N,A){return Function.prototype.apply.call(E,N,A)},"ReflectApply"),X;Z&&typeof Z.ownKeys=="function"?X=Z.ownKeys:Object.getOwnPropertySymbols?X=U(function(E){return Object.getOwnPropertyNames(E).concat(Object.getOwnPropertySymbols(E))},"ReflectOwnKeys"):X=U(function(E){return Object.getOwnPropertyNames(E)},"ReflectOwnKeys");function Y(E){console&&console.warn&&console.warn(E)}U(Y,"ProcessEmitWarning");var M=Number.isNaN||U(function(E){return E!==E},"NumberIsNaN");function G(){G.init.call(this)}U(G,"EventEmitter"),$.exports=G,$.exports.once=T,G.EventEmitter=G,G.prototype._events=void 0,G.prototype._eventsCount=0,G.prototype._maxListeners=void 0;var V=10;function R(E){if(typeof E!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof E)}U(R,"checkListener"),Object.defineProperty(G,"defaultMaxListeners",{enumerable:!0,get:U(function(){return V},"get"),set:U(function(E){if(typeof E!="number"||E<0||M(E))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+E+".");V=E},"set")}),G.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},G.prototype.setMaxListeners=U(function(E){if(typeof E!="number"||E<0||M(E))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+E+".");return this._maxListeners=E,this},"setMaxListeners");function P(E){return E._maxListeners===void 0?G.defaultMaxListeners:E._maxListeners}U(P,"_getMaxListeners"),G.prototype.getMaxListeners=U(function(){return P(this)},"getMaxListeners"),G.prototype.emit=U(function(E){for(var N=[],A=1;A<arguments.length;A++)N.push(arguments[A]);var f=E==="error",B=this._events;if(B!==void 0)f=f&&B.error===void 0;else if(!f)return!1;if(f){var C;if(N.length>0&&(C=N[0]),C instanceof Error)throw C;var c=Error("Unhandled error."+(C?" ("+C.message+")":""));throw c.context=C,c}var m=B[E];if(m===void 0)return!1;if(typeof m=="function")J(m,this,N);else for(var b=m.length,g=Q(m,b),A=0;A<b;++A)J(g[A],this,N);return!0},"emit");function w(E,N,A,f){var B,C,c;if(R(A),C=E._events,C===void 0?(C=E._events=Object.create(null),E._eventsCount=0):(C.newListener!==void 0&&(E.emit("newListener",N,A.listener?A.listener:A),C=E._events),c=C[N]),c===void 0)c=C[N]=A,++E._eventsCount;else if(typeof c=="function"?c=C[N]=f?[A,c]:[c,A]:f?c.unshift(A):c.push(A),B=P(E),B>0&&c.length>B&&!c.warned){c.warned=!0;var m=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(N)+" listeners added. Use emitter.setMaxListeners() to increase limit");m.name="MaxListenersExceededWarning",m.emitter=E,m.type=N,m.count=c.length,Y(m)}return E}U(w,"_addListener"),G.prototype.addListener=U(function(E,N){return w(this,E,N,!1)},"addListener"),G.prototype.on=G.prototype.addListener,G.prototype.prependListener=U(function(E,N){return w(this,E,N,!0)},"prependListener");function D(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}U(D,"onceWrapper");function S(E,N,A){var f={fired:!1,wrapFn:void 0,target:E,type:N,listener:A},B=D.bind(f);return B.listener=A,f.wrapFn=B,B}U(S,"_onceWrap"),G.prototype.once=U(function(E,N){return R(N),this.on(E,S(this,E,N)),this},"once"),G.prototype.prependOnceListener=U(function(E,N){return R(N),this.prependListener(E,S(this,E,N)),this},"prependOnceListener"),G.prototype.removeListener=U(function(E,N){var A,f,B,C,c;if(R(N),f=this._events,f===void 0)return this;if(A=f[E],A===void 0)return this;if(A===N||A.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete f[E],f.removeListener&&this.emit("removeListener",E,A.listener||N));else if(typeof A!="function"){for(B=-1,C=A.length-1;C>=0;C--)if(A[C]===N||A[C].listener===N){c=A[C].listener,B=C;break}if(B<0)return this;B===0?A.shift():_(A,B),A.length===1&&(f[E]=A[0]),f.removeListener!==void 0&&this.emit("removeListener",E,c||N)}return this},"removeListener"),G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=U(function(E){var N,A,f;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[E]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[E]),this;if(arguments.length===0){var B=Object.keys(A),C;for(f=0;f<B.length;++f)C=B[f],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(N=A[E],typeof N=="function")this.removeListener(E,N);else if(N!==void 0)for(f=N.length-1;f>=0;f--)this.removeListener(E,N[f]);return this},"removeAllListeners");function F(E,N,A){var f=E._events;if(f===void 0)return[];var B=f[N];return B===void 0?[]:typeof B=="function"?A?[B.listener||B]:[B]:A?v(B):Q(B,B.length)}U(F,"_listeners"),G.prototype.listeners=U(function(E){return F(this,E,!0)},"listeners"),G.prototype.rawListeners=U(function(E){return F(this,E,!1)},"rawListeners"),G.listenerCount=function(E,N){return typeof E.listenerCount=="function"?E.listenerCount(N):L.call(E,N)},G.prototype.listenerCount=L;function L(E){var N=this._events;if(N!==void 0){var A=N[E];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}U(L,"listenerCount"),G.prototype.eventNames=U(function(){return this._eventsCount>0?X(this._events):[]},"eventNames");function Q(E,N){for(var A=Array(N),f=0;f<N;++f)A[f]=E[f];return A}U(Q,"arrayClone");function _(E,N){for(;N+1<E.length;N++)E[N]=E[N+1];E.pop()}U(_,"spliceOne");function v(E){for(var N=Array(E.length),A=0;A<N.length;++A)N[A]=E[A].listener||E[A];return N}U(v,"unwrapListeners");function T(E,N){return new Promise(function(A,f){function B(c){E.removeListener(N,C),f(c)}U(B,"errorListener");function C(){typeof E.removeListener=="function"&&E.removeListener("error",B),A([].slice.call(arguments))}U(C,"resolver"),q(E,N,C,{once:!0}),N!=="error"&&x(E,B,{once:!0})})}U(T,"once");function x(E,N,A){typeof E.on=="function"&&q(E,"error",N,A)}U(x,"addErrorHandlerIfEventEmitter");function q(E,N,A,f){if(typeof E.on=="function")f.once?E.once(N,A):E.on(N,A);else if(typeof E.addEventListener=="function")E.addEventListener(N,U(function B(C){f.once&&E.removeEventListener(N,B),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof E)}U(q,"eventTargetAgnosticAddListener")}),w7={};S0(w7,{Socket:()=>w8,isIP:()=>Q7});function Q7(W){return 0}var z7,X9,lW,w8,tW=d1(()=>{u(),z7=Q8(S8(),1),U(Q7,"isIP"),X9=/^[^.]+\./,lW=class W extends z7.EventEmitter{constructor(){super(...arguments);t(this,"opts",{}),t(this,"connecting",!1),t(this,"pending",!0),t(this,"writable",!0),t(this,"encrypted",!1),t(this,"authorized",!1),t(this,"destroyed",!1),t(this,"ws",null),t(this,"writeBuffer"),t(this,"tlsState",0),t(this,"tlsRead"),t(this,"tlsWrite")}static get poolQueryViaFetch(){return W.opts.poolQueryViaFetch??W.defaults.poolQueryViaFetch}static set poolQueryViaFetch($){W.opts.poolQueryViaFetch=$}static get fetchEndpoint(){return W.opts.fetchEndpoint??W.defaults.fetchEndpoint}static set fetchEndpoint($){W.opts.fetchEndpoint=$}static get fetchConnectionCache(){return!0}static set fetchConnectionCache($){console.warn("The `fetchConnectionCache` option is deprecated (now always `true`)")}static get fetchFunction(){return W.opts.fetchFunction??W.defaults.fetchFunction}static set fetchFunction($){W.opts.fetchFunction=$}static get webSocketConstructor(){return W.opts.webSocketConstructor??W.defaults.webSocketConstructor}static set webSocketConstructor($){W.opts.webSocketConstructor=$}get webSocketConstructor(){return this.opts.webSocketConstructor??W.webSocketConstructor}set webSocketConstructor($){this.opts.webSocketConstructor=$}static get wsProxy(){return W.opts.wsProxy??W.defaults.wsProxy}static set wsProxy($){W.opts.wsProxy=$}get wsProxy(){return this.opts.wsProxy??W.wsProxy}set wsProxy($){this.opts.wsProxy=$}static get coalesceWrites(){return W.opts.coalesceWrites??W.defaults.coalesceWrites}static set coalesceWrites($){W.opts.coalesceWrites=$}get coalesceWrites(){return this.opts.coalesceWrites??W.coalesceWrites}set coalesceWrites($){this.opts.coalesceWrites=$}static get useSecureWebSocket(){return W.opts.useSecureWebSocket??W.defaults.useSecureWebSocket}static set useSecureWebSocket($){W.opts.useSecureWebSocket=$}get useSecureWebSocket(){return this.opts.useSecureWebSocket??W.useSecureWebSocket}set useSecureWebSocket($){this.opts.useSecureWebSocket=$}static get forceDisablePgSSL(){return W.opts.forceDisablePgSSL??W.defaults.forceDisablePgSSL}static set forceDisablePgSSL($){W.opts.forceDisablePgSSL=$}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??W.forceDisablePgSSL}set forceDisablePgSSL($){this.opts.forceDisablePgSSL=$}static get disableSNI(){return W.opts.disableSNI??W.defaults.disableSNI}static set disableSNI($){W.opts.disableSNI=$}get disableSNI(){return this.opts.disableSNI??W.disableSNI}set disableSNI($){this.opts.disableSNI=$}static get disableWarningInBrowsers(){return W.opts.disableWarningInBrowsers??W.defaults.disableWarningInBrowsers}static set disableWarningInBrowsers($){W.opts.disableWarningInBrowsers=$}get disableWarningInBrowsers(){return this.opts.disableWarningInBrowsers??W.disableWarningInBrowsers}set disableWarningInBrowsers($){this.opts.disableWarningInBrowsers=$}static get pipelineConnect(){return W.opts.pipelineConnect??W.defaults.pipelineConnect}static set pipelineConnect($){W.opts.pipelineConnect=$}get pipelineConnect(){return this.opts.pipelineConnect??W.pipelineConnect}set pipelineConnect($){this.opts.pipelineConnect=$}static get subtls(){return W.opts.subtls??W.defaults.subtls}static set subtls($){W.opts.subtls=$}get subtls(){return this.opts.subtls??W.subtls}set subtls($){this.opts.subtls=$}static get pipelineTLS(){return W.opts.pipelineTLS??W.defaults.pipelineTLS}static set pipelineTLS($){W.opts.pipelineTLS=$}get pipelineTLS(){return this.opts.pipelineTLS??W.pipelineTLS}set pipelineTLS($){this.opts.pipelineTLS=$}static get rootCerts(){return W.opts.rootCerts??W.defaults.rootCerts}static set rootCerts($){W.opts.rootCerts=$}get rootCerts(){return this.opts.rootCerts??W.rootCerts}set rootCerts($){this.opts.rootCerts=$}wsProxyAddrForHost($,Z){let J=this.wsProxy;if(J===void 0)throw Error("No WebSocket proxy is configured. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#wsproxy-string--host-string-port-number--string--string");return typeof J=="function"?J($,Z):`${J}?address=${$}:${Z}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,Z,J){this.connecting=!0,J&&this.once("connect",J);let X=U(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),Y=U((G,V=!1)=>{G.binaryType="arraybuffer",G.addEventListener("error",(R)=>{this.emit("error",R),this.emit("close")}),G.addEventListener("message",(R)=>{if(this.tlsState===0){let P=i.from(R.data);this.emit("data",P)}}),G.addEventListener("close",()=>{this.emit("close")}),V?X():G.addEventListener("open",X)},"configureWebSocket"),M;try{M=this.wsProxyAddrForHost(Z,typeof $=="string"?parseInt($,10):$)}catch(G){this.emit("error",G),this.emit("close");return}try{let G=(this.useSecureWebSocket?"wss:":"ws:")+"//"+M;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(G),Y(this.ws);else try{this.ws=new WebSocket(G),Y(this.ws)}catch{this.ws=new __unstable_WebSocket(G),Y(this.ws)}}catch(G){let V=(this.useSecureWebSocket?"https:":"http:")+"//"+M;fetch(V,{headers:{Upgrade:"websocket"}}).then((R)=>{if(this.ws=R.webSocket,this.ws==null)throw G;this.ws.accept(),Y(this.ws,!0)}).catch((R)=>{this.emit("error",Error(`All attempts to open a WebSocket to connect to the database failed. Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined. Details: ${R}`)),this.emit("close")})}}async startTls($){if(this.subtls===void 0)throw Error("For Postgres SSL connections, you must set `neonConfig.subtls` to the subtls library. See https://github.com/neondatabase/serverless/blob/main/CONFIG.md for more information.");this.tlsState=1;let Z=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),X=J.read.bind(J),Y=this.rawWrite.bind(this),{read:M,write:G}=await this.subtls.startTls($,Z,X,Y,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=M,this.tlsWrite=G,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit("secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let $=await this.tlsRead();if($===void 0)break;{let Z=i.from($);this.emit("data",Z)}}}rawWrite($){if(!this.coalesceWrites){this.ws&&this.ws.send($);return}if(this.writeBuffer===void 0)this.writeBuffer=$,setTimeout(()=>{this.ws&&this.ws.send(this.writeBuffer),this.writeBuffer=void 0},0);else{let Z=new Uint8Array(this.writeBuffer.length+$.length);Z.set(this.writeBuffer),Z.set($,this.writeBuffer.length),this.writeBuffer=Z}}write($,Z="utf8",J=(X)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=i.from($,Z)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,Z,J)}):(this.tlsWrite($),J()),!0)}end($=i.alloc(0),Z="utf8",J=()=>{}){return this.write($,Z,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},U(lW,"Socket"),t(lW,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:U((W,$,Z)=>{let J;return Z?.jwtAuth?J=W.replace(X9,"apiauth."):J=W.replace(X9,"api."),"https://"+J+"/sql"},"fetchEndpoint"),fetchConnectionCache:!0,fetchFunction:void 0,webSocketConstructor:void 0,wsProxy:U((W)=>W+"/v2","wsProxy"),useSecureWebSocket:!0,forceDisablePgSSL:!0,coalesceWrites:!0,pipelineConnect:"password",subtls:void 0,rootCerts:"",pipelineTLS:!1,disableSNI:!1,disableWarningInBrowsers:!1}),t(lW,"opts",{}),w8=lW}),S7={};S0(S7,{parse:()=>L9});function L9(W,$=!1){let{protocol:Z}=new URL(W),J="http:"+W.substring(Z.length),{username:X,password:Y,host:M,hostname:G,port:V,pathname:R,search:P,searchParams:w,hash:D}=new URL(J);Y=decodeURIComponent(Y),X=decodeURIComponent(X),R=decodeURIComponent(R);let S=X+":"+Y,F=$?Object.fromEntries(w.entries()):P;return{href:W,protocol:Z,auth:S,username:X,password:Y,host:M,hostname:G,port:V,pathname:R,search:P,query:F,hash:D}}var _7=d1(()=>{u(),U(L9,"parse")}),v7=o((W)=>{u(),W.parse=function(X,Y){return new Z(X,Y).parse()};var $=class X{constructor(Y,M){this.source=Y,this.transform=M||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var Y=this.source[this.position++];return Y==="\\"?{value:this.source[this.position++],escaped:!0}:{value:Y,escaped:!1}}record(Y){this.recorded.push(Y)}newEntry(Y){var M;(this.recorded.length>0||Y)&&(M=this.recorded.join(""),M==="NULL"&&!Y&&(M=null),M!==null&&(M=this.transform(M)),this.entries.push(M),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var Y=this.nextCharacter();if(Y.value==="=")break}}parse(Y){var M,G,V;for(this.consumeDimensions();!this.isEof();)if(M=this.nextCharacter(),M.value==="{"&&!V)this.dimension++,this.dimension>1&&(G=new X(this.source.substr(this.position-1),this.transform),this.entries.push(G.parse(!0)),this.position+=G.position-2);else if(M.value==="}"&&!V){if(this.dimension--,!this.dimension&&(this.newEntry(),Y))return this.entries}else M.value==='"'&&!M.escaped?(V&&this.newEntry(!0),V=!V):M.value===","&&!V?this.newEntry():this.record(M.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};U($,"ArrayParser");var Z=$;function J(X){return X}U(J,"identity")}),E7=o((W,$)=>{u();var Z=v7();$.exports={create:U(function(J,X){return{parse:U(function(){return Z.parse(J,X)},"parse")}},"create")}}),SZ=o((W,$)=>{u();var Z=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,X=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Y=/^-?infinity$/;$.exports=U(function(P){if(Y.test(P))return Number(P.replace("i","I"));var w=Z.exec(P);if(!w)return M(P)||null;var D=!!w[8],S=parseInt(w[1],10);D&&(S=V(S));var F=parseInt(w[2],10)-1,L=w[3],Q=parseInt(w[4],10),_=parseInt(w[5],10),v=parseInt(w[6],10),T=w[7];T=T?1000*parseFloat(T):0;var x,q=G(P);return q!=null?(x=new Date(Date.UTC(S,F,L,Q,_,v,T)),R(S)&&x.setUTCFullYear(S),q!==0&&x.setTime(x.getTime()-q)):(x=new Date(S,F,L,Q,_,v,T),R(S)&&x.setFullYear(S)),x},"parseDate");function M(P){var w=J.exec(P);if(w){var D=parseInt(w[1],10),S=!!w[4];S&&(D=V(D));var F=parseInt(w[2],10)-1,L=w[3],Q=new Date(D,F,L);return R(D)&&Q.setFullYear(D),Q}}U(M,"getDate");function G(P){if(P.endsWith("+00"))return 0;var w=X.exec(P.split(" ")[1]);if(w){var D=w[1];if(D==="Z")return 0;var S=D==="-"?-1:1,F=parseInt(w[2],10)*3600+parseInt(w[3]||0,10)*60+parseInt(w[4]||0,10);return F*S*1000}}U(G,"timeZoneOffset");function V(P){return-(P-1)}U(V,"bcYearToNegativeYear");function R(P){return P>=0&&P<100}U(R,"is0To99")}),_Z=o((W,$)=>{u(),$.exports=J;var Z=Object.prototype.hasOwnProperty;function J(X){for(var Y=1;Y<arguments.length;Y++){var M=arguments[Y];for(var G in M)Z.call(M,G)&&(X[G]=M[G])}return X}U(J,"extend")}),vZ=o((W,$)=>{u();var Z=_Z();$.exports=J;function J(v){if(!(this instanceof J))return new J(v);Z(this,_(v))}U(J,"PostgresInterval");var X=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var v=X.filter(this.hasOwnProperty,this);return this.milliseconds&&v.indexOf("seconds")<0&&v.push("seconds"),v.length===0?"0":v.map(function(T){var x=this[T]||0;return T==="seconds"&&this.milliseconds&&(x=(x+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),x+" "+T},this).join(" ")};var Y={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},M=["years","months","days"],G=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var v=M.map(x,this).join(""),T=G.map(x,this).join("");return"P"+v+"T"+T;function x(q){var E=this[q]||0;return q==="seconds"&&this.milliseconds&&(E=(E+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),E+Y[q]}};var V="([+-]?\\d+)",R=V+"\\s+years?",P=V+"\\s+mons?",w=V+"\\s+days?",D="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",S=new RegExp([R,P,w,D].map(function(v){return"("+v+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},L=["hours","minutes","seconds","milliseconds"];function Q(v){var T=v+"000000".slice(v.length);return parseInt(T,10)/1000}U(Q,"parseMilliseconds");function _(v){if(!v)return{};var T=S.exec(v),x=T[8]==="-";return Object.keys(F).reduce(function(q,E){var N=F[E],A=T[N];return!A||(A=E==="milliseconds"?Q(A):parseInt(A,10),!A)||(x&&~L.indexOf(E)&&(A*=-1),q[E]=A),q},{})}U(_,"parse")}),EZ=o((W,$)=>{u(),$.exports=U(function(Z){if(/^\\x/.test(Z))return new i(Z.substr(2),"hex");for(var J="",X=0;X<Z.length;)if(Z[X]!=="\\")J+=Z[X],++X;else if(/[0-7]{3}/.test(Z.substr(X+1,3)))J+=String.fromCharCode(parseInt(Z.substr(X+1,3),8)),X+=4;else{for(var Y=1;X+Y<Z.length&&Z[X+Y]==="\\";)Y++;for(var M=0;M<Math.floor(Y/2);++M)J+="\\";X+=Math.floor(Y/2)*2}return new i(J,"binary")},"parseBytea")}),hZ=o((W,$)=>{u();var Z=v7(),J=E7(),X=SZ(),Y=vZ(),M=EZ();function G(f){return U(function(B){return B===null?B:f(B)},"nullAllowed")}U(G,"allowNull");function V(f){return f===null?f:f==="TRUE"||f==="t"||f==="true"||f==="y"||f==="yes"||f==="on"||f==="1"}U(V,"parseBool");function R(f){return f?Z.parse(f,V):null}U(R,"parseBoolArray");function P(f){return parseInt(f,10)}U(P,"parseBaseTenInt");function w(f){return f?Z.parse(f,G(P)):null}U(w,"parseIntegerArray");function D(f){return f?Z.parse(f,G(function(B){return x(B).trim()})):null}U(D,"parseBigIntegerArray");var S=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=E(C)),C});return B.parse()},"parsePointArray"),F=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=parseFloat(C)),C});return B.parse()},"parseFloatArray"),L=U(function(f){if(!f)return null;var B=J.create(f);return B.parse()},"parseStringArray"),Q=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=X(C)),C});return B.parse()},"parseDateArray"),_=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=Y(C)),C});return B.parse()},"parseIntervalArray"),v=U(function(f){return f?Z.parse(f,G(M)):null},"parseByteAArray"),T=U(function(f){return parseInt(f,10)},"parseInteger"),x=U(function(f){var B=String(f);return/^\d+$/.test(B)?B:f},"parseBigInteger"),q=U(function(f){return f?Z.parse(f,G(JSON.parse)):null},"parseJsonArray"),E=U(function(f){return f[0]!=="("?null:(f=f.substring(1,f.length-1).split(","),{x:parseFloat(f[0]),y:parseFloat(f[1])})},"parsePoint"),N=U(function(f){if(f[0]!=="<"&&f[1]!=="(")return null;for(var B="(",C="",c=!1,m=2;m<f.length-1;m++){if(c||(B+=f[m]),f[m]===")"){c=!0;continue}else if(!c)continue;f[m]!==","&&(C+=f[m])}var b=E(B);return b.radius=parseFloat(C),b},"parseCircle"),A=U(function(f){f(20,x),f(21,T),f(23,T),f(26,T),f(700,parseFloat),f(701,parseFloat),f(16,V),f(1082,X),f(1114,X),f(1184,X),f(600,E),f(651,L),f(718,N),f(1000,R),f(1001,v),f(1005,w),f(1007,w),f(1028,w),f(1016,D),f(1017,S),f(1021,F),f(1022,F),f(1231,F),f(1014,L),f(1015,L),f(1008,L),f(1009,L),f(1040,L),f(1041,L),f(1115,Q),f(1182,Q),f(1185,Q),f(1186,Y),f(1187,_),f(17,M),f(114,JSON.parse.bind(JSON)),f(3802,JSON.parse.bind(JSON)),f(199,q),f(3807,q),f(3907,L),f(2951,L),f(791,L),f(1183,L),f(1270,L)},"init");$.exports={init:A}}),TZ=o((W,$)=>{u();var Z=1e6;function J(X){var Y=X.readInt32BE(0),M=X.readUInt32BE(4),G="";Y<0&&(Y=~Y+(M===0),M=~M+1>>>0,G="-");var V="",R,P,w,D,S,F;{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}return R=Y%Z,P=4294967296*R+M,w=""+P%Z,G+w+V}U(J,"readInt8"),$.exports=J}),fZ=o((W,$)=>{u();var Z=TZ(),J=U(function(L,Q,_,v,T){_=_||0,v=v||!1,T=T||function(c,m,b){return c*Math.pow(2,b)+m};var x=_>>3,q=U(function(c){return v?~c&255:c},"inv"),E=255,N=8-_%8;Q<N&&(E=255<<8-Q&255,N=Q),_&&(E=E>>_%8);var A=0;_%8+Q>=8&&(A=T(0,q(L[x])&E,N));for(var f=Q+_>>3,B=x+1;B<f;B++)A=T(A,q(L[B]),8);var C=(Q+_)%8;return C>0&&(A=T(A,q(L[f])>>8-C,C)),A},"parseBits"),X=U(function(L,Q,_){var v=Math.pow(2,_-1)-1,T=J(L,1),x=J(L,_,1);if(x===0)return 0;var q=1,E=U(function(A,f,B){A===0&&(A=1);for(var C=1;C<=B;C++)q/=2,(f&1<<B-C)>0&&(A+=q);return A},"parsePrecisionBits"),N=J(L,Q,_+1,!1,E);return x==Math.pow(2,_+1)-1?N===0?T===0?1/0:-1/0:NaN:(T===0?1:-1)*Math.pow(2,x-v)*N},"parseFloatFromBits"),Y=U(function(L){return J(L,1)==1?-1*(J(L,15,1,!0)+1):J(L,15,1)},"parseInt16"),M=U(function(L){return J(L,1)==1?-1*(J(L,31,1,!0)+1):J(L,31,1)},"parseInt32"),G=U(function(L){return X(L,23,8)},"parseFloat32"),V=U(function(L){return X(L,52,11)},"parseFloat64"),R=U(function(L){var Q=J(L,16,32);if(Q==49152)return NaN;for(var _=Math.pow(1e4,J(L,16,16)),v=0,T=[],x=J(L,16),q=0;q<x;q++)v+=J(L,16,64+16*q)*_,_/=1e4;var E=Math.pow(10,J(L,16,48));return(Q===0?1:-1)*Math.round(v*E)/E},"parseNumeric"),P=U(function(L,Q){var _=J(Q,1),v=J(Q,63,1),T=new Date((_===0?1:-1)*v/1000+946684800000);return L||T.setTime(T.getTime()+T.getTimezoneOffset()*60000),T.usec=v%1000,T.getMicroSeconds=function(){return this.usec},T.setMicroSeconds=function(x){this.usec=x},T.getUTCMicroSeconds=function(){return this.usec},T},"parseDate"),w=U(function(L){for(var Q=J(L,32),_=J(L,32,32),v=J(L,32,64),T=96,x=[],q=0;q<Q;q++)x[q]=J(L,32,T),T+=32,T+=32;var E=U(function(A){var f=J(L,32,T);if(T+=32,f==4294967295)return null;var B;if(A==23||A==20)return B=J(L,f*8,T),T+=f*8,B;if(A==25)return B=L.toString(this.encoding,T>>3,(T+=f<<3)>>3),B;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),N=U(function(A,f){var B=[],C;if(A.length>1){var c=A.shift();for(C=0;C<c;C++)B[C]=N(A,f);A.unshift(c)}else for(C=0;C<A[0];C++)B[C]=E(f);return B},"parse");return N(x,v)},"parseArray"),D=U(function(L){return L.toString("utf8")},"parseText"),S=U(function(L){return L===null?null:J(L,8)>0},"parseBool"),F=U(function(L){L(20,Z),L(21,Y),L(23,M),L(26,M),L(1700,R),L(700,G),L(701,V),L(16,S),L(1114,P.bind(null,!1)),L(1184,P.bind(null,!0)),L(1000,w),L(1007,w),L(1016,w),L(1008,w),L(1009,w),L(25,D)},"init");$.exports={init:F}}),jZ=o((W,$)=>{u(),$.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}}),B4=o((W)=>{u();var $=hZ(),Z=fZ(),J=E7(),X=jZ();W.getTypeParser=G,W.setTypeParser=V,W.arrayParser=J,W.builtins=X;var Y={text:{},binary:{}};function M(R){return String(R)}U(M,"noParse");function G(R,P){return P=P||"text",Y[P]&&Y[P][R]||M}U(G,"getTypeParser");function V(R,P,w){typeof P=="function"&&(w=P,P="text"),Y[P][R]=w}U(V,"setTypeParser"),$.init(function(R,P){Y.text[R]=P}),Z.init(function(R,P){Y.binary[R]=P})}),K9=o((W,$)=>{u();var Z=B4();function J(X){this._types=X||Z,this.text={},this.binary={}}U(J,"TypeOverrides"),J.prototype.getOverrides=function(X){switch(X){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(X,Y,M){typeof Y=="function"&&(M=Y,Y="text"),this.getOverrides(Y)[X]=M},J.prototype.getTypeParser=function(X,Y){return Y=Y||"text",this.getOverrides(Y)[X]||this._types.getTypeParser(X,Y)},$.exports=J});function iW(W){let $=1779033703,Z=3144134277,J=1013904242,X=2773480762,Y=1359893119,M=2600822924,G=528734635,V=1541459225,R=0,P=0,w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],D=U((v,T)=>v>>>T|v<<32-T,"rrot"),S=new Uint32Array(64),F=new Uint8Array(64),L=U(()=>{for(let B=0,C=0;B<16;B++,C+=4)S[B]=F[C]<<24|F[C+1]<<16|F[C+2]<<8|F[C+3];for(let B=16;B<64;B++){let C=D(S[B-15],7)^D(S[B-15],18)^S[B-15]>>>3,c=D(S[B-2],17)^D(S[B-2],19)^S[B-2]>>>10;S[B]=S[B-16]+C+S[B-7]+c|0}let v=$,T=Z,x=J,q=X,E=Y,N=M,A=G,f=V;for(let B=0;B<64;B++){let C=D(E,6)^D(E,11)^D(E,25),c=E&N^~E&A,m=f+C+c+w[B]+S[B]|0,b=D(v,2)^D(v,13)^D(v,22),g=v&T^v&x^T&x,p=b+g|0;f=A,A=N,N=E,E=q+m|0,q=x,x=T,T=v,v=m+p|0}$=$+v|0,Z=Z+T|0,J=J+x|0,X=X+q|0,Y=Y+E|0,M=M+N|0,G=G+A|0,V=V+f|0,P=0},"process"),Q=U((v)=>{typeof v=="string"&&(v=new TextEncoder().encode(v));for(let T=0;T<v.length;T++)F[P++]=v[T],P===64&&L();R+=v.length},"add"),_=U(()=>{if(F[P++]=128,P==64&&L(),P+8>64){for(;P<64;)F[P++]=0;L()}for(;P<58;)F[P++]=0;let v=R*8;F[P++]=v/1099511627776&255,F[P++]=v/4294967296&255,F[P++]=v>>>24,F[P++]=v>>>16&255,F[P++]=v>>>8&255,F[P++]=v&255,L();let T=new Uint8Array(32);return T[0]=$>>>24,T[1]=$>>>16&255,T[2]=$>>>8&255,T[3]=$&255,T[4]=Z>>>24,T[5]=Z>>>16&255,T[6]=Z>>>8&255,T[7]=Z&255,T[8]=J>>>24,T[9]=J>>>16&255,T[10]=J>>>8&255,T[11]=J&255,T[12]=X>>>24,T[13]=X>>>16&255,T[14]=X>>>8&255,T[15]=X&255,T[16]=Y>>>24,T[17]=Y>>>16&255,T[18]=Y>>>8&255,T[19]=Y&255,T[20]=M>>>24,T[21]=M>>>16&255,T[22]=M>>>8&255,T[23]=M&255,T[24]=G>>>24,T[25]=G>>>16&255,T[26]=G>>>8&255,T[27]=G&255,T[28]=V>>>24,T[29]=V>>>16&255,T[30]=V>>>8&255,T[31]=V&255,T},"digest");return W===void 0?{add:Q,digest:_}:(Q(W),_())}var AZ=d1(()=>{u(),U(iW,"sha256")}),a0,H9,NZ=d1(()=>{u(),a0=class W{constructor(){t(this,"_dataLength",0),t(this,"_bufferLength",0),t(this,"_state",new Int32Array(4)),t(this,"_buffer",new ArrayBuffer(68)),t(this,"_buffer8"),t(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,Z=!1){return this.onePassHasher.start().appendByteArray($).end(Z)}static hashStr($,Z=!1){return this.onePassHasher.start().appendStr($).end(Z)}static hashAsciiStr($,Z=!1){return this.onePassHasher.start().appendAsciiStr($).end(Z)}static _hex($){let{hexChars:Z,hexOut:J}=W,X,Y,M,G;for(G=0;G<4;G+=1)for(Y=G*8,X=$[G],M=0;M<8;M+=2)J[Y+1+M]=Z.charAt(X&15),X>>>=4,J[Y+0+M]=Z.charAt(X&15),X>>>=4;return J.join("")}static _md5cycle($,Z){let J=$[0],X=$[1],Y=$[2],M=$[3];J+=(X&Y|~X&M)+Z[0]-680876936|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[1]-389564586|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[2]+606105819|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[3]-1044525330|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[4]-176418897|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[5]+1200080426|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[6]-1473231341|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[7]-45705983|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[8]+1770035416|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[9]-1958414417|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[10]-42063|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[11]-1990404162|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[12]+1804603682|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[13]-40341101|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[14]-1502002290|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[15]+1236535329|0,X=(X<<22|X>>>10)+Y|0,J+=(X&M|Y&~M)+Z[1]-165796510|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[6]-1069501632|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[11]+643717713|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[0]-373897302|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[5]-701558691|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[10]+38016083|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[15]-660478335|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[4]-405537848|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[9]+568446438|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[14]-1019803690|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[3]-187363961|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[8]+1163531501|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[13]-1444681467|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[2]-51403784|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[7]+1735328473|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[12]-1926607734|0,X=(X<<20|X>>>12)+Y|0,J+=(X^Y^M)+Z[5]-378558|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[8]-2022574463|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[11]+1839030562|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[14]-35309556|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[1]-1530992060|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[4]+1272893353|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[7]-155497632|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[10]-1094730640|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[13]+681279174|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[0]-358537222|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[3]-722521979|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[6]+76029189|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[9]-640364487|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[12]-421815835|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[15]+530742520|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[2]-995338651|0,X=(X<<23|X>>>9)+Y|0,J+=(Y^(X|~M))+Z[0]-198630844|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[7]+1126891415|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[14]-1416354905|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[5]-57434055|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[12]+1700485571|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[3]-1894986606|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[10]-1051523|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[1]-2054922799|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[8]+1873313359|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[15]-30611744|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[6]-1560198380|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[13]+1309151649|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[4]-145523070|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[11]-1120210379|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[2]+718787259|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[9]-343485551|0,X=(X<<21|X>>>11)+Y|0,$[0]=J+$[0]|0,$[1]=X+$[1]|0,$[2]=Y+$[2]|0,$[3]=M+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M;for(M=0;M<$.length;M+=1){if(Y=$.charCodeAt(M),Y<128)Z[X++]=Y;else if(Y<2048)Z[X++]=(Y>>>6)+192,Z[X++]=Y&63|128;else if(Y<55296||Y>56319)Z[X++]=(Y>>>12)+224,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128;else{if(Y=(Y-55296)*1024+($.charCodeAt(++M)-56320)+65536,Y>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");Z[X++]=(Y>>>18)+240,Z[X++]=Y>>>12&63|128,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128}X>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),X-=64,J[0]=J[16])}return this._bufferLength=X,this}appendAsciiStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M=0;for(;;){for(Y=Math.min($.length-M,64-X);Y--;)Z[X++]=$.charCodeAt(M++);if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}appendByteArray($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M=0;for(;;){for(Y=Math.min($.length-M,64-X);Y--;)Z[X++]=$[M++];if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}getState(){let $=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[$[0],$[1],$[2],$[3]]}}setState($){let{buffer:Z,state:J}=$,X=this._state,Y;for(this._dataLength=$.length,this._bufferLength=$.buflen,X[0]=J[0],X[1]=J[1],X[2]=J[2],X[3]=J[3],Y=0;Y<Z.length;Y+=1)this._buffer8[Y]=Z.charCodeAt(Y)}end($=!1){let Z=this._bufferLength,J=this._buffer8,X=this._buffer32,Y=(Z>>2)+1;this._dataLength+=Z;let M=this._dataLength*8;if(J[Z]=128,J[Z+1]=J[Z+2]=J[Z+3]=0,X.set(W.buffer32Identity.subarray(Y),Y),Z>55&&(W._md5cycle(this._state,X),X.set(W.buffer32Identity)),M<=4294967295)X[14]=M;else{let G=M.toString(16).match(/(.*?)(.{0,8})$/);if(G===null)return;let V=parseInt(G[2],16),R=parseInt(G[1],16)||0;X[14]=V,X[15]=R}return W._md5cycle(this._state,X),$?this._state:W._hex(this._state)}},U(a0,"Md5"),t(a0,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),t(a0,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),t(a0,"hexChars","0123456789abcdef"),t(a0,"hexOut",[]),t(a0,"onePassHasher",new a0),H9=a0}),z9={};S0(z9,{createHash:()=>T7,createHmac:()=>f7,randomBytes:()=>h7});function h7(W){return crypto.getRandomValues(i.alloc(W))}function T7(W){if(W==="sha256")return{update:U(function($){return{digest:U(function(){return i.from(iW($))},"digest")}},"update")};if(W==="md5")return{update:U(function($){return{digest:U(function(){return typeof $=="string"?H9.hashStr($):H9.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function f7(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:U(function(Z){return{digest:U(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof Z=="string"&&(Z=new TextEncoder().encode(Z));let J=$.length;if(J>64)$=iW($);else if(J<64){let V=new Uint8Array(64);V.set($),$=V}let X=new Uint8Array(64),Y=new Uint8Array(64);for(let V=0;V<64;V++)X[V]=54^$[V],Y[V]=92^$[V];let M=new Uint8Array(Z.length+64);M.set(X,0),M.set(Z,64);let G=new Uint8Array(96);return G.set(Y,0),G.set(iW(M),64),i.from(iW(G))},"digest")}},"update")}}var j7=d1(()=>{u(),AZ(),NZ(),U(h7,"randomBytes"),U(T7,"createHash"),U(f7,"createHmac")}),b4=o((W,$)=>{u(),$.exports={host:"localhost",user:r.platform==="win32"?r.env.USERNAME:r.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Z=B4(),J=Z.getTypeParser(20,"text"),X=Z.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(Y){Z.setTypeParser(20,"text",Y?Z.getTypeParser(23,"text"):J),Z.setTypeParser(1016,"text",Y?Z.getTypeParser(1007,"text"):X)})}),I4=o((W,$)=>{u();var Z=(j7(),B1(z9)),J=b4();function X(F){var L=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+L+'"'}U(X,"escapeElement");function Y(F){for(var L="{",Q=0;Q<F.length;Q++)Q>0&&(L=L+","),F[Q]===null||typeof F[Q]>"u"?L=L+"NULL":Array.isArray(F[Q])?L=L+Y(F[Q]):F[Q]instanceof i?L+="\\\\x"+F[Q].toString("hex"):L+=X(M(F[Q]));return L=L+"}",L}U(Y,"arrayString");var M=U(function(F,L){if(F==null)return null;if(F instanceof i)return F;if(ArrayBuffer.isView(F)){var Q=i.from(F.buffer,F.byteOffset,F.byteLength);return Q.length===F.byteLength?Q:Q.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?P(F):R(F):Array.isArray(F)?Y(F):typeof F=="object"?G(F,L):F.toString()},"prepareValue");function G(F,L){if(F&&typeof F.toPostgres=="function"){if(L=L||[],L.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return L.push(F),M(F.toPostgres(M),L)}return JSON.stringify(F)}U(G,"prepareObject");function V(F,L){for(F=""+F;F.length<L;)F="0"+F;return F}U(V,"pad");function R(F){var L=-F.getTimezoneOffset(),Q=F.getFullYear(),_=Q<1;_&&(Q=Math.abs(Q)+1);var v=V(Q,4)+"-"+V(F.getMonth()+1,2)+"-"+V(F.getDate(),2)+"T"+V(F.getHours(),2)+":"+V(F.getMinutes(),2)+":"+V(F.getSeconds(),2)+"."+V(F.getMilliseconds(),3);return L<0?(v+="-",L*=-1):v+="+",v+=V(Math.floor(L/60),2)+":"+V(L%60,2),_&&(v+=" BC"),v}U(R,"dateToString");function P(F){var L=F.getUTCFullYear(),Q=L<1;Q&&(L=Math.abs(L)+1);var _=V(L,4)+"-"+V(F.getUTCMonth()+1,2)+"-"+V(F.getUTCDate(),2)+"T"+V(F.getUTCHours(),2)+":"+V(F.getUTCMinutes(),2)+":"+V(F.getUTCSeconds(),2)+"."+V(F.getUTCMilliseconds(),3);return _+="+00:00",Q&&(_+=" BC"),_}U(P,"dateToStringUTC");function w(F,L,Q){return F=typeof F=="string"?{text:F}:F,L&&(typeof L=="function"?F.callback=L:F.values=L),Q&&(F.callback=Q),F}U(w,"normalizeQueryConfig");var D=U(function(F){return Z.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),S=U(function(F,L,Q){var _=D(L+F),v=D(i.concat([i.from(_),Q]));return"md5"+v},"postgresMd5PasswordHash");$.exports={prepareValue:U(function(F){return M(F)},"prepareValueWrapper"),normalizeQueryConfig:w,postgresMd5PasswordHash:S,md5:D}}),aW={};S0(aW,{default:()=>A7});var A7,y4=d1(()=>{u(),A7={}}),CZ=o((W,$)=>{u();var Z=(j7(),B1(z9));function J(L){if(L.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let Q=Z.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:Q,response:"n,,n=*,r="+Q,message:"SASLInitialResponse"}}U(J,"startSession");function X(L,Q,_){if(L.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof _!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let v=R(_);if(v.nonce.startsWith(L.clientNonce)){if(v.nonce.length===L.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var T=i.from(v.salt,"base64"),x=F(Q,T,v.iteration),q=S(x,"Client Key"),E=D(q),N="n=*,r="+L.clientNonce,A="r="+v.nonce+",s="+v.salt+",i="+v.iteration,f="c=biws,r="+v.nonce,B=N+","+A+","+f,C=S(E,B),c=w(q,C),m=c.toString("base64"),b=S(x,"Server Key"),g=S(b,B);L.message="SASLResponse",L.serverSignature=g.toString("base64"),L.response=f+",p="+m}U(X,"continueSession");function Y(L,Q){if(L.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:_}=P(Q);if(_!==L.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}U(Y,"finalizeSession");function M(L){if(typeof L!="string")throw TypeError("SASL: text must be a string");return L.split("").map((Q,_)=>L.charCodeAt(_)).every((Q)=>Q>=33&&Q<=43||Q>=45&&Q<=126)}U(M,"isPrintableChars");function G(L){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(L)}U(G,"isBase64");function V(L){if(typeof L!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(L.split(",").map((Q)=>{if(!/^.=/.test(Q))throw Error("SASL: Invalid attribute pair entry");let _=Q[0],v=Q.substring(2);return[_,v]}))}U(V,"parseAttributePairs");function R(L){let Q=V(L),_=Q.get("r");if(_){if(!M(_))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let v=Q.get("s");if(v){if(!G(v))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let T=Q.get("i");if(T){if(!/^[1-9][0-9]*$/.test(T))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let x=parseInt(T,10);return{nonce:_,salt:v,iteration:x}}U(R,"parseServerFirstMessage");function P(L){let Q=V(L).get("v");if(Q){if(!G(Q))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:Q}}U(P,"parseServerFinalMessage");function w(L,Q){if(!i.isBuffer(L))throw TypeError("first argument must be a Buffer");if(!i.isBuffer(Q))throw TypeError("second argument must be a Buffer");if(L.length!==Q.length)throw Error("Buffer lengths must match");if(L.length===0)throw Error("Buffers cannot be empty");return i.from(L.map((_,v)=>L[v]^Q[v]))}U(w,"xorBuffers");function D(L){return Z.createHash("sha256").update(L).digest()}U(D,"sha256");function S(L,Q){return Z.createHmac("sha256",L).update(Q).digest()}U(S,"hmacSha256");function F(L,Q,_){for(var v=S(L,i.concat([Q,i.from([0,0,0,1])])),T=v,x=0;x<_-1;x++)v=S(L,v),T=w(T,v);return T}U(F,"Hi"),$.exports={startSession:J,continueSession:X,finalizeSession:Y}}),U9={};S0(U9,{join:()=>N7});function N7(...W){return W.join("/")}var C7=d1(()=>{u(),U(N7,"join")}),V9={};S0(V9,{stat:()=>q7});function q7(W,$){$(Error("No filesystem"))}var O7=d1(()=>{u(),U(q7,"stat")}),P9={};S0(P9,{default:()=>x7});var x7,B7=d1(()=>{u(),x7={}}),b7={};S0(b7,{StringDecoder:()=>I7});var Y9,I7,qZ=d1(()=>{u(),Y9=class{constructor($){t(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},U(Y9,"StringDecoder"),I7=Y9}),OZ=o((W,$)=>{u();var{Transform:Z}=(B7(),B1(P9)),{StringDecoder:J}=(qZ(),B1(b7)),X=Symbol("last"),Y=Symbol("decoder");function M(w,D,S){let F;if(this.overflow){if(F=this[Y].write(w).split(this.matcher),F.length===1)return S();F.shift(),this.overflow=!1}else this[X]+=this[Y].write(w),F=this[X].split(this.matcher);this[X]=F.pop();for(let L=0;L<F.length;L++)try{V(this,this.mapper(F[L]))}catch(Q){return S(Q)}if(this.overflow=this[X].length>this.maxLength,this.overflow&&!this.skipOverflow){S(Error("maximum buffer reached"));return}S()}U(M,"transform");function G(w){if(this[X]+=this[Y].end(),this[X])try{V(this,this.mapper(this[X]))}catch(D){return w(D)}w()}U(G,"flush");function V(w,D){D!==void 0&&w.push(D)}U(V,"push");function R(w){return w}U(R,"noop");function P(w,D,S){switch(w=w||/\r?\n/,D=D||R,S=S||{},arguments.length){case 1:typeof w=="function"?(D=w,w=/\r?\n/):typeof w=="object"&&!(w instanceof RegExp)&&!w[Symbol.split]&&(S=w,w=/\r?\n/);break;case 2:typeof w=="function"?(S=D,D=w,w=/\r?\n/):typeof D=="object"&&(S=D,D=R)}S=Object.assign({},S),S.autoDestroy=!0,S.transform=M,S.flush=G,S.readableObjectMode=!0;let F=new Z(S);return F[X]="",F[Y]=new J("utf8"),F.matcher=w,F.mapper=D,F.maxLength=S.maxLength,F.skipOverflow=S.skipOverflow||!1,F.overflow=!1,F._destroy=function(L,Q){this._writableState.errorEmitted=!1,Q(L)},F}U(P,"split"),$.exports=P}),xZ=o((W,$)=>{u();var Z=(C7(),B1(U9)),J=(B7(),B1(P9)).Stream,X=OZ(),Y=(y4(),B1(aW)),M=5432,G=r.platform==="win32",V=r.stderr,R=56,P=7,w=61440,D=32768;function S(q){return(q&w)==D}U(S,"isRegFile");var F=["host","port","database","user","password"],L=F.length,Q=F[L-1];function _(){var q=V instanceof J&&V.writable===!0;if(q){var E=Array.prototype.slice.call(arguments).concat(`
28
- `);V.write(Y.format.apply(Y,E))}}U(_,"warn"),Object.defineProperty($.exports,"isWin",{get:U(function(){return G},"get"),set:U(function(q){G=q},"set")}),$.exports.warnTo=function(q){var E=V;return V=q,E},$.exports.getFileName=function(q){var E=q||r.env,N=E.PGPASSFILE||(G?Z.join(E.APPDATA||"./","postgresql","pgpass.conf"):Z.join(E.HOME||"./",".pgpass"));return N},$.exports.usePgPass=function(q,E){return Object.prototype.hasOwnProperty.call(r.env,"PGPASSWORD")?!1:G?!0:(E=E||"<unkn>",S(q.mode)?q.mode&(R|P)?(_('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',E),!1):!0:(_('WARNING: password file "%s" is not a plain file',E),!1))};var v=$.exports.match=function(q,E){return F.slice(0,-1).reduce(function(N,A,f){return f==1&&Number(q[A]||M)===Number(E[A])?N&&!0:N&&(E[A]==="*"||E[A]===q[A])},!0)};$.exports.getPassword=function(q,E,N){var A,f=E.pipe(X());function B(m){var b=T(m);b&&x(b)&&v(q,b)&&(A=b[Q],f.end())}U(B,"onLine");var C=U(function(){E.destroy(),N(A)},"onEnd"),c=U(function(m){E.destroy(),_("WARNING: error on reading file: %s",m),N(void 0)},"onErr");E.on("error",c),f.on("data",B).on("end",C).on("error",c)};var T=$.exports.parseLine=function(q){if(q.length<11||q.match(/^\s+#/))return null;for(var E="",N="",A=0,f=0,B=0,C={},c=!1,m=U(function(g,p,d){var J1=q.substring(p,d);Object.hasOwnProperty.call(r.env,"PGPASS_NO_DEESCAPE")||(J1=J1.replace(/\\([:\\])/g,"$1")),C[F[g]]=J1},"addToObj"),b=0;b<q.length-1;b+=1){if(E=q.charAt(b+1),N=q.charAt(b),c=A==L-1,c){m(A,f);break}b>=0&&E==":"&&N!=="\\"&&(m(A,f,b+1),f=b+2,A+=1)}return C=Object.keys(C).length===L?C:null,C},x=$.exports.isValidEntry=function(q){for(var E={0:function(C){return C.length>0},1:function(C){return C==="*"?!0:(C=Number(C),isFinite(C)&&C>0&&C<9007199254740992&&Math.floor(C)===C)},2:function(C){return C.length>0},3:function(C){return C.length>0},4:function(C){return C.length>0}},N=0;N<F.length;N+=1){var A=E[N],f=q[F[N]]||"",B=A(f);if(!B)return!1}return!0}}),BZ=o((W,$)=>{u();var Z=(C7(),B1(U9)),J=(O7(),B1(V9)),X=xZ();$.exports=function(Y,M){var G=X.getFileName();J.stat(G,function(V,R){if(V||!X.usePgPass(R,G))return M(void 0);var P=J.createReadStream(G);X.getPassword(Y,P,M)})},$.exports.warnTo=X.warnTo}),y7={};S0(y7,{default:()=>g7});var g7,bZ=d1(()=>{u(),g7={}}),IZ=o((W,$)=>{u();var Z=(_7(),B1(S7)),J=(O7(),B1(V9));function X(Y){if(Y.charAt(0)==="/"){var G=Y.split(" ");return{host:G[0],database:G[1]}}var M=Z.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(Y)?encodeURI(Y).replace(/\%25(\d\d)/g,"%$1"):Y,!0),G=M.query;for(var V in G)Array.isArray(G[V])&&(G[V]=G[V][G[V].length-1]);var R=(M.auth||":").split(":");if(G.user=R[0],G.password=R.splice(1).join(":"),G.port=M.port,M.protocol=="socket:")return G.host=decodeURI(M.pathname),G.database=M.query.db,G.client_encoding=M.query.encoding,G;G.host||(G.host=M.hostname);var P=M.pathname;if(!G.host&&P&&/^%2f/i.test(P)){var w=P.split("/");G.host=decodeURIComponent(w[0]),P=w.splice(1).join("/")}switch(P&&P.charAt(0)==="/"&&(P=P.slice(1)||null),G.database=P&&decodeURI(P),(G.ssl==="true"||G.ssl==="1")&&(G.ssl=!0),G.ssl==="0"&&(G.ssl=!1),(G.sslcert||G.sslkey||G.sslrootcert||G.sslmode)&&(G.ssl={}),G.sslcert&&(G.ssl.cert=J.readFileSync(G.sslcert).toString()),G.sslkey&&(G.ssl.key=J.readFileSync(G.sslkey).toString()),G.sslrootcert&&(G.ssl.ca=J.readFileSync(G.sslrootcert).toString()),G.sslmode){case"disable":{G.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{G.ssl.rejectUnauthorized=!1;break}}return G}U(X,"parse"),$.exports=X,X.parse=X}),F9=o((W,$)=>{u();var Z=(bZ(),B1(y7)),J=b4(),X=IZ().parse,Y=U(function(w,D,S){return S===void 0?S=r.env["PG"+w.toUpperCase()]:S===!1||(S=r.env[S]),D[w]||S||J[w]},"val"),M=U(function(){switch(r.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return J.ssl},"readSSLConfigFromEnvironment"),G=U(function(w){return"'"+(""+w).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),V=U(function(w,D,S){var F=D[S];F!=null&&w.push(S+"="+G(F))},"add"),R=class{constructor(D){D=typeof D=="string"?X(D):D||{},D.connectionString&&(D=Object.assign({},D,X(D.connectionString))),this.user=Y("user",D),this.database=Y("database",D),this.database===void 0&&(this.database=this.user),this.port=parseInt(Y("port",D),10),this.host=Y("host",D),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:Y("password",D)}),this.binary=Y("binary",D),this.options=Y("options",D),this.ssl=typeof D.ssl>"u"?M():D.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=Y("client_encoding",D),this.replication=Y("replication",D),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=Y("application_name",D,"PGAPPNAME"),this.fallback_application_name=Y("fallback_application_name",D,!1),this.statement_timeout=Y("statement_timeout",D,!1),this.lock_timeout=Y("lock_timeout",D,!1),this.idle_in_transaction_session_timeout=Y("idle_in_transaction_session_timeout",D,!1),this.query_timeout=Y("query_timeout",D,!1),D.connectionTimeoutMillis===void 0?this.connect_timeout=r.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(D.connectionTimeoutMillis/1000),D.keepAlive===!1?this.keepalives=0:D.keepAlive===!0&&(this.keepalives=1),typeof D.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(D.keepAliveInitialDelayMillis/1000))}getLibpqConnectionString(D){var S=[];V(S,this,"user"),V(S,this,"password"),V(S,this,"port"),V(S,this,"application_name"),V(S,this,"fallback_application_name"),V(S,this,"connect_timeout"),V(S,this,"options");var F=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(V(S,F,"sslmode"),V(S,F,"sslca"),V(S,F,"sslkey"),V(S,F,"sslcert"),V(S,F,"sslrootcert"),this.database&&S.push("dbname="+G(this.database)),this.replication&&S.push("replication="+G(this.replication)),this.host&&S.push("host="+G(this.host)),this.isDomainSocket)return D(null,S.join(" "));this.client_encoding&&S.push("client_encoding="+G(this.client_encoding)),Z.lookup(this.host,function(L,Q){return L?D(L,null):(S.push("hostaddr="+G(Q)),D(null,S.join(" ")))})}};U(R,"ConnectionParameters");var P=R;$.exports=P}),yZ=o((W,$)=>{u();var Z=B4(),J=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,X=class{constructor(G,V){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=V,this.RowCtor=null,this.rowAsArray=G==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(G){var V;G.text?V=J.exec(G.text):V=J.exec(G.command),V&&(this.command=V[1],V[3]?(this.oid=parseInt(V[2],10),this.rowCount=parseInt(V[3],10)):V[2]&&(this.rowCount=parseInt(V[2],10)))}_parseRowAsArray(G){for(var V=Array(G.length),R=0,P=G.length;R<P;R++){var w=G[R];w!==null?V[R]=this._parsers[R](w):V[R]=null}return V}parseRow(G){for(var V={},R=0,P=G.length;R<P;R++){var w=G[R],D=this.fields[R].name;w!==null?V[D]=this._parsers[R](w):V[D]=null}return V}addRow(G){this.rows.push(G)}addFields(G){this.fields=G,this.fields.length&&(this._parsers=Array(G.length));for(var V=0;V<G.length;V++){var R=G[V];this._types?this._parsers[V]=this._types.getTypeParser(R.dataTypeID,R.format||"text"):this._parsers[V]=Z.getTypeParser(R.dataTypeID,R.format||"text")}}};U(X,"Result");var Y=X;$.exports=Y}),gZ=o((W,$)=>{u();var{EventEmitter:Z}=S8(),J=yZ(),X=I4(),Y=class extends Z{constructor(V,R,P){super(),V=X.normalizeQueryConfig(V,R,P),this.text=V.text,this.values=V.values,this.rows=V.rows,this.types=V.types,this.name=V.name,this.binary=V.binary,this.portal=V.portal||"",this.callback=V.callback,this._rowMode=V.rowMode,r.domain&&V.callback&&(this.callback=r.domain.bind(V.callback)),this._result=new J(this._rowMode,this.types),this._results=this._result,this.isPreparedStatement=!1,this._canceledDueToError=!1,this._promise=null}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new J(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(V){this._checkForMultirow(),this._result.addFields(V.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(V){let R;if(!this._canceledDueToError){try{R=this._result.parseRow(V.fields)}catch(P){this._canceledDueToError=P;return}this.emit("row",R,this._result),this._accumulateRows&&this._result.addRow(R)}}handleCommandComplete(V,R){this._checkForMultirow(),this._result.addCommandComplete(V),this.rows&&R.sync()}handleEmptyQuery(V){this.rows&&V.sync()}handleError(V,R){if(this._canceledDueToError&&(V=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(V);this.emit("error",V)}handleReadyForQuery(V){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,V);if(this.callback)try{this.callback(null,this._results)}catch(R){r.nextTick(()=>{throw R})}this.emit("end",this._results)}submit(V){if(typeof this.text!="string"&&typeof this.name!="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let R=V.parsedStatements[this.name];return this.text&&R&&this.text!==R?Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(V):V.query(this.text),null)}hasBeenParsed(V){return this.name&&V.parsedStatements[this.name]}handlePortalSuspended(V){this._getRows(V,this.rows)}_getRows(V,R){V.execute({portal:this.portal,rows:R}),R?V.flush():V.sync()}prepare(V){this.isPreparedStatement=!0,this.hasBeenParsed(V)||V.parse({text:this.text,name:this.name,types:this.types});try{V.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:X.prepareValue})}catch(R){this.handleError(R,V);return}V.describe({type:"P",name:this.portal||""}),this._getRows(V,this.rows)}handleCopyInResponse(V){V.sendCopyFail("No source stream defined")}handleCopyData(V,R){}};U(Y,"Query");var M=Y;$.exports=M}),m7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.NoticeMessage=W.DataRowMessage=W.CommandCompleteMessage=W.ReadyForQueryMessage=W.NotificationResponseMessage=W.BackendKeyDataMessage=W.AuthenticationMD5Password=W.ParameterStatusMessage=W.ParameterDescriptionMessage=W.RowDescriptionMessage=W.Field=W.CopyResponse=W.CopyDataMessage=W.DatabaseError=W.copyDone=W.emptyQuery=W.replicationStart=W.portalSuspended=W.noData=W.closeComplete=W.bindComplete=W.parseComplete=void 0,W.parseComplete={name:"parseComplete",length:5},W.bindComplete={name:"bindComplete",length:5},W.closeComplete={name:"closeComplete",length:5},W.noData={name:"noData",length:5},W.portalSuspended={name:"portalSuspended",length:5},W.replicationStart={name:"replicationStart",length:4},W.emptyQuery={name:"emptyQuery",length:4},W.copyDone={name:"copyDone",length:4};var $=class extends Error{constructor(b,g,p){super(b),this.length=g,this.name=p}};U($,"DatabaseError");var Z=$;W.DatabaseError=Z;var J=class{constructor(b,g){this.length=b,this.chunk=g,this.name="copyData"}};U(J,"CopyDataMessage");var X=J;W.CopyDataMessage=X;var Y=class{constructor(b,g,p,d){this.length=b,this.name=g,this.binary=p,this.columnTypes=Array(d)}};U(Y,"CopyResponse");var M=Y;W.CopyResponse=M;var G=class{constructor(b,g,p,d,J1,s,s1){this.name=b,this.tableID=g,this.columnID=p,this.dataTypeID=d,this.dataTypeSize=J1,this.dataTypeModifier=s,this.format=s1}};U(G,"Field");var V=G;W.Field=V;var R=class{constructor(b,g){this.length=b,this.fieldCount=g,this.name="rowDescription",this.fields=Array(this.fieldCount)}};U(R,"RowDescriptionMessage");var P=R;W.RowDescriptionMessage=P;var w=class{constructor(b,g){this.length=b,this.parameterCount=g,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}};U(w,"ParameterDescriptionMessage");var D=w;W.ParameterDescriptionMessage=D;var S=class{constructor(b,g,p){this.length=b,this.parameterName=g,this.parameterValue=p,this.name="parameterStatus"}};U(S,"ParameterStatusMessage");var F=S;W.ParameterStatusMessage=F;var L=class{constructor(b,g){this.length=b,this.salt=g,this.name="authenticationMD5Password"}};U(L,"AuthenticationMD5Password");var Q=L;W.AuthenticationMD5Password=Q;var _=class{constructor(b,g,p){this.length=b,this.processID=g,this.secretKey=p,this.name="backendKeyData"}};U(_,"BackendKeyDataMessage");var v=_;W.BackendKeyDataMessage=v;var T=class{constructor(b,g,p,d){this.length=b,this.processId=g,this.channel=p,this.payload=d,this.name="notification"}};U(T,"NotificationResponseMessage");var x=T;W.NotificationResponseMessage=x;var q=class{constructor(b,g){this.length=b,this.status=g,this.name="readyForQuery"}};U(q,"ReadyForQueryMessage");var E=q;W.ReadyForQueryMessage=E;var N=class{constructor(b,g){this.length=b,this.text=g,this.name="commandComplete"}};U(N,"CommandCompleteMessage");var A=N;W.CommandCompleteMessage=A;var f=class{constructor(b,g){this.length=b,this.fields=g,this.name="dataRow",this.fieldCount=g.length}};U(f,"DataRowMessage");var B=f;W.DataRowMessage=B;var C=class{constructor(b,g){this.length=b,this.message=g,this.name="notice"}};U(C,"NoticeMessage");var c=C;W.NoticeMessage=c}),mZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Writer=void 0;var $=class{constructor(X=256){this.size=X,this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(X)}ensure(X){if(this.buffer.length-this.offset<X){let Y=this.buffer,M=Y.length+(Y.length>>1)+X;this.buffer=i.allocUnsafe(M),Y.copy(this.buffer)}}addInt32(X){return this.ensure(4),this.buffer[this.offset++]=X>>>24&255,this.buffer[this.offset++]=X>>>16&255,this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addInt16(X){return this.ensure(2),this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addCString(X){if(!X)this.ensure(1);else{let Y=i.byteLength(X);this.ensure(Y+1),this.buffer.write(X,this.offset,"utf-8"),this.offset+=Y}return this.buffer[this.offset++]=0,this}addString(X=""){let Y=i.byteLength(X);return this.ensure(Y),this.buffer.write(X,this.offset),this.offset+=Y,this}add(X){return this.ensure(X.length),X.copy(this.buffer,this.offset),this.offset+=X.length,this}join(X){if(X){this.buffer[this.headerPosition]=X;let Y=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(Y,this.headerPosition+1)}return this.buffer.slice(X?0:5,this.offset)}flush(X){let Y=this.join(X);return this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(this.size),Y}};U($,"Writer");var Z=$;W.Writer=Z}),cZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.serialize=void 0;var $=mZ(),Z=new $.Writer,J=U((b)=>{Z.addInt16(3).addInt16(0);for(let d of Object.keys(b))Z.addCString(d).addCString(b[d]);Z.addCString("client_encoding").addCString("UTF8");let g=Z.addCString("").flush(),p=g.length+4;return new $.Writer().addInt32(p).add(g).flush()},"startup"),X=U(()=>{let b=i.allocUnsafe(8);return b.writeInt32BE(8,0),b.writeInt32BE(80877103,4),b},"requestSsl"),Y=U((b)=>Z.addCString(b).flush(112),"password"),M=U(function(b,g){return Z.addCString(b).addInt32(i.byteLength(g)).addString(g),Z.flush(112)},"sendSASLInitialResponseMessage"),G=U(function(b){return Z.addString(b).flush(112)},"sendSCRAMClientFinalMessage"),V=U((b)=>Z.addCString(b).flush(81),"query"),R=[],P=U((b)=>{let g=b.name||"";g.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",g,g.length),console.error("This can cause conflicts and silent errors executing queries"));let p=b.types||R,d=p.length,J1=Z.addCString(g).addCString(b.text).addInt16(d);for(let s=0;s<d;s++)J1.addInt32(p[s]);return Z.flush(80)},"parse"),w=new $.Writer,D=U(function(b,g){for(let p=0;p<b.length;p++){let d=g?g(b[p],p):b[p];d==null?(Z.addInt16(0),w.addInt32(-1)):d instanceof i?(Z.addInt16(1),w.addInt32(d.length),w.add(d)):(Z.addInt16(0),w.addInt32(i.byteLength(d)),w.addString(d))}},"writeValues"),S=U((b={})=>{let g=b.portal||"",p=b.statement||"",d=b.binary||!1,J1=b.values||R,s=J1.length;return Z.addCString(g).addCString(p),Z.addInt16(s),D(J1,b.valueMapper),Z.addInt16(s),Z.add(w.flush()),Z.addInt16(d?1:0),Z.flush(66)},"bind"),F=i.from([69,0,0,0,9,0,0,0,0,0]),L=U((b)=>{if(!b||!b.portal&&!b.rows)return F;let g=b.portal||"",p=b.rows||0,d=i.byteLength(g),J1=4+d+1+4,s=i.allocUnsafe(1+J1);return s[0]=69,s.writeInt32BE(J1,1),s.write(g,5,"utf-8"),s[d+5]=0,s.writeUInt32BE(p,s.length-4),s},"execute"),Q=U((b,g)=>{let p=i.allocUnsafe(16);return p.writeInt32BE(16,0),p.writeInt16BE(1234,4),p.writeInt16BE(5678,6),p.writeInt32BE(b,8),p.writeInt32BE(g,12),p},"cancel"),_=U((b,g)=>{let p=4+i.byteLength(g)+1,d=i.allocUnsafe(1+p);return d[0]=b,d.writeInt32BE(p,1),d.write(g,5,"utf-8"),d[p]=0,d},"cstringMessage"),v=Z.addCString("P").flush(68),T=Z.addCString("S").flush(68),x=U((b)=>b.name?_(68,`${b.type}${b.name||""}`):b.type==="P"?v:T,"describe"),q=U((b)=>{let g=`${b.type}${b.name||""}`;return _(67,g)},"close"),E=U((b)=>Z.add(b).flush(100),"copyData"),N=U((b)=>_(102,b),"copyFail"),A=U((b)=>i.from([b,0,0,0,4]),"codeOnlyBuffer"),f=A(72),B=A(83),C=A(88),c=A(99),m={startup:J,password:Y,requestSsl:X,sendSASLInitialResponseMessage:M,sendSCRAMClientFinalMessage:G,query:V,parse:P,bind:S,execute:L,describe:x,close:q,flush:U(()=>f,"flush"),sync:U(()=>B,"sync"),end:U(()=>C,"end"),copyData:E,copyDone:U(()=>c,"copyDone"),copyFail:N,cancel:Q};W.serialize=m}),uZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.BufferReader=void 0;var $=i.allocUnsafe(0),Z=class{constructor(Y=0){this.offset=Y,this.buffer=$,this.encoding="utf-8"}setBuffer(Y,M){this.offset=Y,this.buffer=M}int16(){let Y=this.buffer.readInt16BE(this.offset);return this.offset+=2,Y}byte(){let Y=this.buffer[this.offset];return this.offset++,Y}int32(){let Y=this.buffer.readInt32BE(this.offset);return this.offset+=4,Y}uint32(){let Y=this.buffer.readUInt32BE(this.offset);return this.offset+=4,Y}string(Y){let M=this.buffer.toString(this.encoding,this.offset,this.offset+Y);return this.offset+=Y,M}cstring(){let Y=this.offset,M=Y;for(;this.buffer[M++]!==0;);return this.offset=M,this.buffer.toString(this.encoding,Y,M-1)}bytes(Y){let M=this.buffer.slice(this.offset,this.offset+Y);return this.offset+=Y,M}};U(Z,"BufferReader");var J=Z;W.BufferReader=J}),lZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Parser=void 0;var $=m7(),Z=uZ(),J=1,X=4,Y=J+X,M=i.allocUnsafe(0),G=class{constructor(P){if(this.buffer=M,this.bufferLength=0,this.bufferOffset=0,this.reader=new Z.BufferReader,P?.mode==="binary")throw Error("Binary mode not supported yet");this.mode=P?.mode||"text"}parse(P,w){this.mergeBuffer(P);let D=this.bufferOffset+this.bufferLength,S=this.bufferOffset;for(;S+Y<=D;){let F=this.buffer[S],L=this.buffer.readUInt32BE(S+J),Q=J+L;if(Q+S<=D){let _=this.handlePacket(S+Y,F,L,this.buffer);w(_),S+=Q}else break}S===D?(this.buffer=M,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=D-S,this.bufferOffset=S)}mergeBuffer(P){if(this.bufferLength>0){let w=this.bufferLength+P.byteLength;if(w+this.bufferOffset>this.buffer.byteLength){let D;if(w<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)D=this.buffer;else{let S=this.buffer.byteLength*2;for(;w>=S;)S*=2;D=i.allocUnsafe(S)}this.buffer.copy(D,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=D,this.bufferOffset=0}P.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=w}else this.buffer=P,this.bufferOffset=0,this.bufferLength=P.byteLength}handlePacket(P,w,D,S){switch(w){case 50:return $.bindComplete;case 49:return $.parseComplete;case 51:return $.closeComplete;case 110:return $.noData;case 115:return $.portalSuspended;case 99:return $.copyDone;case 87:return $.replicationStart;case 73:return $.emptyQuery;case 68:return this.parseDataRowMessage(P,D,S);case 67:return this.parseCommandCompleteMessage(P,D,S);case 90:return this.parseReadyForQueryMessage(P,D,S);case 65:return this.parseNotificationMessage(P,D,S);case 82:return this.parseAuthenticationResponse(P,D,S);case 83:return this.parseParameterStatusMessage(P,D,S);case 75:return this.parseBackendKeyData(P,D,S);case 69:return this.parseErrorMessage(P,D,S,"error");case 78:return this.parseErrorMessage(P,D,S,"notice");case 84:return this.parseRowDescriptionMessage(P,D,S);case 116:return this.parseParameterDescriptionMessage(P,D,S);case 71:return this.parseCopyInMessage(P,D,S);case 72:return this.parseCopyOutMessage(P,D,S);case 100:return this.parseCopyData(P,D,S);default:return new $.DatabaseError("received invalid response: "+w.toString(16),D,"error")}}parseReadyForQueryMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.string(1);return new $.ReadyForQueryMessage(w,S)}parseCommandCompleteMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.cstring();return new $.CommandCompleteMessage(w,S)}parseCopyData(P,w,D){let S=D.slice(P,P+(w-4));return new $.CopyDataMessage(w,S)}parseCopyInMessage(P,w,D){return this.parseCopyMessage(P,w,D,"copyInResponse")}parseCopyOutMessage(P,w,D){return this.parseCopyMessage(P,w,D,"copyOutResponse")}parseCopyMessage(P,w,D,S){this.reader.setBuffer(P,D);let F=this.reader.byte()!==0,L=this.reader.int16(),Q=new $.CopyResponse(w,S,F,L);for(let _=0;_<L;_++)Q.columnTypes[_]=this.reader.int16();return Q}parseNotificationMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F=this.reader.cstring(),L=this.reader.cstring();return new $.NotificationResponseMessage(w,S,F,L)}parseRowDescriptionMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=new $.RowDescriptionMessage(w,S);for(let L=0;L<S;L++)F.fields[L]=this.parseField();return F}parseField(){let P=this.reader.cstring(),w=this.reader.uint32(),D=this.reader.int16(),S=this.reader.uint32(),F=this.reader.int16(),L=this.reader.int32(),Q=this.reader.int16()===0?"text":"binary";return new $.Field(P,w,D,S,F,L,Q)}parseParameterDescriptionMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=new $.ParameterDescriptionMessage(w,S);for(let L=0;L<S;L++)F.dataTypeIDs[L]=this.reader.int32();return F}parseDataRowMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=Array(S);for(let L=0;L<S;L++){let Q=this.reader.int32();F[L]=Q===-1?null:this.reader.string(Q)}return new $.DataRowMessage(w,F)}parseParameterStatusMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.cstring(),F=this.reader.cstring();return new $.ParameterStatusMessage(w,S,F)}parseBackendKeyData(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F=this.reader.int32();return new $.BackendKeyDataMessage(w,S,F)}parseAuthenticationResponse(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F={name:"authenticationOk",length:w};switch(S){case 0:break;case 3:F.length===8&&(F.name="authenticationCleartextPassword");break;case 5:if(F.length===12){F.name="authenticationMD5Password";let L=this.reader.bytes(4);return new $.AuthenticationMD5Password(w,L)}break;case 10:{F.name="authenticationSASL",F.mechanisms=[];let L;do L=this.reader.cstring(),L&&F.mechanisms.push(L);while(L)}break;case 11:F.name="authenticationSASLContinue",F.data=this.reader.string(w-8);break;case 12:F.name="authenticationSASLFinal",F.data=this.reader.string(w-8);break;default:throw Error("Unknown authenticationOk message type "+S)}return F}parseErrorMessage(P,w,D,S){this.reader.setBuffer(P,D);let F={},L=this.reader.string(1);for(;L!=="\x00";)F[L]=this.reader.cstring(),L=this.reader.string(1);let Q=F.M,_=S==="notice"?new $.NoticeMessage(w,Q):new $.DatabaseError(Q,w,S);return _.severity=F.S,_.code=F.C,_.detail=F.D,_.hint=F.H,_.position=F.P,_.internalPosition=F.p,_.internalQuery=F.q,_.where=F.W,_.schema=F.s,_.table=F.t,_.column=F.c,_.dataType=F.d,_.constraint=F.n,_.file=F.F,_.line=F.L,_.routine=F.R,_}};U(G,"Parser");var V=G;W.Parser=V}),c7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.DatabaseError=W.serialize=W.parse=void 0;var $=m7();Object.defineProperty(W,"DatabaseError",{enumerable:!0,get:U(function(){return $.DatabaseError},"get")});var Z=cZ();Object.defineProperty(W,"serialize",{enumerable:!0,get:U(function(){return Z.serialize},"get")});var J=lZ();function X(Y,M){let G=new J.Parser;return Y.on("data",(V)=>G.parse(V,M)),new Promise((V)=>Y.on("end",()=>V()))}U(X,"parse"),W.parse=X}),u7={};S0(u7,{connect:()=>l7});function l7({socket:W,servername:$}){return W.startTls($),W}var pZ=d1(()=>{u(),U(l7,"connect")}),p7=o((W,$)=>{u();var Z=(tW(),B1(w7)),J=S8().EventEmitter,{parse:X,serialize:Y}=c7(),M=Y.flush(),G=Y.sync(),V=Y.end(),R=class extends J{constructor(D){super(),D=D||{},this.stream=D.stream||new Z.Socket,this._keepAlive=D.keepAlive,this._keepAliveInitialDelayMillis=D.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=D.ssl||!1,this._ending=!1,this._emitMessage=!1;var S=this;this.on("newListener",function(F){F==="message"&&(S._emitMessage=!0)})}connect(D,S){var F=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(D,S),this.stream.once("connect",function(){F._keepAlive&&F.stream.setKeepAlive(!0,F._keepAliveInitialDelayMillis),F.emit("connect")});let L=U(function(Q){F._ending&&(Q.code==="ECONNRESET"||Q.code==="EPIPE")||F.emit("error",Q)},"reportStreamError");if(this.stream.on("error",L),this.stream.on("close",function(){F.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(Q){var _=Q.toString("utf8");switch(_){case"S":break;case"N":return F.stream.end(),F.emit("error",Error("The server does not support SSL connections"));default:return F.stream.end(),F.emit("error",Error("There was an error establishing an SSL connection"))}var v=(pZ(),B1(u7));let T={socket:F.stream};F.ssl!==!0&&(Object.assign(T,F.ssl),("key"in F.ssl)&&(T.key=F.ssl.key)),Z.isIP(S)===0&&(T.servername=S);try{F.stream=v.connect(T)}catch(x){return F.emit("error",x)}F.attachListeners(F.stream),F.stream.on("error",L),F.emit("sslconnect")})}attachListeners(D){D.on("end",()=>{this.emit("end")}),X(D,(S)=>{var F=S.name==="error"?"errorMessage":S.name;this._emitMessage&&this.emit("message",S),this.emit(F,S)})}requestSsl(){this.stream.write(Y.requestSsl())}startup(D){this.stream.write(Y.startup(D))}cancel(D,S){this._send(Y.cancel(D,S))}password(D){this._send(Y.password(D))}sendSASLInitialResponseMessage(D,S){this._send(Y.sendSASLInitialResponseMessage(D,S))}sendSCRAMClientFinalMessage(D){this._send(Y.sendSCRAMClientFinalMessage(D))}_send(D){return this.stream.writable?this.stream.write(D):!1}query(D){this._send(Y.query(D))}parse(D){this._send(Y.parse(D))}bind(D){this._send(Y.bind(D))}execute(D){this._send(Y.execute(D))}flush(){this.stream.writable&&this.stream.write(M)}sync(){this._ending=!0,this._send(M),this._send(G)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(V,()=>{this.stream.end()})}close(D){this._send(Y.close(D))}describe(D){this._send(Y.describe(D))}sendCopyFromChunk(D){this._send(Y.copyData(D))}endCopyFrom(){this._send(Y.copyDone())}sendCopyFail(D){this._send(Y.copyFail(D))}};U(R,"Connection");var P=R;$.exports=P}),iZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(y4(),B1(aW)),X=I4(),Y=CZ(),M=BZ(),G=K9(),V=F9(),R=gZ(),P=b4(),w=p7(),D=class extends Z{constructor(L){super(),this.connectionParameters=new V(L),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var Q=L||{};this._Promise=Q.Promise||x4.Promise,this._types=new G(Q.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=Q.connection||new w({stream:Q.stream,ssl:this.connectionParameters.ssl,keepAlive:Q.keepAlive||!1,keepAliveInitialDelayMillis:Q.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=Q.binary||P.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=Q.connectionTimeoutMillis||0}_errorAllQueries(L){let Q=U((_)=>{r.nextTick(()=>{_.handleError(L,this.connection)})},"enqueueError");this.activeQuery&&(Q(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(Q),this.queryQueue.length=0}_connect(L){var Q=this,_=this.connection;if(this._connectionCallback=L,this._connecting||this._connected){let v=Error("Client has already been connected. You cannot reuse a client.");r.nextTick(()=>{L(v)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{_._ending=!0,_.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){Q.ssl?_.requestSsl():_.startup(Q.getStartupConf())}),_.on("sslconnect",function(){_.startup(Q.getStartupConf())}),this._attachListeners(_),_.once("end",()=>{let v=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(v),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(v):this._handleErrorEvent(v):this._connectionError||this._handleErrorEvent(v)),r.nextTick(()=>{this.emit("end")})})}connect(L){if(L){this._connect(L);return}return new this._Promise((Q,_)=>{this._connect((v)=>{v?_(v):Q()})})}_attachListeners(L){L.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),L.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),L.on("authenticationSASL",this._handleAuthSASL.bind(this)),L.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),L.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),L.on("backendKeyData",this._handleBackendKeyData.bind(this)),L.on("error",this._handleErrorEvent.bind(this)),L.on("errorMessage",this._handleErrorMessage.bind(this)),L.on("readyForQuery",this._handleReadyForQuery.bind(this)),L.on("notice",this._handleNotice.bind(this)),L.on("rowDescription",this._handleRowDescription.bind(this)),L.on("dataRow",this._handleDataRow.bind(this)),L.on("portalSuspended",this._handlePortalSuspended.bind(this)),L.on("emptyQuery",this._handleEmptyQuery.bind(this)),L.on("commandComplete",this._handleCommandComplete.bind(this)),L.on("parseComplete",this._handleParseComplete.bind(this)),L.on("copyInResponse",this._handleCopyInResponse.bind(this)),L.on("copyData",this._handleCopyData.bind(this)),L.on("notification",this._handleNotification.bind(this))}_checkPgPass(L){let Q=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then((_)=>{if(_!==void 0){if(typeof _!="string"){Q.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=_}else this.connectionParameters.password=this.password=null;L()}).catch((_)=>{Q.emit("error",_)}):this.password!==null?L():M(this.connectionParameters,(_)=>{_!==void 0&&(this.connectionParameters.password=this.password=_),L()})}_handleAuthCleartextPassword(L){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(L){this._checkPgPass(()=>{let Q=X.postgresMd5PasswordHash(this.user,this.password,L.salt);this.connection.password(Q)})}_handleAuthSASL(L){this._checkPgPass(()=>{this.saslSession=Y.startSession(L.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(L){Y.continueSession(this.saslSession,this.password,L.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}_handleAuthSASLFinal(L){Y.finalizeSession(this.saslSession,L.data),this.saslSession=null}_handleBackendKeyData(L){this.processID=L.processID,this.secretKey=L.secretKey}_handleReadyForQuery(L){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:Q}=this;this.activeQuery=null,this.readyForQuery=!0,Q&&Q.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(L){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(L);this.emit("error",L)}}_handleErrorEvent(L){if(this._connecting)return this._handleErrorWhileConnecting(L);this._queryable=!1,this._errorAllQueries(L),this.emit("error",L)}_handleErrorMessage(L){if(this._connecting)return this._handleErrorWhileConnecting(L);let Q=this.activeQuery;if(!Q){this._handleErrorEvent(L);return}this.activeQuery=null,Q.handleError(L,this.connection)}_handleRowDescription(L){this.activeQuery.handleRowDescription(L)}_handleDataRow(L){this.activeQuery.handleDataRow(L)}_handlePortalSuspended(L){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(L){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(L){this.activeQuery.handleCommandComplete(L,this.connection)}_handleParseComplete(L){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(L){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(L){this.activeQuery.handleCopyData(L,this.connection)}_handleNotification(L){this.emit("notification",L)}_handleNotice(L){this.emit("notice",L)}getStartupConf(){var L=this.connectionParameters,Q={user:L.user,database:L.database},_=L.application_name||L.fallback_application_name;return _&&(Q.application_name=_),L.replication&&(Q.replication=""+L.replication),L.statement_timeout&&(Q.statement_timeout=String(parseInt(L.statement_timeout,10))),L.lock_timeout&&(Q.lock_timeout=String(parseInt(L.lock_timeout,10))),L.idle_in_transaction_session_timeout&&(Q.idle_in_transaction_session_timeout=String(parseInt(L.idle_in_transaction_session_timeout,10))),L.options&&(Q.options=L.options),Q}cancel(L,Q){if(L.activeQuery===Q){var _=this.connection;this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){_.cancel(L.processID,L.secretKey)})}else L.queryQueue.indexOf(Q)!==-1&&L.queryQueue.splice(L.queryQueue.indexOf(Q),1)}setTypeParser(L,Q,_){return this._types.setTypeParser(L,Q,_)}getTypeParser(L,Q){return this._types.getTypeParser(L,Q)}escapeIdentifier(L){return'"'+L.replace(/"/g,'""')+'"'}escapeLiteral(L){for(var Q=!1,_="'",v=0;v<L.length;v++){var T=L[v];T==="'"?_+=T+T:T==="\\"?(_+=T+T,Q=!0):_+=T}return _+="'",Q===!0&&(_=" E"+_),_}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let L=this.activeQuery.submit(this.connection);L&&r.nextTick(()=>{this.activeQuery.handleError(L,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(L,Q,_){var v,T,x,q,E;if(L==null)throw TypeError("Client was passed a null or undefined query");return typeof L.submit=="function"?(x=L.query_timeout||this.connectionParameters.query_timeout,T=v=L,typeof Q=="function"&&(v.callback=v.callback||Q)):(x=this.connectionParameters.query_timeout,v=new R(L,Q,_),v.callback||(T=new this._Promise((N,A)=>{v.callback=(f,B)=>f?A(f):N(B)}))),x&&(E=v.callback,q=setTimeout(()=>{var N=Error("Query read timeout");r.nextTick(()=>{v.handleError(N,this.connection)}),E(N),v.callback=()=>{};var A=this.queryQueue.indexOf(v);A>-1&&this.queryQueue.splice(A,1),this._pulseQueryQueue()},x),v.callback=(N,A)=>{clearTimeout(q),E(N,A)}),this.binary&&!v.binary&&(v.binary=!0),v._result&&!v._result._types&&(v._result._types=this._types),this._queryable?this._ending?(r.nextTick(()=>{v.handleError(Error("Client was closed and is not queryable"),this.connection)}),T):(this.queryQueue.push(v),this._pulseQueryQueue(),T):(r.nextTick(()=>{v.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),T)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(L){if(this._ending=!0,!this.connection._connecting)if(L)L();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),L)this.connection.once("end",L);else return new this._Promise((Q)=>{this.connection.once("end",Q)})}};U(D,"Client");var S=D;S.Query=R,$.exports=S}),tZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=U(function(){},"NOOP"),X=U((F,L)=>{let Q=F.findIndex(L);return Q===-1?void 0:F.splice(Q,1)[0]},"removeWhere"),Y=class{constructor(L,Q,_){this.client=L,this.idleListener=Q,this.timeoutId=_}};U(Y,"IdleItem");var M=Y,G=class{constructor(L){this.callback=L}};U(G,"PendingItem");var V=G;function R(){throw Error("Release called on client which has already been released to the pool.")}U(R,"throwOnDoubleRelease");function P(F,L){if(L)return{callback:L,result:void 0};let Q,_,v=U(function(x,q){x?Q(x):_(q)},"cb"),T=new F(function(x,q){_=x,Q=q}).catch((x)=>{throw Error.captureStackTrace(x),x});return{callback:v,result:T}}U(P,"promisify");function w(F,L){return U(function Q(_){_.client=L,L.removeListener("error",Q),L.on("error",()=>{F.log("additional client error after disconnection due to error",_)}),F._remove(L),F.emit("error",_,L)},"idleListener")}U(w,"makeIdleListener");var D=class extends Z{constructor(L,Q){super(),this.options=Object.assign({},L),L!=null&&"password"in L&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:L.password}),L!=null&&L.ssl&&L.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Q||g4().Client,this.Promise=this.options.Promise||x4.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map((Q)=>{this._remove(Q.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let L=this._pendingQueue.shift();if(this._idle.length){let Q=this._idle.pop();clearTimeout(Q.timeoutId);let _=Q.client;_.ref&&_.ref();let v=Q.idleListener;return this._acquireClient(_,L,v,!1)}if(!this._isFull())return this.newClient(L);throw Error("unexpected condition")}_remove(L){let Q=X(this._idle,(_)=>_.client===L);Q!==void 0&&clearTimeout(Q.timeoutId),this._clients=this._clients.filter((_)=>_!==L),L.end(),this.emit("remove",L)}connect(L){if(this.ending){let v=Error("Cannot use a pool after calling end on the pool");return L?L(v):this.Promise.reject(v)}let Q=P(this.Promise,L),_=Q.result;if(this._isFull()||this._idle.length){if(this._idle.length&&r.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new V(Q.callback)),_;let v=U((q,E,N)=>{clearTimeout(x),Q.callback(q,E,N)},"queueCallback"),T=new V(v),x=setTimeout(()=>{X(this._pendingQueue,(q)=>q.callback===v),T.timedOut=!0,Q.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return x.unref&&x.unref(),this._pendingQueue.push(T),_}return this.newClient(new V(Q.callback)),_}newClient(L){let Q=new this.Client(this.options);this._clients.push(Q);let _=w(this,Q);this.log("checking client timeout");let v,T=!1;this.options.connectionTimeoutMillis&&(v=setTimeout(()=>{this.log("ending client due to timeout"),T=!0,Q.connection?Q.connection.stream.destroy():Q.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),Q.connect((x)=>{if(v&&clearTimeout(v),Q.on("error",_),x)this.log("client failed to connect",x),this._clients=this._clients.filter((q)=>q!==Q),T&&(x=Error("Connection terminated due to connection timeout",{cause:x})),this._pulseQueue(),L.timedOut||L.callback(x,void 0,J);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let q=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(Q),this._idle.findIndex((E)=>E.client===Q)!==-1&&this._acquireClient(Q,new V((E,N,A)=>A()),_,!1)},this.options.maxLifetimeSeconds*1000);q.unref(),Q.once("end",()=>clearTimeout(q))}return this._acquireClient(Q,L,_,!0)}})}_acquireClient(L,Q,_,v){v&&this.emit("connect",L),this.emit("acquire",L),L.release=this._releaseOnce(L,_),L.removeListener("error",_),Q.timedOut?v&&this.options.verify?this.options.verify(L,L.release):L.release():v&&this.options.verify?this.options.verify(L,(T)=>{if(T)return L.release(T),Q.callback(T,void 0,J);Q.callback(void 0,L,L.release)}):Q.callback(void 0,L,L.release)}_releaseOnce(L,Q){let _=!1;return(v)=>{_&&R(),_=!0,this._release(L,Q,v)}}_release(L,Q,_){if(L.on("error",Q),L._poolUseCount=(L._poolUseCount||0)+1,this.emit("release",_,L),_||this.ending||!L._queryable||L._ending||L._poolUseCount>=this.options.maxUses){L._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(L),this._pulseQueue();return}if(this._expired.has(L)){this.log("remove expired client"),this._expired.delete(L),this._remove(L),this._pulseQueue();return}let v;this.options.idleTimeoutMillis&&this._isAboveMin()&&(v=setTimeout(()=>{this.log("remove idle client"),this._remove(L)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&v.unref()),this.options.allowExitOnIdle&&L.unref(),this._idle.push(new M(L,Q,v)),this._pulseQueue()}query(L,Q,_){if(typeof L=="function"){let T=P(this.Promise,L);return M9(function(){return T.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),T.result}typeof Q=="function"&&(_=Q,Q=void 0);let v=P(this.Promise,_);return _=v.callback,this.connect((T,x)=>{if(T)return _(T);let q=!1,E=U((N)=>{q||(q=!0,x.release(N),_(N))},"onError");x.once("error",E),this.log("dispatching query");try{x.query(L,Q,(N,A)=>{if(this.log("query dispatched"),x.removeListener("error",E),!q)return q=!0,x.release(N),N?_(N):_(void 0,A)})}catch(N){return x.release(N),_(N)}}),v.result}end(L){if(this.log("ending"),this.ending){let _=Error("Called end on pool more than once");return L?L(_):this.Promise.reject(_)}this.ending=!0;let Q=P(this.Promise,L);return this._endCallback=Q.callback,this._pulseQueue(),Q.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((L,Q)=>L+(this._expired.has(Q)?1:0),0)}get totalCount(){return this._clients.length}};U(D,"Pool");var S=D;$.exports=S}),i7={};S0(i7,{default:()=>t7});var t7,aZ=d1(()=>{u(),t7={}}),dZ=o((W,$)=>{$.exports={name:"pg",version:"8.8.0",description:"PostgreSQL client - pure javascript & libpq with the same API",keywords:["database","libpq","pg","postgre","postgres","postgresql","rdbms"],homepage:"https://github.com/brianc/node-postgres",repository:{type:"git",url:"git://github.com/brianc/node-postgres.git",directory:"packages/pg"},author:"Brian Carlson <brian.m.carlson@gmail.com>",main:"./lib",dependencies:{"buffer-writer":"2.0.0","packet-reader":"1.0.0","pg-connection-string":"^2.5.0","pg-pool":"^3.5.2","pg-protocol":"^1.5.0","pg-types":"^2.1.0",pgpass:"1.x"},devDependencies:{async:"2.6.4",bluebird:"3.5.2",co:"4.6.0","pg-copy-streams":"0.3.0"},peerDependencies:{"pg-native":">=3.0.1"},peerDependenciesMeta:{"pg-native":{optional:!0}},scripts:{test:"make test-all"},files:["lib","SPONSORS.md"],license:"MIT",engines:{node:">= 8.0.0"},gitHead:"c99fb2c127ddf8d712500db2c7b9a5491a178655"}}),sZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(y4(),B1(aW)),X=I4(),Y=$.exports=function(G,V,R){Z.call(this),G=X.normalizeQueryConfig(G,V,R),this.text=G.text,this.values=G.values,this.name=G.name,this.callback=G.callback,this.state="new",this._arrayMode=G.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(P){P==="row"&&(this._emitRowEvents=!0)}.bind(this))};J.inherits(Y,Z);var M={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};Y.prototype.handleError=function(G){var V=this.native.pq.resultErrorFields();if(V)for(var R in V){var P=M[R]||R;G[P]=V[R]}this.callback?this.callback(G):this.emit("error",G),this.state="error"},Y.prototype.then=function(G,V){return this._getPromise().then(G,V)},Y.prototype.catch=function(G){return this._getPromise().catch(G)},Y.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(G,V){this._once("end",G),this._once("error",V)}.bind(this)),this._promise)},Y.prototype.submit=function(G){this.state="running";var V=this;this.native=G.native,G.native.arrayMode=this._arrayMode;var R=U(function(D,S,F){if(G.native.arrayMode=!1,M9(function(){V.emit("_done")}),D)return V.handleError(D);V._emitRowEvents&&(F.length>1?S.forEach((L,Q)=>{L.forEach((_)=>{V.emit("row",_,F[Q])})}):S.forEach(function(L){V.emit("row",L,F)})),V.state="end",V.emit("end",F),V.callback&&V.callback(null,F)},"after");if(r.domain&&(R=r.domain.bind(R)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var P=(this.values||[]).map(X.prepareValue);if(G.namedQueries[this.name]){if(this.text&&G.namedQueries[this.name]!==this.text){let D=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return R(D)}return G.native.execute(this.name,P,R)}return G.native.prepare(this.name,this.text,P.length,function(D){return D?R(D):(G.namedQueries[V.name]=V.text,V.native.execute(V.name,P,R))})}else if(this.values){if(!Array.isArray(this.values)){let D=Error("Query values must be an array");return R(D)}var w=this.values.map(X.prepareValue);G.native.query(this.text,w,R)}else G.native.query(this.text,R)}}),nZ=o((W,$)=>{u();var Z=(aZ(),B1(i7)),J=K9(),X=dZ(),Y=S8().EventEmitter,M=(y4(),B1(aW)),G=F9(),V=sZ(),R=$.exports=function(P){Y.call(this),P=P||{},this._Promise=P.Promise||x4.Promise,this._types=new J(P.types),this.native=new Z({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var w=this.connectionParameters=new G(P);this.user=w.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:w.password}),this.database=w.database,this.host=w.host,this.port=w.port,this.namedQueries={}};R.Query=V,M.inherits(R,Y),R.prototype._errorAllQueries=function(P){let w=U((D)=>{r.nextTick(()=>{D.native=this.native,D.handleError(P)})},"enqueueError");this._hasActiveQuery()&&(w(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(w),this._queryQueue.length=0},R.prototype._connect=function(P){var w=this;if(this._connecting){r.nextTick(()=>P(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(D,S){if(D)return P(D);w.native.connect(S,function(F){if(F)return w.native.end(),P(F);w._connected=!0,w.native.on("error",function(L){w._queryable=!1,w._errorAllQueries(L),w.emit("error",L)}),w.native.on("notification",function(L){w.emit("notification",{channel:L.relname,payload:L.extra})}),w.emit("connect"),w._pulseQueryQueue(!0),P()})})},R.prototype.connect=function(P){if(P){this._connect(P);return}return new this._Promise((w,D)=>{this._connect((S)=>{S?D(S):w()})})},R.prototype.query=function(P,w,D){var S,F,L,Q,_;if(P==null)throw TypeError("Client was passed a null or undefined query");if(typeof P.submit=="function")L=P.query_timeout||this.connectionParameters.query_timeout,F=S=P,typeof w=="function"&&(P.callback=w);else if(L=this.connectionParameters.query_timeout,S=new V(P,w,D),!S.callback){let v,T;F=new this._Promise((x,q)=>{v=x,T=q}),S.callback=(x,q)=>x?T(x):v(q)}return L&&(_=S.callback,Q=setTimeout(()=>{var v=Error("Query read timeout");r.nextTick(()=>{S.handleError(v,this.connection)}),_(v),S.callback=()=>{};var T=this._queryQueue.indexOf(S);T>-1&&this._queryQueue.splice(T,1),this._pulseQueryQueue()},L),S.callback=(v,T)=>{clearTimeout(Q),_(v,T)}),this._queryable?this._ending?(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client was closed and is not queryable"))}),F):(this._queryQueue.push(S),this._pulseQueryQueue(),F):(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client has encountered a connection error and is not queryable"))}),F)},R.prototype.end=function(P){var w=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,P));var D;return P||(D=new this._Promise(function(S,F){P=U((L)=>L?F(L):S(),"cb")})),this.native.end(function(){w._errorAllQueries(Error("Connection terminated")),r.nextTick(()=>{w.emit("end"),P&&P()})}),D},R.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},R.prototype._pulseQueryQueue=function(P){if(this._connected&&!this._hasActiveQuery()){var w=this._queryQueue.shift();if(!w){P||this.emit("drain");return}this._activeQuery=w,w.submit(this);var D=this;w.once("_done",function(){D._pulseQueryQueue()})}},R.prototype.cancel=function(P){this._activeQuery===P?this.native.cancel(function(){}):this._queryQueue.indexOf(P)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(P),1)},R.prototype.ref=function(){},R.prototype.unref=function(){},R.prototype.setTypeParser=function(P,w,D){return this._types.setTypeParser(P,w,D)},R.prototype.getTypeParser=function(P,w){return this._types.getTypeParser(P,w)}}),U7=o((W,$)=>{u(),$.exports=nZ()}),g4=o((W,$)=>{u();var Z=iZ(),J=b4(),X=p7(),Y=tZ(),{DatabaseError:M}=c7(),G=U((R)=>{var P;return P=class extends Y{constructor(w){super(w,R)}},U(P,"BoundPool"),P},"poolFactory"),V=U(function(R){this.defaults=J,this.Client=R,this.Query=this.Client.Query,this.Pool=G(this.Client),this._pools=[],this.Connection=X,this.types=B4(),this.DatabaseError=M},"PG");typeof r.env.NODE_PG_FORCE_NATIVE<"u"?$.exports=new V(U7()):($.exports=new V(Z),Object.defineProperty($.exports,"native",{configurable:!0,enumerable:!1,get(){var R=null;try{R=new V(U7())}catch(P){if(P.code!=="MODULE_NOT_FOUND")throw P}return Object.defineProperty($.exports,"native",{value:R}),R}}))});u();u();tW();_7();u();var{defineProperty:rZ,defineProperties:oZ,getOwnPropertyDescriptors:eZ,getOwnPropertySymbols:V7}=Object,WJ=Object.prototype.hasOwnProperty,$J=Object.prototype.propertyIsEnumerable,P7=U((W,$,Z)=>($ in W)?rZ(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,"__defNormalProp"),ZJ=U((W,$)=>{for(var Z in $||($={}))WJ.call($,Z)&&P7(W,Z,$[Z]);if(V7)for(var Z of V7($))$J.call($,Z)&&P7(W,Z,$[Z]);return W},"__spreadValues"),JJ=U((W,$)=>oZ(W,eZ($)),"__spreadProps"),XJ=1008000,F7=new Uint8Array(new Uint16Array([258]).buffer)[0]===2,YJ=new TextDecoder,R9=new TextEncoder,N4=R9.encode("0123456789abcdef"),C4=R9.encode("0123456789ABCDEF"),HJ=R9.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),a7=HJ.slice();a7[62]=45;a7[63]=95;var pW,q4;function d7(W,{alphabet:$,scratchArr:Z}={}){if(!pW)if(pW=new Uint16Array(256),q4=new Uint16Array(256),F7)for(let S=0;S<256;S++)pW[S]=N4[S&15]<<8|N4[S>>>4],q4[S]=C4[S&15]<<8|C4[S>>>4];else for(let S=0;S<256;S++)pW[S]=N4[S&15]|N4[S>>>4]<<8,q4[S]=C4[S&15]|C4[S>>>4]<<8;W.byteOffset%4!==0&&(W=new Uint8Array(W));let J=W.length,X=J>>>1,Y=J>>>2,M=Z||new Uint16Array(J),G=new Uint32Array(W.buffer,W.byteOffset,Y),V=new Uint32Array(M.buffer,M.byteOffset,X),R=$==="upper"?q4:pW,P=0,w=0,D;if(F7)for(;P<Y;)D=G[P++],V[w++]=R[D>>>8&255]<<16|R[D&255],V[w++]=R[D>>>24]<<16|R[D>>>16&255];else for(;P<Y;)D=G[P++],V[w++]=R[D>>>24]<<16|R[D>>>16&255],V[w++]=R[D>>>8&255]<<16|R[D&255];for(P<<=2;P<J;)M[P]=R[W[P++]];return YJ.decode(M.subarray(0,J))}U(d7,"_toHex");function s7(W,$={}){let Z="",J=W.length,X=XJ>>>1,Y=Math.ceil(J/X),M=new Uint16Array(Y>1?X:J);for(let G=0;G<Y;G++){let V=G*X,R=V+X;Z+=d7(W.subarray(V,R),JJ(ZJ({},$),{scratchArr:M}))}return Z}U(s7,"_toHexChunked");function n7(W,$={}){return $.alphabet!=="upper"&&typeof W.toHex=="function"?W.toHex():s7(W,$)}U(n7,"toHex");u();var r7=class W{constructor($,Z){this.strings=$,this.values=Z}toParameterizedQuery($={query:"",params:[]}){let{strings:Z,values:J}=this;for(let X=0,Y=Z.length;X<Y;X++)if($.query+=Z[X],X<J.length){let M=J[X];if(M instanceof W$)$.query+=M.sql;else if(M instanceof O4)if(M.queryData instanceof W)M.queryData.toParameterizedQuery($);else{if(M.queryData.params?.length)throw Error("This query is not composable");$.query+=M.queryData.query}else{let{params:G}=$;G.push(M),$.query+="$"+G.length,(M instanceof i||ArrayBuffer.isView(M))&&($.query+="::bytea")}}return $}};U(r7,"SqlTemplate");var o7=r7,e7=class{constructor($){this.sql=$}};U(e7,"UnsafeRawSql");var W$=e7;u();function D9(){typeof window<"u"&&typeof document<"u"&&typeof console<"u"&&typeof console.warn=="function"&&console.warn(`
27
+ `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function g9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let Z,J="127.0.0.1",X="9229",Y;if((Y=$.match(/^(--inspect(-brk)?)$/))!==null)Z=Y[1];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else J=Y[3];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=Y[1],J=Y[3],X=Y[4];if(Z&&X!=="0")return`${Z}=${J}:${parseInt(X)+1}`;return $})}function X6(){if(H1.env.NO_COLOR||H1.env.FORCE_COLOR==="0"||H1.env.FORCE_COLOR==="false")return!1;if(H1.env.FORCE_COLOR||H1.env.CLICOLOR_FORCE!==void 0)return!0;return}z2.Command=Y6;z2.useColor=X6});var p9=K8((D2)=>{var{Argument:c9}=eW(),{Command:H6}=m9(),{CommanderError:P2,InvalidArgumentError:u9}=MW(),{Help:F2}=W6(),{Option:l9}=$6();D2.program=new H6;D2.createCommand=(W)=>new H6(W);D2.createOption=(W,$)=>new l9(W,$);D2.createArgument=(W,$)=>new c9(W,$);D2.Command=H6;D2.Option=l9;D2.Argument=c9;D2.Help=F2;D2.CommanderError=P2;D2.InvalidArgumentError=u9;D2.InvalidOptionArgumentError=u9});var i9=I$(p9(),1),{program:aJ,createCommand:dJ,createArgument:sJ,createOption:nJ,CommanderError:rJ,InvalidArgumentError:oJ,InvalidOptionArgumentError:eJ,Command:t9,Argument:W3,Option:$3,Help:Z3}=i9.default;import sW from"path";import{fileURLToPath as OJ}from"url";import{createRequire as xJ}from"module";import{execSync as BJ,spawn as bJ}from"child_process";function n1(W){return typeof W>"u"||W===void 0}function a(W){return typeof W==="string"}function d0(W){return typeof W==="number"}function M8(W){return typeof W==="boolean"}function T8(W){return W===null}function a9(W){return W instanceof Date}function v8(W){return typeof W==="bigint"}function D1(W){return typeof W==="function"}function Q1(W){return typeof W==="object"&&W!==null}function d9(W){return W[W.length-1]}function k(W){return Object.freeze(W)}function zW(W){if(y1(W))return W;else return[W]}function y1(W){return Array.isArray(W)}function N1(W){return W}function s9(W){return W instanceof Error?W.message:String(W)}var $1=k({is(W){return W.kind==="AlterTableNode"},create(W){return k({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return k({...W,...$})},cloneWithColumnAlteration(W,$){return k({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var l=k({is(W){return W.kind==="IdentifierNode"},create(W){return k({kind:"IdentifierNode",name:W})}});var H0=k({is(W){return W.kind==="CreateIndexNode"},create(W){return k({kind:"CreateIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});var $4=k({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return k({kind:"CreateSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var n9=["preserve rows","delete rows","drop"],C1=k({is(W){return W.kind==="CreateTableNode"},create(W){return k({kind:"CreateTableNode",table:W,columns:k([])})},cloneWithColumn(W,$){return k({...W,columns:k([...W.columns,$])})},cloneWithConstraint(W,$){return k({...W,constraints:W.constraints?k([...W.constraints,$]):k([$])})},cloneWithIndex(W,$){return k({...W,indexes:W.indexes?k([...W.indexes,$]):k([$])})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWith(W,$){return k({...W,...$})}});var g1=k({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return k({kind:"SchemableIdentifierNode",identifier:l.create(W)})},createWithSchema(W,$){return k({kind:"SchemableIdentifierNode",schema:l.create(W),identifier:l.create($)})}});var s0=k({is(W){return W.kind==="DropIndexNode"},create(W,$){return k({kind:"DropIndexNode",name:g1.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var UW=k({is(W){return W.kind==="DropSchemaNode"},create(W,$){return k({kind:"DropSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var f8=k({is(W){return W.kind==="DropTableNode"},create(W,$){return k({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return k({...W,...$})}});var q1=k({is(W){return W.kind==="AliasNode"},create(W,$){return k({kind:"AliasNode",node:W,alias:$})}});var u1=k({is(W){return W.kind==="TableNode"},create(W){return k({kind:"TableNode",table:g1.create(W)})},createWithSchema(W,$){return k({kind:"TableNode",table:g1.createWithSchema(W,$)})}});function G1(W){return Q1(W)&&D1(W.toOperationNode)}function Z4(W){return Q1(W)&&"expressionType"in W&&G1(W)}function r9(W){return Q1(W)&&"expression"in W&&a(W.alias)&&G1(W)}var _0=k({is(W){return W.kind==="SelectModifierNode"},create(W,$){return k({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return k({kind:"SelectModifierNode",rawModifier:W})}});var l1=k({is(W){return W.kind==="AndNode"},create(W,$){return k({kind:"AndNode",left:W,right:$})}});var k0=k({is(W){return W.kind==="OrNode"},create(W,$){return k({kind:"OrNode",left:W,right:$})}});var J4=k({is(W){return W.kind==="OnNode"},create(W){return k({kind:"OnNode",on:W})},cloneWithOperation(W,$,Z){return k({...W,on:$==="And"?l1.create(W.on,Z):k0.create(W.on,Z)})}});var G0=k({is(W){return W.kind==="JoinNode"},create(W,$){return k({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,Z){return k({kind:"JoinNode",joinType:W,table:$,on:J4.create(Z)})},cloneWithOn(W,$){return k({...W,on:W.on?J4.cloneWithOperation(W.on,"And",$):J4.create($)})}});var n0=k({is(W){return W.kind==="BinaryOperationNode"},create(W,$,Z){return k({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:Z})}});var o9=k({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),WX=Object.keys(o9),e9=k({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),$X=Object.keys(e9),W5=k({"->":!0,"->>":!0}),A2=Object.keys(W5),$5=k({...o9,...e9,"||":!0}),N2=Object.keys($5),Z5=k({exists:!0,"not exists":!0}),ZX=Object.keys(Z5),J5=k({...Z5,"-":!0,not:!0}),C2=Object.keys(J5),JX=[...N2,...A2,...C2,"between","between symmetric"],r1=k({is(W){return W.kind==="OperatorNode"},create(W){return k({kind:"OperatorNode",operator:W})}});function X5(W){return a(W)&&$5[W]}function Y5(W){return a(W)&&W5[W]}function H5(W){return a(W)&&J5[W]}var e=k({is(W){return W.kind==="ColumnNode"},create(W){return k({kind:"ColumnNode",column:l.create(W)})}});var j8=k({is(W){return W.kind==="SelectAllNode"},create(){return k({kind:"SelectAllNode"})}});var A8=k({is(W){return W.kind==="ReferenceNode"},create(W,$){return k({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return k({kind:"ReferenceNode",table:W,column:j8.create()})}});class k6{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return G6(this.#W)}}function X4(W){return Q1(W)&&G1(W)&&a(W.dynamicReference)}var L0=k({is(W){return W.kind==="OrderByItemNode"},create(W,$){return k({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return k({...W,...$})}});var X1=k({is(W){return W.kind==="RawNode"},create(W,$){return k({kind:"RawNode",sqlFragments:k(W),parameters:k($)})},createWithSql(W){return X1.create([W],[])},createWithChild(W){return X1.create(["",""],[W])},createWithChildren(W){return X1.create(Array(W.length+1).fill(""),W)}});var k5=k({is(W){return W.kind==="CollateNode"},create(W){return k({kind:"CollateNode",collation:l.create(W)})}});class r0{#W;constructor(W){this.#W=k(W)}desc(){return new r0({node:L0.cloneWith(this.#W.node,{direction:X1.createWithSql("desc")})})}asc(){return new r0({node:L0.cloneWith(this.#W.node,{direction:X1.createWithSql("asc")})})}nullsLast(){return new r0({node:L0.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new r0({node:L0.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new r0({node:L0.cloneWith(this.#W.node,{collation:k5.create(W)})})}toOperationNode(){return this.#W.node}}var G5=new Set;function N8(W){if(G5.has(W))return;G5.add(W),console.log(W)}function K6(W){return W==="asc"||W==="desc"}function o1(W){if(W.length===2)return[L6(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return N8("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((Z)=>L6(Z));return[L6($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function L6(W,$){let Z=q2(W);if(L0.is(Z)){if($)throw Error("Cannot specify direction twice!");return Z}return L5(Z,$)}function q2(W){if(B0(W))return O1(W);if(X4(W))return W.toOperationNode();let[$,Z]=W.split(" ");if(Z)return N8("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),L5(p1($),Z);return p1(W)}function L5(W,$){if(typeof $==="string"){if(!K6($))throw Error(`Invalid order by direction: ${$}`);return L0.create(W,X1.createWithSql($))}if(Z4($))return N8("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),L0.create(W,$.toOperationNode());let Z=L0.create(W);if(!$)return Z;return $(new r0({node:Z})).toOperationNode()}var C8=k({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return k({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return k({...W,traversal:$})}});var Y4=k({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return k({kind:"JSONOperatorChainNode",operator:W,values:k([])})},cloneWithValue(W,$){return k({...W,values:k([...W.values,$])})}});var o0=k({is(W){return W.kind==="JSONPathNode"},create(W){return k({kind:"JSONPathNode",inOperator:W,pathLegs:k([])})},cloneWithLeg(W,$){return k({...W,pathLegs:k([...W.pathLegs,$])})}});function G6(W){if(a(W))return p1(W);return W.toOperationNode()}function b0(W){if(y1(W))return W.map(($)=>v1($));else return[v1(W)]}function v1(W){if(B0(W))return O1(W);return G6(W)}function K5(W,$){if(Y5($))return C8.create(p1(W),Y4.create(r1.create($)));if($==="->$"||$==="->>$")return C8.create(p1(W),o0.create(r1.create($.slice(0,-1))));throw Error(`Invalid JSON operator: ${$}`)}function p1(W){if(!W.includes("."))return A8.create(e.create(W));let Z=W.split(".").map(z6);if(Z.length===3)return O2(Z);if(Z.length===2)return x2(Z);throw Error(`invalid column reference ${W}`)}function M5(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(z6);return q1.create(p1(Z),l.create(J))}else return p1(W)}function M6(W){return e.create(W)}function q8(W){if(W.includes(" ")){let[Z,J]=W.split(" ").map(z6);if(!K6(J))throw Error(`invalid order direction "${J}" next to "${Z}"`);return o1([Z,J])[0]}else return M6(W)}function O2(W){let[$,Z,J]=W;return A8.create(e.create(J),u1.createWithSchema($,Z))}function x2(W){let[$,Z]=W;return A8.create(e.create(Z),u1.create($))}function z6(W){return W.trim()}var H4=k({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return k({kind:"PrimitiveValueListNode",values:k([...W])})}});var e0=k({is(W){return W.kind==="ValueListNode"},create(W){return k({kind:"ValueListNode",values:k(W)})}});var R1=k({is(W){return W.kind==="ValueNode"},create(W){return k({kind:"ValueNode",value:W})},createImmediate(W){return k({kind:"ValueNode",value:W,immediate:!0})}});function z5(W){if(y1(W))return B2(W);return L1(W)}function L1(W){if(B0(W))return O1(W);return R1.create(W)}function k4(W){return d0(W)||M8(W)||T8(W)}function VW(W){if(!k4(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return R1.createImmediate(W)}function B2(W){if(W.some(B0))return e0.create(W.map(($)=>L1($)));return H4.create(W)}var e1=k({is(W){return W.kind==="ParensNode"},create(W){return k({kind:"ParensNode",node:W})}});function M1(W){if(W.length===3)return G4(W[0],W[1],W[2]);else if(W.length===1)return L1(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function G4(W,$,Z){if(b2($)&&V5(Z))return n0.create(v1(W),U6($),R1.createImmediate(Z));return n0.create(v1(W),U6($),z5(Z))}function h1(W,$,Z){return n0.create(v1(W),U6($),v1(Z))}function V6(W,$){return O8(Object.entries(W).filter(([,Z])=>!n1(Z)).map(([Z,J])=>G4(Z,V5(J)?"is":"=",J)),$)}function O8(W,$,Z=!0){let J=$==="and"?l1.create:k0.create;if(W.length===0)return n0.create(R1.createImmediate(1),r1.create("="),R1.createImmediate($==="and"?1:0));let X=U5(W[0]);for(let Y=1;Y<W.length;++Y)X=J(X,U5(W[Y]));if(W.length>1&&Z)return e1.create(X);return X}function b2(W){return W==="is"||W==="is not"}function V5(W){return T8(W)||M8(W)}function U6(W){if(X5(W))return r1.create(W);if(G1(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function U5(W){return G1(W)?W.toOperationNode():W}var I0=k({is(W){return W.kind==="OrderByNode"},create(W){return k({kind:"OrderByNode",items:k([...W])})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var P6=k({is(W){return W.kind==="PartitionByNode"},create(W){return k({kind:"PartitionByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var PW=k({is(W){return W.kind==="OverNode"},create(){return k({kind:"OverNode"})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithPartitionByItems(W,$){return k({...W,partitionBy:W.partitionBy?P6.cloneWithItems(W.partitionBy,$):P6.create($)})}});var z8=k({is(W){return W.kind==="FromNode"},create(W){return k({kind:"FromNode",froms:k(W)})},cloneWithFroms(W,$){return k({...W,froms:k([...W.froms,...$])})}});var F6=k({is(W){return W.kind==="GroupByNode"},create(W){return k({kind:"GroupByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var D6=k({is(W){return W.kind==="HavingNode"},create(W){return k({kind:"HavingNode",having:W})},cloneWithOperation(W,$,Z){return k({...W,having:$==="And"?l1.create(W.having,Z):k0.create(W.having,Z)})}});var S1=k({is(W){return W.kind==="InsertQueryNode"},create(W,$,Z){return k({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:Z})},createWithoutInto(){return k({kind:"InsertQueryNode"})},cloneWith(W,$){return k({...W,...$})}});var L4=k({is(W){return W.kind==="ListNode"},create(W){return k({kind:"ListNode",items:k(W)})}});var E0=k({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return k({kind:"UpdateQueryNode",table:W.length===1?W[0]:L4.create(W),...$&&{with:$}})},createWithoutTable(){return k({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return k({...W,from:W.from?z8.cloneWithFroms(W.from,$):z8.create($)})},cloneWithUpdates(W,$){return k({...W,updates:W.updates?k([...W.updates,...$]):$})},cloneWithLimit(W,$){return k({...W,limit:$})}});var FW=k({is(W){return W.kind==="UsingNode"},create(W){return k({kind:"UsingNode",tables:k(W)})},cloneWithTables(W,$){return k({...W,tables:k([...W.tables,...$])})}});var W8=k({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return k({kind:"DeleteQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithUsing(W,$){return k({...W,using:W.using!==void 0?FW.cloneWithTables(W.using,$):FW.create($)})}});var b1=k({is(W){return W.kind==="WhereNode"},create(W){return k({kind:"WhereNode",where:W})},cloneWithOperation(W,$,Z){return k({...W,where:$==="And"?l1.create(W.where,Z):k0.create(W.where,Z)})}});var R6=k({is(W){return W.kind==="ReturningNode"},create(W){return k({kind:"ReturningNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var P5=k({is(W){return W.kind==="ExplainNode"},create(W,$){return k({kind:"ExplainNode",format:W,options:$})}});var i1=k({is(W){return W.kind==="WhenNode"},create(W){return k({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return k({...W,result:$})}});var W0=k({is(W){return W.kind==="MergeQueryNode"},create(W,$){return k({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return k({...W,using:$})},cloneWithWhen(W,$){return k({...W,whens:W.whens?k([...W.whens,$]):k([$])})},cloneWithThen(W,$){return k({...W,whens:W.whens?k([...W.whens.slice(0,-1),i1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var w6=k({is(W){return W.kind==="OutputNode"},create(W){return k({kind:"OutputNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var y=k({is(W){return k1.is(W)||S1.is(W)||E0.is(W)||W8.is(W)||W0.is(W)},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWithWhere(W,$){return k({...W,where:W.where?b1.cloneWithOperation(W.where,"And",$):b1.create($)})},cloneWithJoin(W,$){return k({...W,joins:W.joins?k([...W.joins,$]):k([$])})},cloneWithReturning(W,$){return k({...W,returning:W.returning?R6.cloneWithSelections(W.returning,$):R6.create($)})},cloneWithoutReturning(W){return k({...W,returning:void 0})},cloneWithoutWhere(W){return k({...W,where:void 0})},cloneWithExplain(W,$,Z){return k({...W,explain:P5.create($,Z?.toOperationNode())})},cloneWithTop(W,$){return k({...W,top:$})},cloneWithOutput(W,$){return k({...W,output:W.output?w6.cloneWithSelections(W.output,$):w6.create($)})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithoutOrderBy(W){return k({...W,orderBy:void 0})}});var k1=k({is(W){return W.kind==="SelectQueryNode"},create(W){return k({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return k({kind:"SelectQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})},cloneWithDistinctOn(W,$){return k({...W,distinctOn:W.distinctOn?k([...W.distinctOn,...$]):k($)})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return k({...W,groupBy:W.groupBy?F6.cloneWithItems(W.groupBy,$):F6.create($)})},cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithOffset(W,$){return k({...W,offset:$})},cloneWithFetch(W,$){return k({...W,fetch:$})},cloneWithHaving(W,$){return k({...W,having:W.having?D6.cloneWithOperation(W.having,"And",$):D6.create($)})},cloneWithSetOperations(W,$){return k({...W,setOperations:W.setOperations?k([...W.setOperations,...$]):k([...$])})},cloneWithoutSelections(W){return k({...W,selections:[]})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithoutOffset(W){return k({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return k({...W,groupBy:void 0})}});class x8{#W;constructor(W){this.#W=k(W)}on(...W){return new x8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,M1(W))})}onRef(W,$,Z){return new x8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,h1(W,$,Z))})}onTrue(){return new x8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,X1.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var F5=k({is(W){return W.kind==="PartitionByItemNode"},create(W){return k({kind:"PartitionByItemNode",partitionBy:W})}});function D5(W){return b0(W).map(F5.create)}class B8{#W;constructor(W){this.#W=k(W)}orderBy(...W){return new B8({overNode:PW.cloneWithOrderByItems(this.#W.overNode,o1(W))})}clearOrderBy(){return new B8({overNode:y.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new B8({overNode:PW.cloneWithPartitionByItems(this.#W.overNode,D5(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var b8=k({is(W){return W.kind==="SelectionNode"},create(W){return k({kind:"SelectionNode",selection:W})},createSelectAll(){return k({kind:"SelectionNode",selection:j8.create()})},createSelectAllFromTable(W){return k({kind:"SelectionNode",selection:A8.createSelectAll(W)})}});function j1(W){if(D1(W))return j1(W(K0()));else if(y1(W))return W.map(($)=>R5($));else return[R5(W)]}function R5(W){if(a(W))return b8.create(M5(W));else if(X4(W))return b8.create(W.toOperationNode());else return b8.create(K4(W))}function x1(W){if(!W)return[b8.createSelectAll()];else if(Array.isArray(W))return W.map(w5);else return[w5(W)]}function w5(W){if(a(W))return b8.createSelectAllFromTable(Z1(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var Q5=k({is(W){return W.kind==="ValuesNode"},create(W){return k({kind:"ValuesNode",values:k(W)})}});var S5=k({is(W){return W.kind==="DefaultInsertValueNode"},create(){return k({kind:"DefaultInsertValueNode"})}});function M4(W){let $=D1(W)?W(K0()):W,Z=y1($)?$:k([$]);return I2(Z)}function I2(W){let $=y2(W);return[k([...$.keys()].map(e.create)),Q5.create(W.map((Z)=>g2(Z,$)))]}function y2(W){let $=new Map;for(let Z of W){let J=Object.keys(Z);for(let X of J)if(!$.has(X)&&Z[X]!==void 0)$.set(X,$.size)}return $}function g2(W,$){let Z=Object.keys(W),J=Array.from({length:$.size}),X=!1,Y=Z.length;for(let G of Z){let U=$.get(G);if(n1(U)){Y--;continue}let D=W[G];if(n1(D)||B0(D))X=!0;J[U]=D}if(Y<$.size||X){let G=S5.create();return e0.create(J.map((U)=>n1(U)?G:L1(U)))}return H4.create(J)}var Q6=k({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return k({kind:"ColumnUpdateNode",column:W,value:$})}});function _5(...W){if(W.length===2)return[Q6.create(v1(W[0]),L1(W[1]))];return DW(W[0])}function DW(W){let $=D1(W)?W(K0()):W;return Object.entries($).filter(([Z,J])=>J!==void 0).map(([Z,J])=>{return Q6.create(e.create(Z),L1(J))})}var E5=k({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return k({kind:"OnDuplicateKeyNode",updates:W})}});class S6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class M0 extends Error{node;constructor(W){super("no result");this.node=W}}function h0(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var m1=k({is(W){return W.kind==="OnConflictNode"},create(){return k({kind:"OnConflictNode"})},cloneWith(W,$){return k({...W,...$})},cloneWithIndexWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"And",$):b1.create($)})},cloneWithIndexOrWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"Or",$):b1.create($)})},cloneWithUpdateWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"And",$):b1.create($)})},cloneWithUpdateOrWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"Or",$):b1.create($)})},cloneWithoutIndexWhere(W){return k({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return k({...W,updateWhere:void 0})}});class T0{#W;constructor(W){this.#W=k(W)}column(W){let $=e.create(W);return new T0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,$]):k([$])})})}columns(W){let $=W.map(e.create);return new T0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,...$]):k($)})})}constraint(W){return new T0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{constraint:l.create(W)})})}expression(W){return new T0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new T0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,M1(W))})}whereRef(W,$,Z){return new T0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,h1(W,$,Z))})}clearWhere(){return new T0({...this.#W,onConflictNode:m1.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new h5({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new RW({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{updates:DW(W)})})}$call(W){return W(this)}}class h5{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.onConflictNode}}class RW{#W;constructor(W){this.#W=k(W)}where(...W){return new RW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,M1(W))})}whereRef(W,$,Z){return new RW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,h1(W,$,Z))})}clearWhere(){return new RW({...this.#W,onConflictNode:m1.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var T5=k({is(W){return W.kind==="TopNode"},create(W,$){return k({kind:"TopNode",expression:W,modifiers:$})}});function z0(W,$){if(!d0(W)&&!v8(W))throw Error(`Invalid top expression: ${W}`);if(!n1($)&&!m2($))throw Error(`Invalid top modifiers: ${$}`);return T5.create(W,$)}function m2(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var U8=k({is(W){return W.kind==="OrActionNode"},create(W){return k({kind:"OrActionNode",action:W})}});class K1{#W;constructor(W){this.#W=k(W)}values(W){let[$,Z]=M4(W);return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:$,values:Z})})}columns(W){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:k(W.map(e.create))})})}expression(W){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{values:O1(W)})})}defaultValues(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new K1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orIgnore(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orAbort(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("abort")})})}orFail(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("fail")})})}orReplace(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("replace")})})}orRollback(){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("rollback")})})}top(W,$){return new K1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}onConflict(W){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onConflict:W(new T0({onConflictNode:m1.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new K1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onDuplicateKey:E5.create(DW(W))})})}returning(W){return new K1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(){return new K1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1())})}output(W){return new K1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new K1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new K1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new K1({...this.#W})}$castTo(){return new K1(this.#W)}$narrowType(){return new K1(this.#W)}$assertType(){return new K1(this.#W)}withPlugin(W){return new K1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new S6(Z.insertId,Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??M0;throw h0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new K1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class _6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var I8=k({is(W){return W.kind==="LimitNode"},create(W){return k({kind:"LimitNode",limit:W})}});var _1;class z4{#W;constructor(W){this.#W=k(W)}where(...W){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,M1(W))})}whereRef(W,$,Z){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,h1(W,$,Z))})}clearWhere(){return new _1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new _1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(W){return new _1({...this.#W,queryNode:W8.cloneWithUsing(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new _1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}returning(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new _1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new _1({...this.#W,queryNode:W8.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new _1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new _1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new _1({...this.#W,queryNode:W8.cloneWithLimit(this.#W.queryNode,I8.create(L1(W)))})}modifyEnd(W){return new _1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new _1({...this.#W})}$castTo(){return new _1(this.#W)}$narrowType(){return new _1(this.#W)}$assertType(){return new _1(this.#W)}withPlugin(W){return new _1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new _6(Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??M0;throw h0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new _1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}_1=z4;class E6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}var E1;class y8{#W;constructor(W){this.#W=k(W)}where(...W){return new E1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,M1(W))})}whereRef(W,$,Z){return new E1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,h1(W,$,Z))})}clearWhere(){return new E1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new E1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}from(W){return new E1({...this.#W,queryNode:E0.cloneWithFromItems(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new E1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new E1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new E1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new E1({...this.#W,queryNode:E0.cloneWithLimit(this.#W.queryNode,I8.create(L1(W)))})}set(...W){return new E1({...this.#W,queryNode:E0.cloneWithUpdates(this.#W.queryNode,_5(...W))})}returning(W){return new E1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new E1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new E1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new E1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}modifyEnd(W){return new E1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new E1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new E1({...this.#W})}$castTo(){return new E1(this.#W)}$narrowType(){return new E1(this.#W)}$assertType(){return new E1(this.#W)}withPlugin(W){return new E1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new E6(Z.numAffectedRows??BigInt(0),Z.numChangedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??M0;throw h0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new E1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}E1=y8;var h6=k({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return k({kind:"CommonTableExpressionNameNode",table:u1.create(W),columns:$?k($.map(e.create)):void 0})}});var g8=k({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return k({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return k({...W,...$})}});class wW{#W;constructor(W){this.#W=k(W)}materialized(){return new wW({...this.#W,node:g8.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new wW({...this.#W,node:g8.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function T6(W,$){let Z=G1($)?$.toOperationNode():$(f5()).toOperationNode();if(D1(W))return W(c2(Z)).toOperationNode();return g8.create(v5(W),Z)}function c2(W){return($)=>{return new wW({node:g8.create(v5($),W)})}}function v5(W){if(W.includes("(")){let $=W.split(/[\(\)]/),Z=$[0],J=$[1].split(",").map((X)=>X.trim());return h6.create(Z,J)}else return h6.create(W)}var QW=k({is(W){return W.kind==="WithNode"},create(W,$){return k({kind:"WithNode",expressions:k([W]),...$})},cloneWithExpression(W,$){return k({...W,expressions:k([...W.expressions,$])})}});var j5=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function A5(W){let $="";for(let Z=0;Z<W;++Z)$+=u2();return $}function u2(){return j5[~~(Math.random()*j5.length)]}function W1(){return new N5}class N5{#W;get queryId(){if(this.#W===void 0)this.#W=A5(8);return this.#W}}class SW{nodeStack=[];#W=k({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let Z=this.transformNodeImpl(W,$);return this.nodeStack.pop(),k(Z)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return k(W.map((Z)=>this.transformNode(Z,$)))}transformSelectQuery(W,$){return{kind:"SelectQueryNode",from:this.transformNode(W.from,$),selections:this.transformNodeList(W.selections,$),distinctOn:this.transformNodeList(W.distinctOn,$),joins:this.transformNodeList(W.joins,$),groupBy:this.transformNode(W.groupBy,$),orderBy:this.transformNode(W.orderBy,$),where:this.transformNode(W.where,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),limit:this.transformNode(W.limit,$),offset:this.transformNode(W.offset,$),with:this.transformNode(W.with,$),having:this.transformNode(W.having,$),explain:this.transformNode(W.explain,$),setOperations:this.transformNodeList(W.setOperations,$),fetch:this.transformNode(W.fetch,$),top:this.transformNode(W.top,$)}}transformSelection(W,$){return{kind:"SelectionNode",selection:this.transformNode(W.selection,$)}}transformColumn(W,$){return{kind:"ColumnNode",column:this.transformNode(W.column,$)}}transformAlias(W,$){return{kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)}}transformTable(W,$){return{kind:"TableNode",table:this.transformNode(W.table,$)}}transformFrom(W,$){return{kind:"FromNode",froms:this.transformNodeList(W.froms,$)}}transformReference(W,$){return{kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)}}transformAnd(W,$){return{kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformOr(W,$){return{kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformValueList(W,$){return{kind:"ValueListNode",values:this.transformNodeList(W.values,$)}}transformParens(W,$){return{kind:"ParensNode",node:this.transformNode(W.node,$)}}transformJoin(W,$){return{kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)}}transformRaw(W,$){return{kind:"RawNode",sqlFragments:k([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)}}transformWhere(W,$){return{kind:"WhereNode",where:this.transformNode(W.where,$)}}transformInsertQuery(W,$){return{kind:"InsertQueryNode",into:this.transformNode(W.into,$),columns:this.transformNodeList(W.columns,$),values:this.transformNode(W.values,$),returning:this.transformNode(W.returning,$),onConflict:this.transformNode(W.onConflict,$),onDuplicateKey:this.transformNode(W.onDuplicateKey,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orAction:this.transformNode(W.orAction,$),replace:W.replace,explain:this.transformNode(W.explain,$),defaultValues:W.defaultValues,top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformValues(W,$){return{kind:"ValuesNode",values:this.transformNodeList(W.values,$)}}transformDeleteQuery(W,$){return{kind:"DeleteQueryNode",from:this.transformNode(W.from,$),using:this.transformNode(W.using,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orderBy:this.transformNode(W.orderBy,$),limit:this.transformNode(W.limit,$),explain:this.transformNode(W.explain,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformReturning(W,$){return{kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)}}transformCreateTable(W,$){return{kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),indexes:this.transformNodeList(W.indexes,$),temporary:W.temporary,ifNotExists:W.ifNotExists,onCommit:W.onCommit,frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),selectQuery:this.transformNode(W.selectQuery,$)}}transformColumnDefinition(W,$){return{kind:"ColumnDefinitionNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),references:this.transformNode(W.references,$),primaryKey:W.primaryKey,autoIncrement:W.autoIncrement,unique:W.unique,notNull:W.notNull,unsigned:W.unsigned,defaultTo:this.transformNode(W.defaultTo,$),check:this.transformNode(W.check,$),generated:this.transformNode(W.generated,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),nullsNotDistinct:W.nullsNotDistinct,identity:W.identity,ifNotExists:W.ifNotExists}}transformAddColumn(W,$){return{kind:"AddColumnNode",column:this.transformNode(W.column,$)}}transformDropTable(W,$){return{kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade,temporary:W.temporary}}transformOrderBy(W,$){return{kind:"OrderByNode",items:this.transformNodeList(W.items,$)}}transformOrderByItem(W,$){return{kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls}}transformGroupBy(W,$){return{kind:"GroupByNode",items:this.transformNodeList(W.items,$)}}transformGroupByItem(W,$){return{kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)}}transformUpdateQuery(W,$){return{kind:"UpdateQueryNode",table:this.transformNode(W.table,$),from:this.transformNode(W.from,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),updates:this.transformNodeList(W.updates,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),explain:this.transformNode(W.explain,$),limit:this.transformNode(W.limit,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$),orderBy:this.transformNode(W.orderBy,$)}}transformColumnUpdate(W,$){return{kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)}}transformLimit(W,$){return{kind:"LimitNode",limit:this.transformNode(W.limit,$)}}transformOffset(W,$){return{kind:"OffsetNode",offset:this.transformNode(W.offset,$)}}transformOnConflict(W,$){return{kind:"OnConflictNode",columns:this.transformNodeList(W.columns,$),constraint:this.transformNode(W.constraint,$),indexExpression:this.transformNode(W.indexExpression,$),indexWhere:this.transformNode(W.indexWhere,$),updates:this.transformNodeList(W.updates,$),updateWhere:this.transformNode(W.updateWhere,$),doNothing:W.doNothing}}transformOnDuplicateKey(W,$){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)}}transformCreateIndex(W,$){return{kind:"CreateIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists,where:this.transformNode(W.where,$),nullsNotDistinct:W.nullsNotDistinct}}transformList(W,$){return{kind:"ListNode",items:this.transformNodeList(W.items,$)}}transformDropIndex(W,$){return{kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade}}transformPrimaryKeyConstraint(W,$){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformUniqueConstraint(W,$){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformForeignKeyConstraint(W,$){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(W.columns,$),references:this.transformNode(W.references,$),name:this.transformNode(W.name,$),onDelete:W.onDelete,onUpdate:W.onUpdate,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformSetOperation(W,$){return{kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all}}transformReferences(W,$){return{kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate}}transformCheckConstraint(W,$){return{kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)}}transformWith(W,$){return{kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive}}transformCommonTableExpression(W,$){return{kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)}}transformCommonTableExpressionName(W,$){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)}}transformHaving(W,$){return{kind:"HavingNode",having:this.transformNode(W.having,$)}}transformCreateSchema(W,$){return{kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists}}transformDropSchema(W,$){return{kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade}}transformAlterTable(W,$){return{kind:"AlterTableNode",table:this.transformNode(W.table,$),renameTo:this.transformNode(W.renameTo,$),setSchema:this.transformNode(W.setSchema,$),columnAlterations:this.transformNodeList(W.columnAlterations,$),addConstraint:this.transformNode(W.addConstraint,$),dropConstraint:this.transformNode(W.dropConstraint,$),renameConstraint:this.transformNode(W.renameConstraint,$),addIndex:this.transformNode(W.addIndex,$),dropIndex:this.transformNode(W.dropIndex,$)}}transformDropColumn(W,$){return{kind:"DropColumnNode",column:this.transformNode(W.column,$),ifExists:W.ifExists}}transformRenameColumn(W,$){return{kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)}}transformAlterColumn(W,$){return{kind:"AlterColumnNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),dataTypeExpression:this.transformNode(W.dataTypeExpression,$),setDefault:this.transformNode(W.setDefault,$),dropDefault:W.dropDefault,setNotNull:W.setNotNull,dropNotNull:W.dropNotNull}}transformModifyColumn(W,$){return{kind:"ModifyColumnNode",column:this.transformNode(W.column,$)}}transformAddConstraint(W,$){return{kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)}}transformDropConstraint(W,$){return{kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier}}transformRenameConstraint(W,$){return{kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)}}transformCreateView(W,$){return{kind:"CreateViewNode",name:this.transformNode(W.name,$),temporary:W.temporary,orReplace:W.orReplace,ifNotExists:W.ifNotExists,materialized:W.materialized,columns:this.transformNodeList(W.columns,$),as:this.transformNode(W.as,$)}}transformRefreshMaterializedView(W,$){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData}}transformDropView(W,$){return{kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade}}transformGenerated(W,$){return{kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)}}transformDefaultValue(W,$){return{kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)}}transformOn(W,$){return{kind:"OnNode",on:this.transformNode(W.on,$)}}transformSelectModifier(W,$){return{kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)}}transformCreateType(W,$){return{kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)}}transformDropType(W,$){return{kind:"DropTypeNode",name:this.transformNode(W.name,$),additionalNames:this.transformNodeList(W.additionalNames,$),cascade:W.cascade,ifExists:W.ifExists}}transformExplain(W,$){return{kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)}}transformSchemableIdentifier(W,$){return{kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)}}transformAggregateFunction(W,$){return{kind:"AggregateFunctionNode",func:W.func,aggregated:this.transformNodeList(W.aggregated,$),distinct:W.distinct,orderBy:this.transformNode(W.orderBy,$),withinGroup:this.transformNode(W.withinGroup,$),filter:this.transformNode(W.filter,$),over:this.transformNode(W.over,$)}}transformOver(W,$){return{kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)}}transformPartitionBy(W,$){return{kind:"PartitionByNode",items:this.transformNodeList(W.items,$)}}transformPartitionByItem(W,$){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)}}transformBinaryOperation(W,$){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)}}transformUnaryOperation(W,$){return{kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)}}transformUsing(W,$){return{kind:"UsingNode",tables:this.transformNodeList(W.tables,$)}}transformFunction(W,$){return{kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)}}transformCase(W,$){return{kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement}}transformWhen(W,$){return{kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)}}transformJSONReference(W,$){return{kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)}}transformJSONPath(W,$){return{kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)}}transformJSONPathLeg(W,$){return{kind:"JSONPathLegNode",type:W.type,value:W.value}}transformJSONOperatorChain(W,$){return{kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)}}transformTuple(W,$){return{kind:"TupleNode",values:this.transformNodeList(W.values,$)}}transformMergeQuery(W,$){return{kind:"MergeQueryNode",into:this.transformNode(W.into,$),using:this.transformNode(W.using,$),whens:this.transformNodeList(W.whens,$),with:this.transformNode(W.with,$),top:this.transformNode(W.top,$),endModifiers:this.transformNodeList(W.endModifiers,$),output:this.transformNode(W.output,$),returning:this.transformNode(W.returning,$)}}transformMatched(W,$){return{kind:"MatchedNode",not:W.not,bySource:W.bySource}}transformAddIndex(W,$){return{kind:"AddIndexNode",name:this.transformNode(W.name,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists}}transformCast(W,$){return{kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)}}transformFetch(W,$){return{kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier}}transformTop(W,$){return{kind:"TopNode",expression:W.expression,modifiers:W.modifiers}}transformOutput(W,$){return{kind:"OutputNode",selections:this.transformNodeList(W.selections,$)}}transformAlterType(W,$){return{kind:"AlterTypeNode",name:this.transformNode(W.name,$),addValue:this.transformNode(W.addValue,$),renameTo:this.transformNode(W.renameTo,$),renameValue:this.transformNode(W.renameValue,$),setSchema:this.transformNode(W.setSchema,$)}}transformAddValue(W,$){return{kind:"AddValueNode",value:this.transformNode(W.value,$),ifNotExists:W.ifNotExists,isBefore:W.isBefore,neighborValue:this.transformNode(W.neighborValue,$)}}transformRenameValue(W,$){return{kind:"RenameValueNode",oldValue:this.transformNode(W.oldValue,$),newValue:this.transformNode(W.newValue,$)}}transformDataType(W,$){return W}transformSelectAll(W,$){return W}transformIdentifier(W,$){return W}transformValue(W,$){return W}transformPrimitiveValueList(W,$){return W}transformOperator(W,$){return W}transformDefaultInsertValue(W,$){return W}transformOrAction(W,$){return W}transformCollate(W,$){return W}}function C5(W){return Q1(W)&&a(W.kind)}var l2={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function q5(W){return C5(W)&&l2[W.kind]===!0}var p2=k({json_agg:!0,to_json:!0});class v6 extends SW{#W;#$=new Set;#Z=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!q5(W))return super.transformNodeImpl(W,$);let Z=this.#k(W);for(let Y of Z)this.#Z.add(Y);let J=this.#Y(W);for(let Y of J)this.#$.add(Y);let X=super.transformNodeImpl(W,$);for(let Y of J)this.#$.delete(Y);for(let Y of Z)this.#Z.delete(Y);return X}transformSchemableIdentifier(W,$){let Z=super.transformSchemableIdentifier(W,$);if(Z.schema||!this.#$.has(W.identifier.name))return Z;return{...Z,schema:l.create(this.#W)}}transformReferences(W,$){let Z=super.transformReferences(W,$);if(Z.table.table.schema)return Z;return{...Z,table:u1.createWithSchema(this.#W,Z.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#X(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#X(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((Z)=>u1.is(Z)&&!Z.table.schema?{...Z,table:this.transformIdentifier(Z.table.identifier,$)}:this.transformNode(Z,$))}}#X(W,$,Z){return p2[W.func]?W[Z].map((J)=>!u1.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[Z],$)}#Y(W){let $=new Set;if("name"in W&&W.name&&g1.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let Z of W.from.froms)this.#J(Z,$);if("into"in W&&W.into)this.#J(W.into,$);if("table"in W&&W.table)this.#J(W.table,$);if("joins"in W&&W.joins)for(let Z of W.joins)this.#J(Z.table,$);if("using"in W&&W.using)if(G0.is(W.using))this.#J(W.using.table,$);else this.#J(W.using,$);return $}#k(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#J(W,$){if(u1.is(W))return this.#H(W.table,$);if(q1.is(W)&&u1.is(W.node))return this.#H(W.node.table,$);if(L4.is(W)){for(let Z of W.items)this.#J(Z,$);return}if(FW.is(W)){for(let Z of W.tables)this.#J(Z,$);return}}#H(W,$){let Z=W.identifier.name;if(!this.#$.has(Z)&&!this.#Z.has(Z))$.add(Z)}#G(W,$){for(let Z of W.expressions){let J=Z.name.table.table.identifier.name;if(!this.#Z.has(J))$.add(J)}}}class V0{#W;constructor(W){this.#W=new v6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var O5=k({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return k({kind:"MatchedNode",not:W,bySource:$})}});function f6(W,$,Z){return i1.create(O8([O5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&Z?h1($[0],$[1],$[2]):M1($)]:[]],"and",!1))}function m8(W){if(a(W))return X1.create([W],[]);if(G1(W))return W.toOperationNode();return W}class y0{#W;#$;#Z;constructor(){this.#W=new Promise((W,$)=>{this.#Z=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{this.#$?.(W),this.#$=this.#Z=void 0};reject=(W)=>{this.#Z?.(W),this.#Z=this.#$=void 0}}async function c8(W,$){let Z=new y0,J=new y0;return W.provideConnection(async(X)=>{return Z.resolve(X),await J.promise},$).catch((X)=>Z.reject(X)),k({connection:await Z.promise,release:J.resolve})}function B5(W="ignore query",$,Z){if(W==="ignore query")return;if(W==="cancel query"){let J=$.cancelQuery;if(!J)x5(W,$.killSession?"kill session":void 0);return J.bind($)}if(W==="kill session"){let J=$.killSession;if(!J)x5(W,$.cancelQuery?"cancel query":void 0);return J.bind($)}throw Z(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${W}"`)}function x5(W,$){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${W}". Use "ignore query"${$?` or "${$}"`:""} instead.`)}function g0(W,$,Z){if(W?.aborted)Z?.(),Z8(W.reason,$)}function Z8(W,$){throw i2(W,$),W}var $0={};async function u8(W,$,Z,J){if(!$)return W;g0($,`before ${Z}`,J);let{promise:X,resolve:Y}=new y0,L=()=>Y($0);$.addEventListener("abort",L);try{g0($,`before ${Z}`,J);let G=await Promise.race([W,X]);if(G!==$0)return G;J?.(),Z8($.reason,`during ${Z}`)}finally{$.removeEventListener("abort",L),Y($0)}}function v0(W){return($)=>console.error(`\`${W}\` failed in the background after abortion: ${s9($)}`)}function i2(W,$){if(W!==null&&typeof W==="object"&&!Object.isFrozen(W))Object.defineProperty(W,"__kysely_timing__",{configurable:!0,enumerable:!1,value:$,writable:!1})}var t2=k([]);class _W{#W;constructor(W=t2){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let Z of this.#W){let J=Z.transformQuery({node:W,queryId:$});if(J.kind===W.kind)W=J;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${W.kind}`,`but it returned a ${J.kind}`].join(" "))}return W}async executeQuery(W,$){let{inflightQueryAbortStrategy:Z="ignore query",signal:J}=$||{};if(!J){let P=await this.provideConnection(async(w)=>{return await w.executeQuery(W)},$);return await this.#$(P,W.queryId)}g0(J,"before query execution"),$=k({signal:J});let{connection:X,release:Y}=await c8(this,$),L=this.provideConnection.bind(this),{promise:G,resolve:U}=new y0,D=()=>U($0);J.addEventListener("abort",D,{once:!0});try{g0(J,"before query execution",Y);let P=B5(Z,X,Y);if(P&&X.collectSessionInfo){g0(J,"before query execution",Y);let K=X.collectSessionInfo();if(await Promise.race([G,K]).catch((_)=>{throw Y(),_})===$0)K.catch(v0("collectSessionInfo")).finally(Y),Z8(J.reason,"before query execution")}let w=X.executeQuery(W,$),R=await Promise.race([G,w]).catch((K)=>{throw Y(),K});if(R===$0)Promise.allSettled([w.catch(v0("query")),P?.(L).catch(v0("inflightQueryAbortHandler"))]).finally(Y),Z8(J.reason,"during query execution");else Y();let S=this.#$(R,W.queryId,$),F=await Promise.race([G,S]);if(F===$0)S.catch(v0("plugins.transformResult")),Z8(J.reason,"during result transformation");return F}finally{U($0),J.removeEventListener("abort",D)}}async*stream(W,$,Z){let{signal:J}=Z||{};if(!J){let{connection:R,release:S}=await c8(this);try{for await(let F of R.streamQuery(W,$))yield await this.#$(F,W.queryId,Z)}finally{S()}return}Z=k({signal:J}),g0(J,"before connection acquisition");let{connection:X,release:Y}=await c8(this,Z),{promise:L,resolve:G}=new y0,U=()=>G($0);J.addEventListener("abort",U,{once:!0});let D,P;g0(J,"before query streaming",Y);let{queryId:w}=W;try{D=X.streamQuery(W,$,Z);while(!0){g0(J,"during query streaming");let R=D.next(),S=await Promise.race([L,R]);if(S===$0)P=R.catch(v0("iterator.next")),Z8(J.reason,"during query streaming");if(S.done)break;let F=this.#$(S.value,w,Z),K=await Promise.race([L,F]);if(K===$0)P=F.catch(v0("plugins.transformResult")),Z8(J.reason,"during result transformation");yield K}}finally{G($0),J.removeEventListener("abort",U);let R=(D?.return?.()||Promise.resolve()).finally(()=>P).finally(Y);if(!P)await R}}async#$(W,$,Z){let{signal:J}=Z||{};for(let X of this.#W)W=await X.transformResult(k({queryId:$,result:W,signal:J}));return W}}class l8 extends _W{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(W){return new l8([...this.plugins,W])}withPlugins(W){return new l8([...this.plugins,...W])}withPluginAtFront(W){return new l8([W,...this.plugins])}withoutPlugins(){return new l8([])}}var J8=new l8;class j6{numChangedRows;constructor(W){this.numChangedRows=W}}class m0{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new m0({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new m0({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(...W){return new t1({...this.#W,queryNode:W0.cloneWithUsing(this.#W.queryNode,$8("Using",W))})}returning(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}}class t1{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new t1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new t1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,Z){return this.#$([W,$,Z],!0)}#$(W,$){return new A6({...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,f6({isMatched:!0},W,$))})}whenNotMatched(){return this.#Z([])}whenNotMatchedAnd(...W){return this.#Z(W)}whenNotMatchedAndRef(W,$,Z){return this.#Z([W,$,Z],!0)}whenNotMatchedBySource(){return this.#Z([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#Z(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,Z){return this.#Z([W,$,Z],!0,!0)}returning(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}#Z(W,$=!1,Z=!1){let J={...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,f6({isMatched:!1,bySource:Z},W,$))};return new(Z?A6:b5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new t1({...this.#W})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new j6(Z.numAffectedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??M0;throw h0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}}class A6{#W;constructor(W){this.#W=k(W)}thenDelete(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,m8("delete"))})}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,m8("do nothing"))})}thenUpdate(W){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,m8(W(new y8({queryId:this.#W.queryId,executor:J8,queryNode:E0.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class b5{#W;constructor(W){this.#W=k(W)}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,m8("do nothing"))})}thenInsertValues(W){let[$,Z]=M4(W);return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,m8(S1.cloneWith(S1.createWithoutInto(),{columns:$,values:Z})))})}}class f0{#W;constructor(W){this.#W=k(W)}selectFrom(W){return EW({queryId:W1(),executor:this.#W.executor,queryNode:k1.createFrom(U0(W),this.#W.withNode)})}selectNoFrom(W){return EW({queryId:W1(),executor:this.#W.executor,queryNode:k1.cloneWithSelections(k1.create(this.#W.withNode),j1(W))})}insertInto(W){return new K1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode)})}replaceInto(W){return new K1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode,!0)})}deleteFrom(W){return new z4({queryId:W1(),executor:this.#W.executor,queryNode:W8.create(U0(W),this.#W.withNode)})}updateTable(W){return new y8({queryId:W1(),executor:this.#W.executor,queryNode:E0.create(U0(W),this.#W.withNode)})}mergeInto(W){return new m0({queryId:W1(),executor:this.#W.executor,queryNode:W0.create(N6(W),this.#W.withNode)})}with(W,$){let Z=T6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z)})}withRecursive(W,$){let Z=T6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z,{recursive:!0})})}withPlugin(W){return new f0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new f0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new f0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}}function f5(){return new f0({executor:J8})}function I5(W,$){return new x8({joinNode:G0.create(W,V8($))})}function y5(){return new B8({overNode:PW.create()})}function $8(W,$){if($.length===3)return d2(W,$[0],$[1],$[2]);else if($.length===2)return a2(W,$[0],$[1]);else if($.length===1)return s2(W,$[0]);else throw Error("not implemented")}function a2(W,$,Z){return Z(I5(W,$)).toOperationNode()}function d2(W,$,Z,J){return G0.createWithOn(W,V8($),h1(Z,"=",J))}function s2(W,$){return G0.create(W,V8($))}var g5=k({is(W){return W.kind==="OffsetNode"},create(W){return k({kind:"OffsetNode",offset:W})}});var m5=k({is(W){return W.kind==="GroupByItemNode"},create(W){return k({kind:"GroupByItemNode",groupBy:W})}});function c5(W){return W=D1(W)?W(K0()):W,b0(W).map(m5.create)}var U4=k({is(W){return W.kind==="SetOperationNode"},create(W,$,Z){return k({kind:"SetOperationNode",operator:W,expression:$,all:Z})}});function P8(W,$,Z){if(D1($))$=$(C6());if(!y1($))$=[$];return $.map((J)=>U4.create(W,O1(J),Z))}class Y1{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new F4(this,W)}or(...W){return new V4(k0.create(this.#W,M1(W)))}and(...W){return new P4(l1.create(this.#W,M1(W)))}$castTo(){return new Y1(this.#W)}$notNull(){return new Y1(this.#W)}toOperationNode(){return this.#W}}class F4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}class V4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new F4(this,W)}or(...W){return new V4(k0.create(this.#W,M1(W)))}$castTo(){return new V4(this.#W)}toOperationNode(){return e1.create(this.#W)}}class P4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new F4(this,W)}and(...W){return new P4(l1.create(this.#W,M1(W)))}$castTo(){return new P4(this.#W)}toOperationNode(){return e1.create(this.#W)}}var u5=k({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:R1.create(W),modifier:$}}});function l5(W,$){if(!d0(W)&&!v8(W))throw Error(`Invalid fetch row count: ${W}`);if(!n2($))throw Error(`Invalid fetch modifier: ${$}`);return u5.create(W,$)}function n2(W){return W==="only"||W==="with ties"}var n;class q6{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,M1(W))})}whereRef(W,$,Z){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,h1(W,$,Z))})}having(...W){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,M1(W))})}havingRef(W,$,Z){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,h1(W,$,Z))})}select(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,j1(W))})}distinctOn(W){return new n({...this.#W,queryNode:k1.cloneWithDistinctOn(this.#W.queryNode,b0(W))})}modifyFront(W){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}distinct(){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.create("Distinct"))})}forUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForUpdate",W?zW(W).map(Z1):void 0))})}forShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForShare",W?zW(W).map(Z1):void 0))})}forKeyShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForKeyShare",W?zW(W).map(Z1):void 0))})}forNoKeyUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForNoKeyUpdate",W?zW(W).map(Z1):void 0))})}skipLocked(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("SkipLocked"))})}noWait(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("NoWait"))})}selectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,x1(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}crossJoin(...W){return this.#$("CrossJoin",W)}innerJoinLateral(...W){return this.#$("LateralInnerJoin",W)}leftJoinLateral(...W){return this.#$("LateralLeftJoin",W)}crossJoinLateral(...W){return this.#$("LateralCrossJoin",W)}crossApply(...W){return this.#$("CrossApply",W)}outerApply(...W){return this.#$("OuterApply",W)}#$(W,$){return new n({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new n({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}groupBy(W){return new n({...this.#W,queryNode:k1.cloneWithGroupByItems(this.#W.queryNode,c5(W))})}limit(W){return new n({...this.#W,queryNode:k1.cloneWithLimit(this.#W.queryNode,I8.create(L1(W)))})}offset(W){return new n({...this.#W,queryNode:k1.cloneWithOffset(this.#W.queryNode,g5.create(L1(W)))})}fetch(W,$="only"){return new n({...this.#W,queryNode:k1.cloneWithFetch(this.#W.queryNode,l5(W,$))})}top(W,$){return new n({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}union(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!1))})}unionAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!0))})}intersect(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!1))})}intersectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!0))})}except(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!1))})}exceptAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!0))})}as(W){return new p5(this,W)}clearSelect(){return new n({...this.#W,queryNode:k1.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new n({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new n({...this.#W,queryNode:k1.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new n({...this.#W,queryNode:k1.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new n({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new n({...this.#W,queryNode:k1.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new n({...this.#W})}$castTo(){return new n(this.#W)}$narrowType(){return new n(this.#W)}$assertType(){return new n(this.#W)}$asTuple(){return new Y1(this.toOperationNode())}$asScalar(){return new Y1(this.toOperationNode())}withPlugin(W){return new n({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile();return(await this.#W.executor.executeQuery($,W)).rows}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??M0;throw h0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new n({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}n=q6;function EW(W){return new q6(W)}class p5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}var j0=k({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return k({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return k({...W,distinct:!0})},cloneWithOrderBy(W,$,Z=!1){let J=Z?"withinGroup":"orderBy";return k({...W,[J]:W[J]?I0.cloneWithItems(W[J],$):I0.create($)})},cloneWithFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"And",$):b1.create($)})},cloneWithOrFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"Or",$):b1.create($)})},cloneWithOver(W,$){return k({...W,over:$})}});var O6=k({is(W){return W.kind==="FunctionNode"},create(W,$){return k({kind:"FunctionNode",func:W,arguments:$})}});class a1{#W;constructor(W){this.#W=k(W)}get expressionType(){return}as(W){return new i5(this,W)}distinct(){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithOrderByItems(this.#W.aggregateFunctionNode,o1(W))})}clearOrderBy(){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOrderBy(this.#W.aggregateFunctionNode,o1(W),!0)})}filterWhere(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,M1(W))})}filterWhereRef(W,$,Z){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,h1(W,$,Z))})}over(W){let $=y5();return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new a1(this.#W)}$notNull(){return new a1(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class i5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}function D4(){let W=(Z,J)=>{return new Y1(O6.create(Z,b0(J??[])))},$=(Z,J)=>{return new a1({aggregateFunctionNode:j0.create(Z,J?b0(J):void 0)})};return Object.assign(W,{agg:$,avg(Z){return $("avg",[Z])},coalesce(...Z){return W("coalesce",Z)},count(Z){return $("count",[Z])},countAll(Z){return new a1({aggregateFunctionNode:j0.create("count",x1(Z))})},max(Z){return $("max",[Z])},min(Z){return $("min",[Z])},sum(Z){return $("sum",[Z])},any(Z){return W("any",[Z])},jsonAgg(Z){return new a1({aggregateFunctionNode:j0.create("json_agg",[a(Z)?Z1(Z):Z.toOperationNode()])})},toJson(Z){return new Y1(O6.create("to_json",[a(Z)?Z1(Z):Z.toOperationNode()]))}})}var t5=k({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return k({kind:"UnaryOperationNode",operator:W,operand:$})}});function a5(W,$){if(H5(W))return t5.create(r1.create(W),v1($));throw Error(`invalid unary operator ${JSON.stringify(W)}`)}var I1=k({is(W){return W.kind==="CaseNode"},create(W){return k({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return k({...W,when:k(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return k({...W,when:W.when?k([...W.when.slice(0,-1),i1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return k({...W,...$})}});class TW{#W;constructor(W){this.#W=k(W)}when(...W){return new hW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(M1(W)))})}whenRef(W,$,Z){return new hW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(h1(W,$,Z)))})}}class hW{#W;constructor(W){this.#W=k(W)}then(W){return new x6({...this.#W,node:I1.cloneWithThen(this.#W.node,k4(W)?VW(W):L1(W))})}thenRef(W){return new x6({...this.#W,node:I1.cloneWithThen(this.#W.node,v1(W))})}}class x6{#W;constructor(W){this.#W=k(W)}when(...W){return new hW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(M1(W)))})}whenRef(W,$,Z){return new hW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(h1(W,$,Z)))})}else(W){return new B6({...this.#W,node:I1.cloneWith(this.#W.node,{else:k4(W)?VW(W):L1(W)})})}elseRef(W){return new B6({...this.#W,node:I1.cloneWith(this.#W.node,{else:v1(W)})})}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}class B6{#W;constructor(W){this.#W=k(W)}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}var b6=k({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return k({kind:"JSONPathLegNode",type:W,value:$})}});var r2=/^#-\d+$/;class fW{#W;constructor(W){this.#W=W}at(W){if(typeof W!=="number"&&typeof W!=="string"||typeof W==="number"&&!Number.isInteger(W)||typeof W==="string"&&W!=="last"&&!r2.test(W))throw Error(`Unexpected index value in .at(...): ${W}`);return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(C8.is(this.#W))return new vW(C8.cloneWithTraversal(this.#W,o0.is(this.#W.traversal)?o0.cloneWithLeg(this.#W.traversal,b6.create(W,$)):Y4.cloneWithValue(this.#W.traversal,R1.createImmediate($))));return new vW(o0.cloneWithLeg(this.#W,b6.create(W,$)))}}class vW extends fW{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new d5(this,W)}$castTo(){return new vW(this.#W)}$notNull(){return new vW(this.#W)}toOperationNode(){return this.#W}}class d5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var I6=k({is(W){return W.kind==="TupleNode"},create(W){return k({kind:"TupleNode",values:k(W)})}});var o2=k({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),e2=k([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),s5=k({is(W){return W.kind==="DataTypeNode"},create(W){return k({kind:"DataTypeNode",dataType:W})}});function n5(W){return o2[W]||e2.some(($)=>$.test(W))}function P0(W){if(G1(W))return W.toOperationNode();if(n5(W))return s5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var r5=k({is(W){return W.kind==="CastNode"},create(W,$){return k({kind:"CastNode",expression:W,dataType:$})}});function C6(W=J8){function $(X,Y,L){return new Y1(G4(X,Y,L))}function Z(X,Y){return new Y1(a5(X,Y))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(X){return EW({queryId:W1(),executor:W,queryNode:k1.createFrom(U0(X))})},case(X){return new TW({node:I1.create(n1(X)?void 0:v1(X))})},ref(X,Y){if(n1(Y))return new Y1(p1(X));return new fW(K5(X,Y))},jsonPath(){return new fW(o0.create())},table(X){return new Y1(Z1(X))},val(X){return new Y1(L1(X))},refTuple(...X){return new Y1(I6.create(X.map(v1)))},tuple(...X){return new Y1(I6.create(X.map(L1)))},lit(X){return new Y1(VW(X))},unary:Z,not(X){return Z("not",X)},exists(X){return Z("exists",X)},neg(X){return Z("-",X)},between(X,Y,L){return new Y1(n0.create(v1(X),r1.create("between"),l1.create(L1(Y),L1(L))))},betweenSymmetric(X,Y,L){return new Y1(n0.create(v1(X),r1.create("between symmetric"),l1.create(L1(Y),L1(L))))},and(X){if(y1(X))return new Y1(O8(X,"and"));return new Y1(V6(X,"and"))},or(X){if(y1(X))return new Y1(O8(X,"or"));return new Y1(V6(X,"or"))},parens(...X){let Y=M1(X);if(e1.is(Y))return new Y1(Y);else return new Y1(e1.create(Y))},cast(X,Y){return new Y1(r5.create(v1(X),P0(Y)))}});return J.fn=D4(),J.eb=J,J}function K0(W){return C6()}function O1(W){if(G1(W))return W.toOperationNode();else if(D1(W))return W(K0()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function K4(W){if(G1(W))return W.toOperationNode();else if(D1(W))return W(K0()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function B0(W){return Z4(W)||r9(W)||D1(W)}class y6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new o5(this.#W,W)}}class o5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return q1.create(Z1(this.#W),l.create(this.#$))}}function e5(W){return Q1(W)&&G1(W)&&a(W.table)&&a(W.alias)}function U0(W){if(y1(W))return W.map(($)=>V8($));else return[V8(W)]}function V8(W){if(a(W))return N6(W);else if(e5(W))return W.toOperationNode();else return K4(W)}function N6(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(W7);return q1.create(Z1(Z),l.create(J))}else return Z1(W)}function Z1(W){if(W.includes(".")){let[Z,J]=W.split(".").map(W7);return u1.createWithSchema(Z,J)}else return u1.create(W)}function W7(W){return W.trim()}var g6=k({is(W){return W.kind==="AddColumnNode"},create(W){return k({kind:"AddColumnNode",column:W})}});var z1=k({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return k({kind:"ColumnDefinitionNode",column:e.create(W),dataType:$})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):[$]})},cloneWith(W,$){return k({...W,...$})}});var jW=k({is(W){return W.kind==="DropColumnNode"},create(W){return k({kind:"DropColumnNode",column:e.create(W)})},cloneWith(W,$){return k({...W,...$})}});var m6=k({is(W){return W.kind==="RenameColumnNode"},create(W,$){return k({kind:"RenameColumnNode",column:e.create(W),renameTo:e.create($)})}});var p8=k({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return k({kind:"CheckConstraintNode",expression:W,name:$?l.create($):void 0})}});var $7=k({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),GV=Object.keys($7),i8=k({is(W){return W.kind==="ReferencesNode"},create(W,$){return k({kind:"ReferencesNode",table:W,columns:k([...$])})},cloneWithOnDelete(W,$){return k({...W,onDelete:$})},cloneWithOnUpdate(W,$){return k({...W,onUpdate:$})}});function Z7(W){return a(W)&&$7[W]}function R4(W){return G1(W)?W.toOperationNode():R1.createImmediate(W)}var AW=k({is(W){return W.kind==="GeneratedNode"},create(W){return k({kind:"GeneratedNode",...W})},createWithExpression(W){return k({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return k({...W,...$})}});var J7=k({is(W){return W.kind==="DefaultValueNode"},create(W){return k({kind:"DefaultValueNode",defaultValue:W})}});function t8(W){if(Z7(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class U1{#W;constructor(W){this.#W=W}autoIncrement(){return new U1(z1.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new U1(z1.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new U1(z1.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=p1(W);if(!$.table||j8.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new U1(z1.cloneWith(this.#W,{references:i8.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:i8.cloneWithOnDelete(this.#W.references,t8(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:i8.cloneWithOnUpdate(this.#W.references,t8(W))}))}unique(){return new U1(z1.cloneWith(this.#W,{unique:!0}))}notNull(){return new U1(z1.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new U1(z1.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new U1(z1.cloneWith(this.#W,{defaultTo:J7.create(R4(W))}))}check(W){return new U1(z1.cloneWith(this.#W,{check:p8.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new U1(z1.cloneWith(this.#W,{generated:AW.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new U1(z1.cloneWith(this.#W,{generated:AW.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new U1(z1.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new U1(z1.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new U1(z1.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new U1(z1.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var c6=k({is(W){return W.kind==="ModifyColumnNode"},create(W){return k({kind:"ModifyColumnNode",column:W})}});var F0=k({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,Z,J){return k({kind:"ForeignKeyConstraintNode",columns:W,references:i8.create($,Z),name:J?l.create(J):void 0})},cloneWith(W,$){return k({...W,...$})}});class D0{#W;constructor(W){this.#W=W}onDelete(W){return new D0(F0.cloneWith(this.#W,{onDelete:t8(W)}))}onUpdate(W){return new D0(F0.cloneWith(this.#W,{onUpdate:t8(W)}))}deferrable(){return new D0(F0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new D0(F0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new D0(F0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new D0(F0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var a8=k({is(W){return W.kind==="AddConstraintNode"},create(W){return k({kind:"AddConstraintNode",constraint:W})}});var A0=k({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,Z){if(a(W.at(0)))N8("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),W=W.map(e.create);return k({kind:"UniqueConstraintNode",columns:k(W),name:$?l.create($):void 0,nullsNotDistinct:Z})},cloneWith(W,$){return k({...W,...$})}});var d8=k({is(W){return W.kind==="DropConstraintNode"},create(W){return k({kind:"DropConstraintNode",constraintName:l.create(W)})},cloneWith(W,$){return k({...W,...$})}});var s8=k({is(W){return W.kind==="AlterColumnNode"},create(W,$,Z){return k({kind:"AlterColumnNode",column:e.create(W),[$]:Z})}});class w4{#W;constructor(W){this.#W=W}setDataType(W){return new n8(s8.create(this.#W,"dataType",P0(W)))}setDefault(W){return new n8(s8.create(this.#W,"setDefault",R4(W)))}dropDefault(){return new n8(s8.create(this.#W,"dropDefault",!0))}setNotNull(){return new n8(s8.create(this.#W,"setNotNull",!0))}dropNotNull(){return new n8(s8.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class n8{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class X8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class c0{#W;constructor(W){this.#W=k(W)}onDelete(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($1.cloneWithTableProps(this.#W.node,{addConstraint:a8.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class F8{#W;constructor(W){this.#W=k(W)}ifExists(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:d8.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:d8.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:d8.cloneWith(this.#W.node.dropConstraint,{modifier:"restrict"})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var u0=k({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return k({kind:"PrimaryKeyConstraintNode",columns:k(W.map(e.create)),name:$?l.create($):void 0})},cloneWith(W,$){return k({...W,...$})}});var Z0=k({is(W){return W.kind==="AddIndexNode"},create(W){return k({kind:"AddIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});class Y8{#W;constructor(W){this.#W=k(W)}unique(){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[a(W)?q8(W):W.toOperationNode()])})})}columns(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,W.map(($)=>a($)?q8($):$.toOperationNode()))})})}expression(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{using:X1.createWithSql(W)})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class N0{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N0(A0.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class l0{#W;constructor(W){this.#W=W}deferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class NW{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var X7=k({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return k({kind:"RenameConstraintNode",oldName:l.create(W),newName:l.create($)})}});class CW{#W;constructor(W){this.#W=k({...W})}ifExists(){return new CW({...this.#W,node:jW.cloneWith(this.#W.node,{ifExists:!0})})}toOperationNode(){return this.#W.node}}class u6{#W;constructor(W){this.#W=k(W)}renameTo(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameTo:Z1(W)})})}setSchema(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{setSchema:l.create(W)})})}alterColumn(W,$){let Z=$(new w4(W));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,c6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:a8.create(J.toOperationNode())})})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(p8.create($.toOperationNode(),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:a8.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new D0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c0({...this.#W,constraintBuilder:Y})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:a8.create(J.toOperationNode())})})}dropConstraint(W){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:d8.create(W)})})}renameConstraint(W,$){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameConstraint:X7.create(W,$)})})}addIndex(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.create(W)})})}dropIndex(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropIndex:s0.create(W)})})}$call(W){return W(this)}}class R0{#W;constructor(W){this.#W=k(W)}alterColumn(W,$){let Z=$(new w4(W));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new R0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,c6.create(J.toOperationNode()))})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class qW extends SW{transformPrimitiveValueList(W){return e0.create(W.values.map(R1.createImmediate))}transformValue(W){return R1.createImmediate(W.value)}}class J0{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{table:Z1(W)})})}column(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[a(W)?q8(W):W.toOperationNode()])})}columns(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,W.map(($)=>a($)?q8($):$.toOperationNode()))})}expression(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{using:X1.createWithSql(W)})})}where(...W){let $=new qW;return new J0({...this.#W,node:y.cloneWithWhere(this.#W.node,$.transformNode(M1(W),this.#W.queryId))})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class Q4{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new Q4({...this.#W,node:$4.cloneWith(this.#W.node,{ifNotExists:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function Y7(W){if(n9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class S4{#W;constructor(W){this.#W=W}using(W){return new S4(Z0.cloneWith(this.#W,{using:X1.createWithSql(W)}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class c1{#W;constructor(W){this.#W=k(W)}temporary(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{onCommit:Y7(W)})})}ifNotExists(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new c1({...this.#W,node:C1.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addIndex(W,$,Z=N1){let J=Z(new S4(Z0.cloneWithColumns(Z0.create(W),$.map((X)=>a(X)?e.create(X):O1(X)))));return new c1({...this.#W,node:C1.cloneWithIndex(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(p8.create($.toOperationNode(),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new D0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,Y.toOperationNode())})}modifyFront(W){return new c1({...this.#W,node:C1.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new c1({...this.#W,node:C1.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{selectQuery:O1(W)})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class r8{#W;constructor(W){this.#W=k(W)}on(W){return new r8({...this.#W,node:s0.cloneWith(this.#W.node,{table:Z1(W)})})}ifExists(){return new r8({...this.#W,node:s0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new r8({...this.#W,node:s0.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class OW{#W;constructor(W){this.#W=k(W)}ifExists(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class o8{#W;constructor(W){this.#W=k(W)}temporary(){return new o8({...this.#W,node:f8.cloneWith(this.#W.node,{temporary:!0})})}ifExists(){return new o8({...this.#W,node:f8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new o8({...this.#W,node:f8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var w0=k({is(W){return W.kind==="CreateViewNode"},create(W){return k({kind:"CreateViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class l6{#W=new qW;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class p0{#W;constructor(W){this.#W=k(W)}temporary(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{columns:W.map(M6)})})}as(W){let $=W.withPlugin(new l6).toOperationNode();return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{as:$})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var e8=k({is(W){return W.kind==="DropViewNode"},create(W){return k({kind:"DropViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class WW{#W;constructor(W){this.#W=k(W)}materialized(){return new WW({...this.#W,node:e8.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new WW({...this.#W,node:e8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new WW({...this.#W,node:e8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var _4=k({is(W){return W.kind==="CreateTypeNode"},create(W){return k({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return k({...W,enum:e0.create($.map(R1.createImmediate))})}});class E4{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new E4({...this.#W,node:_4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var xW=k({is(W){return W.kind==="DropTypeNode"},create(W){if(!Array.isArray(W))W=[W];return k({kind:"DropTypeNode",name:W[0],additionalNames:W.slice(1)})},cloneWith(W,$){return k({...W,...$})}});class BW{#W;constructor(W){this.#W=k(W)}ifExists(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function h4(W){if(W.includes(".")){let Z=W.split(".").map(WZ);if(Z.length===2)return g1.createWithSchema(Z[0],Z[1]);else throw Error(`invalid schemable identifier ${W}`)}else return g1.create(W)}function H7(W){if(!Array.isArray(W))W=[W];return W.map(h4)}function WZ(W){return W.trim()}var $W=k({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return k({kind:"RefreshMaterializedViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class ZW{#W;constructor(W){this.#W=k(W)}concurrently(){return new ZW({...this.#W,node:$W.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new ZW({...this.#W,node:$W.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new ZW({...this.#W,node:$W.cloneWith(this.#W.node,{withNoData:!0,concurrently:!1})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var C0=k({is(W){return W.kind==="AlterTypeNode"},create(W){return k({kind:"AlterTypeNode",name:W})},cloneWith(W,$){return k({...W,...$})}});var bW=k({is(W){return W.kind==="AddValueNode"},create(W){return k({kind:"AddValueNode",value:W})},cloneWith(W,$){return k({...W,...$})}});class D8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){return await this.#W.executor.executeQuery(this.compile(),W)}}var p6;class T4 extends D8{#W;constructor(W){super(W);this.#W=W}ifNotExists(){return new p6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{ifNotExists:!0})})})}before(W){return this.#$(W,!0)}after(W){return this.#$(W,!1)}#$(W,$){return new p6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{isBefore:$,neighborValue:R1.createImmediate(W)})})})}}p6=T4;var k7=k({is(W){return W.kind==="RenameValueNode"},create(W,$){return k({kind:"RenameValueNode",oldValue:W,newValue:$})}});class i6{#W;constructor(W){this.#W=k(W)}addValue(W){return new T4({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.create(R1.createImmediate(W))})})}renameTo(W){return new D8({...this.#W,node:C0.cloneWith(this.#W.node,{renameTo:l.create(W)})})}renameValue(W,$){return new D8({...this.#W,node:C0.cloneWith(this.#W.node,{renameValue:k7.create(R1.createImmediate(W),R1.createImmediate($))})})}setSchema(W){return new D8({...this.#W,node:C0.cloneWith(this.#W.node,{setSchema:l.create(W)})})}}class JW{#W;constructor(W){this.#W=W}createTable(W){return new c1({queryId:W1(),executor:this.#W,node:C1.create(Z1(W))})}dropTable(W){return new o8({queryId:W1(),executor:this.#W,node:f8.create(Z1(W))})}createIndex(W){return new J0({queryId:W1(),executor:this.#W,node:H0.create(W)})}dropIndex(W){return new r8({queryId:W1(),executor:this.#W,node:s0.create(W)})}createSchema(W){return new Q4({queryId:W1(),executor:this.#W,node:$4.create(W)})}dropSchema(W){return new OW({queryId:W1(),executor:this.#W,node:UW.create(W)})}alterTable(W){return new u6({queryId:W1(),executor:this.#W,node:$1.create(Z1(W))})}createView(W){return new p0({queryId:W1(),executor:this.#W,node:w0.create(W)})}refreshMaterializedView(W){return new ZW({queryId:W1(),executor:this.#W,node:$W.create(W)})}dropView(W){return new WW({queryId:W1(),executor:this.#W,node:e8.create(W)})}createType(W){return new E4({queryId:W1(),executor:this.#W,node:_4.create(h4(W))})}alterType(W){return new i6({executor:this.#W,node:C0.create(h4(W)),queryId:W1()})}dropType(W){return new BW({queryId:W1(),executor:this.#W,node:xW.create(H7(W))})}withPlugin(W){return new JW(this.#W.withPlugin(W))}withoutPlugins(){return new JW(this.#W.withoutPlugins())}withSchema(W){return new JW(this.#W.withPluginAtFront(new V0(W)))}}class t6{ref(W){return new k6(W)}table(W){return new y6(W)}}class a6{#W;constructor(W){this.#W=W}async provideConnection(W,$){let Z=await this.#W.acquireConnection($);try{return await W(Z)}finally{await this.#W.releaseConnection(Z,$)}}}class H8 extends _W{#W;#$;#Z;constructor(W,$,Z,J=[]){super(J);this.#W=W,this.#$=$,this.#Z=Z}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#Z.provideConnection(W,$)}withPlugins(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,...W])}withPlugin(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,W])}withPluginAtFront(W){return new H8(this.#W,this.#$,this.#Z,[W,...this.plugins])}withConnectionProvider(W){return new H8(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new H8(this.#W,this.#$,this.#Z,[])}}function v4(){if(typeof performance<"u"&&D1(performance.now))return performance.now();else return Date.now()}class d6{#W;#$;async obtainLock(){while(this.#W)await this.#W;this.#W=new Promise((W)=>{this.#$=W})}releaseLock(){let W=this.#$;this.#W=void 0,this.#$=void 0,W?.()}}class s6{#W;#$;#Z;#X;#Y;#k=new WeakSet;#J;constructor(W,$,Z){if(this.#W=W,this.#X=!1,this.#$=Z,$.supportsMultipleConnections===!1)this.#J=new d6}async init(W){if(this.#Y)throw Error("driver has already been destroyed");this.#Z??=this.#W.init(W).then(()=>{this.#X=!0}).catch(($)=>{throw this.#Z=void 0,$}),await u8(this.#Z,W?.signal,"init")}async acquireConnection(W){if(this.#Y)throw Error("driver has already been destroyed");if(!this.#X)await this.init(W);if(this.#J){let J=this.#J.obtainLock();await u8(J,W?.signal,"acquireConnection:mutex",()=>J.then(()=>this.#J?.releaseLock()))}let $=this.#W.acquireConnection(W),Z=await u8($,W?.signal,"acquireConnection:acquire",()=>$?.then((J)=>this.releaseConnection(J).catch(v0("driver.releaseConnection"))).catch(v0("driver.acquireConnection")));if(!this.#k.has(Z)){if(this.#H())this.#G(Z);this.#k.add(Z)}return Z}async releaseConnection(W,$){await this.#W.releaseConnection(W,$),this.#J?.releaseLock()}async beginTransaction(W,$){return await this.#W.beginTransaction(W,$)}async commitTransaction(W){return await this.#W.commitTransaction(W)}async rollbackTransaction(W){return await this.#W.rollbackTransaction(W)}async savepoint(W,$,Z){if(this.#W.savepoint)return await this.#W.savepoint(W,$,Z);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(W,$,Z){if(this.#W.rollbackToSavepoint)return await this.#W.rollbackToSavepoint(W,$,Z);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(W,$,Z){if(this.#W.releaseSavepoint)return await this.#W.releaseSavepoint(W,$,Z);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(W){if(!this.#Z)return;await u8(this.#Z,W?.signal,"destroy:initPromise"),this.#Y??=this.#W.destroy(W).catch(($)=>{throw this.#Y=void 0,$}),await u8(this.#Y,W?.signal,"destroy")}#H(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#G(W){let{executeQuery:$,streamQuery:Z}=W,J=this;W.executeQuery=async(X,Y)=>{let L,G=v4();try{return await $.call(W,X,Y)}catch(U){throw L=U,await J.#M(U,X,G),U}finally{if(!L)await J.#z(X,G)}},W.streamQuery=async function*(X,Y,L){let G,U=v4();try{for await(let D of Z.call(W,X,Y,L))yield D}catch(D){throw G=D,await J.#M(D,X,U),D}finally{if(!G)await J.#z(X,U,!0)}}}async#M(W,$,Z){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#L(Z)}))}async#z(W,$,Z=!1){await this.#$.query(()=>({level:"query",isStream:Z,query:W,queryDurationMillis:this.#L($)}))}#L(W){return v4()-W}}var $Z=()=>{};class IW{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch($Z);return this.#$=this.#Z(W).finally(()=>{this.#$=void 0}),this.#$}async#Z(W){return await W(this.#W)}}var ZZ=["read only","read write"],JZ=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function n6(W){if(W.accessMode&&!ZZ.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!JZ.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var XZ=["query","error"],Gw=k(XZ);class r6{#W;#$;constructor(W){if(D1(W))this.#$=W,this.#W=k({query:!0,error:!0});else this.#$=YZ,this.#W=k({query:W.includes("query"),error:W.includes("error")})}isLevelEnabled(W){return this.#W[W]}async query(W){if(this.#W.query)await this.#$(W())}async error(W){if(this.#W.error)await this.#$(W())}}function YZ(W){if(W.level==="query"){let $=`kysely:query:${W.isStream?"stream:":""}`;console.log(`${$} ${W.query.sql}`),console.log(`${$} duration: ${W.queryDurationMillis.toFixed(1)}ms`)}else if(W.level==="error")if(W.error instanceof Error)console.error(`kysely:error: ${W.error.stack??W.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:W.error,query:W.query.sql,queryDurationMillis:W.queryDurationMillis})}`)}function G7(W){return Q1(W)&&D1(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class Q0 extends f0{#W;constructor(W){let $,Z;if(HZ(W))$={executor:W.executor},Z={...W};else{let J=W.dialect,X=J.createDriver(),Y=J.createQueryCompiler(),L=J.createAdapter(),G=new r6(W.log??[]),U=new s6(X,L,G),D=new a6(U),P=new H8(Y,L,D,W.plugins??[]);$={executor:P},Z={config:W,executor:P,dialect:J,driver:U}}super($);this.#W=k(Z)}get schema(){return new JW(this.#W.executor)}get dynamic(){return new t6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new TW({node:I1.create(n1(W)?void 0:O1(W))})}get fn(){return D4()}transaction(){return new f4({...this.#W})}startTransaction(){return new j4({...this.#W})}connection(){return new L7({...this.#W})}withPlugin(W){return new Q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new Q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new Q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}$extendTables(){return new Q0({...this.#W})}$omitTables(){return new Q0({...this.#W})}$pickTables(){return new Q0({...this.#W})}withTables(){return this.$extendTables()}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}async executeQuery(W,$){let Z=G7(W)?W.compile():W;return await this.#W.executor.executeQuery(Z,$)}async[Symbol.asyncDispose](){await this.destroy()}}class q0 extends Q0{#W;constructor(W){super(W);this.#W=W}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new q0({...this.#W})}$extendTables(){return new q0({...this.#W})}$omitTables(){return new q0({...this.#W})}$pickTables(){return new q0({...this.#W})}}function HZ(W){return Q1(W)&&Q1(W.config)&&Q1(W.driver)&&Q1(W.executor)&&Q1(W.dialect)}class L7{#W;constructor(W){this.#W=k(W)}async execute(W,$){return this.#W.executor.provideConnection(async(Z)=>{let J=this.#W.executor.withConnectionProvider(new IW(Z)),X=new Q0({...this.#W,executor:J});return await W(X)},k({signal:$?.signal}))}}class f4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new f4({...this.#W,accessMode:W})}setIsolationLevel(W){return new f4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:Z,...J}=this.#W,X={isolationLevel:$,accessMode:Z};return n6(X),this.#W.executor.provideConnection(async(Y)=>{let L={isCommitted:!1,isRolledBack:!1},G=new i0(this.#W.executor.withConnectionProvider(new IW(Y)),L),U=new q0({...J,executor:G}),D=!1;try{await this.#W.driver.beginTransaction(Y,X),D=!0;let P=await W(U);return await this.#W.driver.commitTransaction(Y),L.isCommitted=!0,P}catch(P){if(D)await this.#W.driver.rollbackTransaction(Y),L.isRolledBack=!0;throw P}})}}class j4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new j4({...this.#W,accessMode:W})}setIsolationLevel(W){return new j4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...Z}=this.#W,J={isolationLevel:W,accessMode:$};n6(J);let X=await c8(this.#W.executor);return await this.#W.driver.beginTransaction(X.connection,J),new X0({...Z,connection:X,executor:this.#W.executor.withConnectionProvider(new IW(X.connection))})}}class X0 extends q0{#W;#$;#Z;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new i0(W.executor,$)};let{connection:Z,...J}=W;super(J);this.#W=k(W),this.#Z=$;let X=W1();this.#$=(Y)=>W.executor.compileQuery(Y,X)}get isCommitted(){return this.#Z.isCommitted}get isRolledBack(){return this.#Z.isRolledBack}commit(){return R8(this.#Z),new XW(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#Z.isCommitted=!0,this.#W.connection.release()})}rollback(){return R8(this.#Z),new XW(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#Z.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return R8(this.#Z),new XW(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}rollbackToSavepoint(W){return R8(this.#Z),new XW(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}releaseSavepoint(W){return R8(this.#Z),new XW(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}withPlugin(W){return new X0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new X0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new X0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new X0({...this.#W})}$extendTables(){return new X0({...this.#W})}$omitTables(){return new X0({...this.#W})}$pickTables(){return new X0({...this.#W})}}class XW{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function R8(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class i0{#W;#$;constructor(W,$){this.#W=W instanceof i0?W.#W:W,this.#$=$}get adapter(){return this.#W.adapter}get plugins(){return this.#W.plugins}transformQuery(W,$){return this.#W.transformQuery(W,$)}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#W.provideConnection(W,$)}executeQuery(W,$){return R8(this.#$),this.#W.executeQuery(W,$)}stream(W,$,Z){return R8(this.#$),this.#W.stream(W,$,Z)}withConnectionProvider(W){return new i0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new i0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new i0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new i0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new i0(this.#W.withoutPlugins(),this.#$)}}class yW{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new K7(this,W)}$castTo(){return new yW({...this.#W})}$notNull(){return new yW(this.#W)}withPlugin(W){return new yW({...this.#W,plugins:this.#W.plugins!==void 0?k([...this.#W.plugins,W]):k([W])})}toOperationNode(){return this.#Z(this.#$())}compile(W){return this.#X(this.#$(W))}async execute(W,$){let Z=this.#$(W);return Z.executeQuery(this.#X(Z),$)}#$(W){let $=W!==void 0?W.getExecutor():J8;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#Z(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#X(W){return W.compileQuery(this.#Z(W),this.#W.queryId)}}function t0(W){return new yW(W)}class K7{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var k8=Object.assign((W,...$)=>{return t0({queryId:W1(),rawNode:X1.create(W,$?.map(M7)??[])})},{ref(W){return t0({queryId:W1(),rawNode:X1.createWithChild(p1(W))})},val(W){return t0({queryId:W1(),rawNode:X1.createWithChild(L1(W))})},table(W){return t0({queryId:W1(),rawNode:X1.createWithChild(Z1(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",t0({queryId:W1(),rawNode:X1.create($,W.map(l.create))})},lit(W){return t0({queryId:W1(),rawNode:X1.createWithChild(R1.createImmediate(W))})},raw(W){return t0({queryId:W1(),rawNode:X1.createWithSql(W)})},join(W,$=k8`, `){let Z=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let X=0;X<W.length;++X)if(Z[2*X]=M7(W[X]),X!==W.length-1)Z[2*X+1]=J;return t0({queryId:W1(),rawNode:X1.createWithChildren(Z)})}});function M7(W){if(G1(W))return W.toOperationNode();return L1(W)}class o6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=k({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var kZ=/'/g,GZ=/['"]/g;class e6 extends o6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),k({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!S1.is(this.parentNode)&&!C1.is(this.parentNode)&&!w0.is(this.parentNode)&&!U4.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("select"),W.distinctOn)this.append(" "),this.compileDistinctOn(W.distinctOn);if(W.frontModifiers?.length)this.append(" "),this.compileList(W.frontModifiers," ");if(W.top)this.append(" "),this.visitNode(W.top);if(W.selections)this.append(" "),this.compileList(W.selections);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.groupBy)this.append(" "),this.visitNode(W.groupBy);if(W.having)this.append(" "),this.visitNode(W.having);if(W.setOperations)this.append(" "),this.compileList(W.setOperations," ");if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.offset)this.append(" "),this.visitNode(W.offset);if(W.fetch)this.append(" "),this.visitNode(W.fetch);if(W.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers(W.endModifiers)," ");if($)this.append(")")}visitFrom(W){this.append("from "),this.compileList(W.froms)}visitSelection(W){this.visitNode(W.selection)}visitColumn(W){this.visitNode(W.column)}compileDistinctOn(W){this.append("distinct on ("),this.compileList(W),this.append(")")}compileList(W,$=", "){let Z=W.length-1;for(let J=0;J<=Z;J++)if(this.visitNode(W[J]),J<Z)this.append($)}visitWhere(W){this.append("where "),this.visitNode(W.where)}visitHaving(W){this.append("having "),this.visitNode(W.having)}visitInsertQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append(W.replace?"replace":"insert"),W.orAction)this.append(" "),this.visitNode(W.orAction);if(W.top)this.append(" "),this.visitNode(W.top);if(W.into)this.append(" into "),this.visitNode(W.into);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.output)this.append(" "),this.visitNode(W.output);if(W.values)this.append(" "),this.visitNode(W.values);if(W.defaultValues)this.append(" "),this.append("default values");if(W.onConflict)this.append(" "),this.visitNode(W.onConflict);if(W.onDuplicateKey)this.append(" "),this.visitNode(W.onDuplicateKey);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitValues(W){this.append("values "),this.compileList(W.values)}visitDeleteQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("delete "),W.top)this.visitNode(W.top),this.append(" ");if(this.visitNode(W.from),W.output)this.append(" "),this.visitNode(W.output);if(W.using)this.append(" "),this.visitNode(W.using);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitReturning(W){this.append("returning "),this.compileList(W.selections)}visitAlias(W){this.visitNode(W.node),this.append(" as "),this.visitNode(W.alias)}visitReference(W){if(W.table)this.visitNode(W.table),this.append(".");this.visitNode(W.column)}visitSelectAll(W){this.append("*")}visitIdentifier(W){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(W),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(W){if(!a(W.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(W.name))}visitAnd(W){this.visitNode(W.left),this.append(" and "),this.visitNode(W.right)}visitOr(W){this.visitNode(W.left),this.append(" or "),this.visitNode(W.right)}visitValue(W){if(W.immediate)this.appendImmediateValue(W.value);else this.appendValue(W.value)}visitValueList(W){this.append("("),this.compileList(W.values),this.append(")")}visitTuple(W){this.append("("),this.compileList(W.values),this.append(")")}visitPrimitiveValueList(W){this.append("(");let{values:$}=W;for(let Z=0;Z<$.length;++Z)if(this.appendValue($[Z]),Z!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(KZ[W.joinType]),this.append(" "),this.visitNode(W.table),W.on)this.append(" "),this.visitNode(W.on)}visitOn(W){this.append("on "),this.visitNode(W.on)}visitRaw(W){let{sqlFragments:$,parameters:Z}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),Z.length>J)this.visitNode(Z[J])}visitOperator(W){this.append(W.operator)}visitTable(W){this.visitNode(W.table)}visitSchemableIdentifier(W){if(W.schema)this.visitNode(W.schema),this.append(".");this.visitNode(W.identifier)}visitCreateTable(W){if(this.append("create "),W.frontModifiers?.length)this.compileList(W.frontModifiers," "),this.append(" ");if(W.temporary)this.append("temporary ");if(this.append("table "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.table),!W.selectQuery)this.append(" ("),this.compileList([...W.columns,...W.constraints??[],...W.indexes??[]]),this.append(")");if(W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ");if(W.selectQuery)this.append(" as "),this.visitNode(W.selectQuery)}visitColumnDefinition(W){if(W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.column),this.append(" "),this.visitNode(W.dataType),W.unsigned)this.append(" unsigned");if(W.frontModifiers&&W.frontModifiers.length>0)this.append(" "),this.compileList(W.frontModifiers," ");if(W.generated)this.append(" "),this.visitNode(W.generated);if(W.identity)this.append(" identity");if(W.defaultTo)this.append(" "),this.visitNode(W.defaultTo);if(W.notNull)this.append(" not null");if(W.unique)this.append(" unique");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.primaryKey)this.append(" primary key");if(W.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(W.references)this.append(" "),this.visitNode(W.references);if(W.check)this.append(" "),this.visitNode(W.check);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(W){if(this.append("references "),this.visitNode(W.table),this.append(" ("),this.compileList(W.columns),this.append(")"),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate)}visitDropTable(W){if(this.append("drop "),W.temporary)this.append("temporary ");if(this.append("table "),W.ifExists)this.append("if exists ");if(this.visitNode(W.table),W.cascade)this.append(" cascade")}visitDataType(W){this.append(W.dataType)}visitOrderBy(W){this.append("order by "),this.compileList(W.items)}visitOrderByItem(W){if(this.visitNode(W.orderBy),W.collation)this.append(" "),this.visitNode(W.collation);if(W.direction)this.append(" "),this.visitNode(W.direction);if(W.nulls)this.append(" nulls "),this.append(W.nulls)}visitGroupBy(W){this.append("group by "),this.compileList(W.items)}visitGroupByItem(W){this.visitNode(W.groupBy)}visitUpdateQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("update "),W.top)this.visitNode(W.top),this.append(" ");if(W.table)this.visitNode(W.table),this.append(" ");if(this.append("set "),W.updates)this.compileList(W.updates);if(W.output)this.append(" "),this.visitNode(W.output);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins){if(!W.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(W.joins," ")}if(W.where)this.append(" "),this.visitNode(W.where);if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitColumnUpdate(W){this.visitNode(W.column),this.append(" = "),this.visitNode(W.value)}visitLimit(W){this.append("limit "),this.visitNode(W.limit)}visitOffset(W){this.append("offset "),this.visitNode(W.offset)}visitOnConflict(W){if(this.append("on conflict"),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");else if(W.constraint)this.append(" on constraint "),this.visitNode(W.constraint);else if(W.indexExpression)this.append(" ("),this.visitNode(W.indexExpression),this.append(")");if(W.indexWhere)this.append(" "),this.visitNode(W.indexWhere);if(W.doNothing===!0)this.append(" do nothing");else if(W.updates){if(this.append(" do update set "),this.compileList(W.updates),W.updateWhere)this.append(" "),this.visitNode(W.updateWhere)}}visitOnDuplicateKey(W){this.append("on duplicate key update "),this.compileList(W.updates)}visitCreateIndex(W){if(this.append("create "),W.unique)this.append("unique ");if(this.append("index "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.using)this.append(" using "),this.visitNode(W.using);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.where)this.append(" "),this.visitNode(W.where)}visitDropIndex(W){if(this.append("drop index "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.cascade)this.append(" cascade")}visitCreateSchema(W){if(this.append("create schema "),W.ifNotExists)this.append("if not exists ");this.visitNode(W.schema)}visitDropSchema(W){if(this.append("drop schema "),W.ifExists)this.append("if exists ");if(this.visitNode(W.schema),W.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("primary key ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}buildDeferrable(W){if(W.deferrable!==void 0)if(W.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(W.initiallyDeferred!==void 0)if(W.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("unique"),W.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}visitCheckConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("check ("),this.visitNode(W.expression),this.append(")")}visitForeignKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("foreign key ("),this.compileList(W.columns),this.append(") "),this.visitNode(W.references),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate);this.buildDeferrable(W)}visitList(W){this.compileList(W.items)}visitWith(W){if(this.append("with "),W.recursive)this.append("recursive ");this.compileList(W.expressions)}visitCommonTableExpression(W){if(this.visitNode(W.name),this.append(" as "),M8(W.materialized)){if(!W.materialized)this.append("not ");this.append("materialized ")}this.visitNode(W.expression)}visitCommonTableExpressionName(W){if(this.visitNode(W.table),W.columns)this.append("("),this.compileList(W.columns),this.append(")")}visitAlterTable(W){if(this.append("alter table "),this.visitNode(W.table),this.append(" "),W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema);if(W.addConstraint)this.visitNode(W.addConstraint);if(W.dropConstraint)this.visitNode(W.dropConstraint);if(W.renameConstraint)this.visitNode(W.renameConstraint);if(W.columnAlterations)this.compileColumnAlterations(W.columnAlterations);if(W.addIndex)this.visitNode(W.addIndex);if(W.dropIndex)this.visitNode(W.dropIndex)}visitAddColumn(W){this.append("add column "),this.visitNode(W.column)}visitRenameColumn(W){this.append("rename column "),this.visitNode(W.column),this.append(" to "),this.visitNode(W.renameTo)}visitDropColumn(W){if(this.append("drop column "),W.ifExists)this.append("if exists ");this.visitNode(W.column)}visitAlterColumn(W){if(this.append("alter column "),this.visitNode(W.column),this.append(" "),W.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(W.dataType),W.dataTypeExpression)this.append("using "),this.visitNode(W.dataTypeExpression)}if(W.setDefault)this.append("set default "),this.visitNode(W.setDefault);if(W.dropDefault)this.append("drop default");if(W.setNotNull)this.append("set not null");if(W.dropNotNull)this.append("drop not null")}visitModifyColumn(W){this.append("modify column "),this.visitNode(W.column)}visitAddConstraint(W){this.append("add "),this.visitNode(W.constraint)}visitDropConstraint(W){if(this.append("drop constraint "),W.ifExists)this.append("if exists ");if(this.visitNode(W.constraintName),W.modifier==="cascade")this.append(" cascade");else if(W.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(W){this.append("rename constraint "),this.visitNode(W.oldName),this.append(" to "),this.visitNode(W.newName)}visitSetOperation(W){if(this.append(W.operator),this.append(" "),W.all)this.append("all ");this.visitNode(W.expression)}visitCreateView(W){if(this.append("create "),W.orReplace)this.append("or replace ");if(W.materialized)this.append("materialized ");if(W.temporary)this.append("temporary ");if(this.append("view "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),this.append(" "),W.columns)this.append("("),this.compileList(W.columns),this.append(") ");if(W.as)this.append("as "),this.visitNode(W.as)}visitRefreshMaterializedView(W){if(this.append("refresh materialized view "),W.concurrently)this.append("concurrently ");if(this.visitNode(W.name),W.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(W){if(this.append("drop "),W.materialized)this.append("materialized ");if(this.append("view "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.cascade)this.append(" cascade")}visitGenerated(W){if(this.append("generated "),W.always)this.append("always ");if(W.byDefault)this.append("by default ");if(this.append("as "),W.identity)this.append("identity");if(W.expression)this.append("("),this.visitNode(W.expression),this.append(")");if(W.stored)this.append(" stored")}visitDefaultValue(W){this.append("default "),this.visitNode(W.defaultValue)}visitSelectModifier(W){if(W.rawModifier)this.visitNode(W.rawModifier);else this.append(LZ[W.modifier]);if(W.of)this.append(" of "),this.compileList(W.of,", ")}visitCreateType(W){if(this.append("create type "),this.visitNode(W.name),W.enum)this.append(" as enum "),this.visitNode(W.enum)}visitDropType(W){if(this.append("drop type "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.additionalNames?.length)this.append(", "),this.compileList(W.additionalNames);if(W.cascade)this.append(" cascade")}visitAlterType(W){if(this.append("alter type "),this.visitNode(W.name),this.append(" "),W.addValue)this.visitNode(W.addValue);else if(W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);else if(W.renameValue)this.visitNode(W.renameValue);else if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema)}visitAddValue(W){if(this.append("add value "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.value),W.neighborValue)this.append(W.isBefore?" before ":" after "),this.visitNode(W.neighborValue)}visitRenameValue(W){this.append("rename value "),this.visitNode(W.oldValue),this.append(" to "),this.visitNode(W.newValue)}visitExplain(W){if(this.append("explain"),W.options||W.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),W.options){if(this.visitNode(W.options),W.format)this.append(this.getExplainOptionsDelimiter())}if(W.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(W.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(W){this.append("default")}visitAggregateFunction(W){if(this.append(W.func),this.append("("),W.distinct)this.append("distinct ");if(this.compileList(W.aggregated),W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(this.append(")"),W.withinGroup)this.append(" within group ("),this.visitNode(W.withinGroup),this.append(")");if(W.filter)this.append(" filter("),this.visitNode(W.filter),this.append(")");if(W.over)this.append(" "),this.visitNode(W.over)}visitOver(W){if(this.append("over("),W.partitionBy){if(this.visitNode(W.partitionBy),W.orderBy)this.append(" ")}if(W.orderBy)this.visitNode(W.orderBy);this.append(")")}visitPartitionBy(W){this.append("partition by "),this.compileList(W.items)}visitPartitionByItem(W){this.visitNode(W.partitionBy)}visitBinaryOperation(W){this.visitNode(W.leftOperand),this.append(" "),this.visitNode(W.operator),this.append(" "),this.visitNode(W.rightOperand)}visitUnaryOperation(W){if(this.visitNode(W.operator),!this.isMinusOperator(W.operator))this.append(" ");this.visitNode(W.operand)}isMinusOperator(W){return r1.is(W)&&W.operator==="-"}visitUsing(W){this.append("using "),this.compileList(W.tables)}visitFunction(W){this.append(W.func),this.append("("),this.compileList(W.arguments),this.append(")")}visitCase(W){if(this.append("case"),W.value)this.append(" "),this.visitNode(W.value);if(W.when)this.append(" "),this.compileList(W.when," ");if(W.else)this.append(" else "),this.visitNode(W.else);if(this.append(" end"),W.isStatement)this.append(" case")}visitWhen(W){if(this.append("when "),this.visitNode(W.condition),W.result)this.append(" then "),this.visitNode(W.result)}visitJSONReference(W){this.visitNode(W.reference),this.visitNode(W.traversal)}visitJSONPath(W){if(W.inOperator)this.visitNode(W.inOperator);this.append("'$");for(let $ of W.pathLegs)this.visitNode($);this.append("'")}visitJSONPathLeg(W){let $=W.type==="ArrayLocation",Z=String(W.value);if($)this.append("["),this.append(this.sanitizeStringLiteral(Z)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(Z)),this.append('"')}visitJSONOperatorChain(W){for(let $=0,Z=W.values.length;$<Z;$++){if($===Z-1)this.visitNode(W.operator);else this.append("->");this.visitNode(W.values[$])}}visitMergeQuery(W){if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("merge "),W.top)this.visitNode(W.top),this.append(" ");if(this.append("into "),this.visitNode(W.into),W.using)this.append(" "),this.visitNode(W.using);if(W.whens)this.append(" "),this.compileList(W.whens," ");if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.output)this.append(" "),this.visitNode(W.output);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitMatched(W){if(W.not)this.append("not ");if(this.append("matched"),W.bySource)this.append(" by source")}visitAddIndex(W){if(!this.parentNode||!C1.is(this.parentNode))this.append("add ");if(W.unique)this.append("unique ");if(this.append("index "),this.visitNode(W.name),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.using)this.append(" using "),this.visitNode(W.using)}visitCast(W){this.append("cast("),this.visitNode(W.expression),this.append(" as "),this.visitNode(W.dataType),this.append(")")}visitFetch(W){this.append("fetch next "),this.visitNode(W.rowCount),this.append(` rows ${W.modifier}`)}visitOutput(W){this.append("output "),this.compileList(W.selections)}visitTop(W){if(this.append(`top(${W.expression})`),W.modifiers)this.append(` ${W.modifiers}`)}visitOrAction(W){this.append(W.action)}visitCollate(W){this.append("collate "),this.visitNode(W.collation)}append(W){this.#W+=W}appendValue(W){this.addParameter(W),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(W){let $=this.getLeftIdentifierWrapper(),Z=this.getRightIdentifierWrapper(),J="";for(let X of W)if(J+=X,X===$)J+=$;else if(X===Z)J+=Z;return J}sanitizeStringLiteral(W){return W.replace(kZ,"''")}sanitizeJSONPathMemberValue(W){return W.replace(GZ,($)=>$==="'"?"''":"\\\"")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(a(W))this.appendStringLiteral(W);else if(d0(W)||M8(W)||v8(W))this.append(W.toString());else if(T8(W))this.append("null");else if(a9(W))this.appendImmediateValue(W.toISOString());else throw Error(`invalid immediate value ${W}`)}appendStringLiteral(W){this.append("'"),this.append(this.sanitizeStringLiteral(W)),this.append("'")}sortSelectModifiers(W){return k(W.toSorted(($,Z)=>$.modifier&&Z.modifier?z7[$.modifier]-z7[Z.modifier]:1))}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var LZ=k({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),z7=k({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),KZ=k({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var gW=k({raw(W,$=[]){return k({sql:W,query:X1.createWithSql(W),parameters:k($),queryId:W1()})}});class W9{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class $9{transformQuery(W){return W.node}async transformResult(W){return W.result}}var J9="kysely_migration",N4="kysely_migration_lock",MZ=!1,Z9="migration_lock",PQ=k({__noMigrations__:!0});class X9{#W;constructor(W){this.#W=k(W)}async getMigrations(){let $=await this.#K(this.#X)?await this.#W.db.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#P()).map(({name:J,...X})=>{let Y=$.find((L)=>L.name===J);return{name:J,migration:X,executedAt:Y?new Date(Y.timestamp):void 0}})}async migrateToLatest(W){return this.#$(()=>({direction:"Up",step:1/0}),W)}async migrateTo(W,$){return this.#$(({migrations:Z,executedMigrations:J,pendingMigrations:X})=>{if(Q1(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!Z.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Y=J.indexOf(W),L=X.findIndex((G)=>G.name===W);if(Y!==-1)return{direction:"Down",step:J.length-Y-1};if(L!==-1)return{direction:"Up",step:L+1};throw Error(`migration "${W}" isn't executed or pending`)},$)}async migrateUp(W){return this.#$(()=>({direction:"Up",step:1}),W)}async migrateDown(W){return this.#$(()=>({direction:"Down",step:1}),W)}async#$(W,$){try{return await this.#H(),await this.#G(),await this.#M(),await this.#z(),await this.#F(W,$)}catch(Z){if(Z instanceof A4)return Z.resultSet;return{error:Z}}}get#Z(){return this.#W.migrationTableSchema}get#X(){return this.#W.migrationTableName??J9}get#Y(){return this.#W.migrationLockTableName??N4}get#k(){return this.#W.allowUnorderedMigrations??MZ}get#J(){if(this.#Z)return new V0(this.#Z);return new $9}async#H(){if(!this.#Z)return;if(await this.#L())return;try{await this.#U(this.#W.db.schema.createSchema(this.#Z))}catch($){if(!await this.#L())throw $}}async#G(){if(await this.#K(this.#X))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#X).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#K(this.#X))throw $}}async#M(){if(await this.#K(this.#Y))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#Y).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#K(this.#Y))throw $}}async#z(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#J).insertInto(this.#Y).values({id:Z9,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#L(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#Z)}async#K(W){let $=this.#Z;return(await this.#W.db.introspection.getTables({withInternalKyselyTables:!0})).some((J)=>J.name===W&&(!$||J.schema===$))}async#V(){return!!await this.#W.db.withPlugin(this.#J).selectFrom(this.#Y).where("id","=",Z9).select("id").executeTakeFirst()}async#F(W,$){let Z=this.#W.db.getExecutor().adapter,J=k({lockTable:this.#W.migrationLockTableName??N4,lockRowId:Z9,lockTableSchema:this.#W.migrationTableSchema}),X=async(L)=>{try{await Z.acquireMigrationLock(L,J);let G=await this.#D(L);if(G.migrations.length===0)return{results:[]};let{direction:U,step:D}=W(G);if(D<=0)return{results:[]};if(U==="Down")return await this.#_(L,G,D);else if(U==="Up")return await this.#E(L,G,D);return{results:[]}}finally{await Z.releaseMigrationLock(L,J)}},Y=$?.disableTransactions??this.#W.disableTransactions;if(this.#W.db.isTransaction){if(!Z.supportsTransactionalDdl)throw Error("Transactional DDL is not supported in this dialect. Passing a transaction to this migrator would result in failure or unexpected behavior.");if(Y)throw Error("`disableTransactions` is true but the migrator was given a transaction. Passing a transaction to this migrator would result in failure or unexpected behavior.");return X(this.#W.db)}if(Z.supportsTransactionalDdl&&!Y)return this.#W.db.transaction().execute(X);return this.#W.db.connection().execute(X)}async#D(W){let $=await this.#P(),Z=await this.#w(W);if(this.#Q($,Z),!this.#k)this.#S($,Z);let J=this.#R($,Z);return k({migrations:$,executedMigrations:Z,lastMigration:d9(Z),pendingMigrations:J})}#R(W,$){return W.filter((Z)=>{return!$.includes(Z.name)})}async#P(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#w(W){let $=await W.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute(),Z=this.#W.nameComparator||((J,X)=>J.localeCompare(X));return $.sort((J,X)=>{if(J.timestamp===X.timestamp)return Z(J.name,X.name);return new Date(J.timestamp).getTime()-new Date(X.timestamp).getTime()}).map((J)=>J.name)}#Q(W,$){for(let Z of $)if(!W.some((J)=>J.name===Z))throw Error(`corrupted migrations: previously executed migration ${Z} is missing`)}#S(W,$){for(let Z=0;Z<$.length;++Z)if(W[Z].name!==$[Z])throw Error(`corrupted migrations: expected previously executed migration ${$[Z]} to be at index ${Z} but ${W[Z].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#_(W,$,Z){let J=$.executedMigrations.toReversed().slice(0,Z).map((Y)=>{return $.migrations.find((L)=>L.name===Y)}),X=J.map((Y)=>{return{migrationName:Y.name,direction:"Down",status:"NotExecuted"}});for(let Y=0;Y<X.length;++Y){let L=J[Y];try{if(L.down)await L.down(W),await W.withPlugin(this.#J).deleteFrom(this.#X).where("name","=",L.name).execute(),X[Y]={migrationName:L.name,direction:"Down",status:"Success"}}catch(G){throw X[Y]={migrationName:L.name,direction:"Down",status:"Error"},new A4({error:G,results:X})}}return{results:X}}async#E(W,$,Z){let X=$.pendingMigrations.slice(0,Z).map((Y)=>{return{migrationName:Y.name,direction:"Up",status:"NotExecuted"}});for(let Y=0;Y<X.length;Y++){let L=$.pendingMigrations[Y];try{await L.up(W),await W.withPlugin(this.#J).insertInto(this.#X).values({name:L.name,timestamp:new Date().toISOString()}).execute(),X[Y]={migrationName:L.name,direction:"Up",status:"Success"}}catch(G){throw X[Y]={migrationName:L.name,direction:"Up",status:"Error"},new A4({error:G,results:X})}}return{results:X}}async#U(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class A4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}class mW{#W;constructor(W){this.#W=W}async getSchemas(){return(await this.#W.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(($)=>({name:$.nspname}))}async getTables(W={withInternalKyselyTables:!1}){let $=this.#W.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",k8`col_description(a.attrelid, a.attnum)`.as("column_description"),k8`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p","f"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k8`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!W.withInternalKyselyTables)$=$.where("c.relname","!=",J9).where("c.relname","!=",N4);let Z=await $.execute();return this.#$(Z)}#$(W){let $=[],Z=new Map;for(let J of W){let X=Z.get(J.schema);if(!X)X=new Map,Z.set(J.schema,X);let Y=X.get(J.table);if(!Y)Y=k({columns:[],isForeign:J.table_type==="f",isView:J.table_type==="v",name:J.table,schema:J.schema}),X.set(J.table,Y),$.push(Y);Y.columns.push(k({comment:J.column_description??void 0,dataType:J.type,dataTypeSchema:J.type_schema,hasDefaultValue:J.has_default,isAutoIncrementing:J.auto_incrementing!==null,isNullable:!J.not_null,name:J.column}))}return $}}var zZ=/"/g;class cW extends e6{sanitizeIdentifier(W){return W.replace(zZ,'""')}}var UZ=BigInt("3853314791062309107");class uW extends W9{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k8`select pg_advisory_xact_lock(${k8.lit(UZ)})`.execute(W)}async releaseMigrationLock(W,$){}}var{create:VZ,defineProperty:HW,getOwnPropertyDescriptor:PZ,getOwnPropertyNames:FZ,getPrototypeOf:DZ}=Object,RZ=Object.prototype.hasOwnProperty,wZ=(W,$,Z)=>($ in W)?HW(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,V=(W,$)=>HW(W,"name",{value:$,configurable:!0}),d1=(W,$)=>()=>(W&&($=W(W=0)),$),o=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),S0=(W,$)=>{for(var Z in $)HW(W,Z,{get:$[Z],enumerable:!0})},w7=(W,$,Z,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let X of FZ($))!RZ.call(W,X)&&X!==Z&&HW(W,X,{get:()=>$[X],enumerable:!(J=PZ($,X))||J.enumerable});return W},Q8=(W,$,Z)=>(Z=W!=null?VZ(DZ(W)):{},w7($||!W||!W.__esModule?HW(Z,"default",{value:W,enumerable:!0}):Z,W)),B1=(W)=>w7(HW({},"__esModule",{value:!0}),W),t=(W,$,Z)=>wZ(W,typeof $!="symbol"?$+"":$,Z),QZ=o((W)=>{u(),W.byteLength=U,W.toByteArray=P,W.fromByteArray=S;var $=[],Z=[],J=typeof Uint8Array<"u"?Uint8Array:Array,X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Y=0,L=X.length;Y<L;++Y)$[Y]=X[Y],Z[X.charCodeAt(Y)]=Y;var Y,L;Z[45]=62,Z[95]=63;function G(F){var K=F.length;if(K%4>0)throw Error("Invalid string. Length must be a multiple of 4");var Q=F.indexOf("=");Q===-1&&(Q=K);var _=Q===K?0:4-Q%4;return[Q,_]}V(G,"getLens");function U(F){var K=G(F),Q=K[0],_=K[1];return(Q+_)*3/4-_}V(U,"byteLength");function D(F,K,Q){return(K+Q)*3/4-Q}V(D,"_byteLength");function P(F){var K,Q=G(F),_=Q[0],E=Q[1],v=new J(D(F,_,E)),x=0,q=E>0?_-4:_,h;for(h=0;h<q;h+=4)K=Z[F.charCodeAt(h)]<<18|Z[F.charCodeAt(h+1)]<<12|Z[F.charCodeAt(h+2)]<<6|Z[F.charCodeAt(h+3)],v[x++]=K>>16&255,v[x++]=K>>8&255,v[x++]=K&255;return E===2&&(K=Z[F.charCodeAt(h)]<<2|Z[F.charCodeAt(h+1)]>>4,v[x++]=K&255),E===1&&(K=Z[F.charCodeAt(h)]<<10|Z[F.charCodeAt(h+1)]<<4|Z[F.charCodeAt(h+2)]>>2,v[x++]=K>>8&255,v[x++]=K&255),v}V(P,"toByteArray");function w(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}V(w,"tripletToBase64");function R(F,K,Q){for(var _,E=[],v=K;v<Q;v+=3)_=(F[v]<<16&16711680)+(F[v+1]<<8&65280)+(F[v+2]&255),E.push(w(_));return E.join("")}V(R,"encodeChunk");function S(F){for(var K,Q=F.length,_=Q%3,E=[],v=16383,x=0,q=Q-_;x<q;x+=v)E.push(R(F,x,x+v>q?q:x+v));return _===1?(K=F[Q-1],E.push($[K>>2]+$[K<<4&63]+"==")):_===2&&(K=(F[Q-2]<<8)+F[Q-1],E.push($[K>>10]+$[K>>4&63]+$[K<<2&63]+"=")),E.join("")}V(S,"fromByteArray")}),SZ=o((W)=>{u(),W.read=function($,Z,J,X,Y){var L,G,U=Y*8-X-1,D=(1<<U)-1,P=D>>1,w=-7,R=J?Y-1:0,S=J?-1:1,F=$[Z+R];for(R+=S,L=F&(1<<-w)-1,F>>=-w,w+=U;w>0;L=L*256+$[Z+R],R+=S,w-=8);for(G=L&(1<<-w)-1,L>>=-w,w+=X;w>0;G=G*256+$[Z+R],R+=S,w-=8);if(L===0)L=1-P;else{if(L===D)return G?NaN:(F?-1:1)*(1/0);G=G+Math.pow(2,X),L=L-P}return(F?-1:1)*G*Math.pow(2,L-X)},W.write=function($,Z,J,X,Y,L){var G,U,D,P=L*8-Y-1,w=(1<<P)-1,R=w>>1,S=Y===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=X?0:L-1,K=X?1:-1,Q=Z<0||Z===0&&1/Z<0?1:0;for(Z=Math.abs(Z),isNaN(Z)||Z===1/0?(U=isNaN(Z)?1:0,G=w):(G=Math.floor(Math.log(Z)/Math.LN2),Z*(D=Math.pow(2,-G))<1&&(G--,D*=2),G+R>=1?Z+=S/D:Z+=S*Math.pow(2,1-R),Z*D>=2&&(G++,D/=2),G+R>=w?(U=0,G=w):G+R>=1?(U=(Z*D-1)*Math.pow(2,Y),G=G+R):(U=Z*Math.pow(2,R-1)*Math.pow(2,Y),G=0));Y>=8;$[J+F]=U&255,F+=K,U/=256,Y-=8);for(G=G<<Y|U,P+=Y;P>0;$[J+F]=G&255,F+=K,G/=256,P-=8);$[J+F-K]|=Q*128}}),_Z=o((W)=>{u();var $=QZ(),Z=SZ(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=G,W.SlowBuffer=E,W.INSPECT_MAX_BYTES=50;var X=2147483647;W.kMaxLength=X,G.TYPED_ARRAY_SUPPORT=Y(),!G.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Y(){try{let H=new Uint8Array(1),M={foo:V(function(){return 42},"foo")};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(H,M),H.foo()===42}catch{return!1}}V(Y,"typedArraySupport"),Object.defineProperty(G.prototype,"parent",{enumerable:!0,get:V(function(){if(G.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(G.prototype,"offset",{enumerable:!0,get:V(function(){if(G.isBuffer(this))return this.byteOffset},"get")});function L(H){if(H>X)throw RangeError('The value "'+H+'" is invalid for option "size"');let M=new Uint8Array(H);return Object.setPrototypeOf(M,G.prototype),M}V(L,"createBuffer");function G(H,M,z){if(typeof H=="number"){if(typeof M=="string")throw TypeError('The "string" argument must be of type string. Received type number');return w(H)}return U(H,M,z)}V(G,"Buffer"),G.poolSize=8192;function U(H,M,z){if(typeof H=="string")return R(H,M);if(ArrayBuffer.isView(H))return F(H);if(H==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H);if(Y0(H,ArrayBuffer)||H&&Y0(H.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Y0(H,SharedArrayBuffer)||H&&Y0(H.buffer,SharedArrayBuffer)))return K(H,M,z);if(typeof H=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let T=H.valueOf&&H.valueOf();if(T!=null&&T!==H)return G.from(T,M,z);let j=Q(H);if(j)return j;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof H[Symbol.toPrimitive]=="function")return G.from(H[Symbol.toPrimitive]("string"),M,z);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H)}V(U,"from"),G.from=function(H,M,z){return U(H,M,z)},Object.setPrototypeOf(G.prototype,Uint8Array.prototype),Object.setPrototypeOf(G,Uint8Array);function D(H){if(typeof H!="number")throw TypeError('"size" argument must be of type number');if(H<0)throw RangeError('The value "'+H+'" is invalid for option "size"')}V(D,"assertSize");function P(H,M,z){return D(H),H<=0?L(H):M!==void 0?typeof z=="string"?L(H).fill(M,z):L(H).fill(M):L(H)}V(P,"alloc"),G.alloc=function(H,M,z){return P(H,M,z)};function w(H){return D(H),L(H<0?0:_(H)|0)}V(w,"allocUnsafe"),G.allocUnsafe=function(H){return w(H)},G.allocUnsafeSlow=function(H){return w(H)};function R(H,M){if((typeof M!="string"||M==="")&&(M="utf8"),!G.isEncoding(M))throw TypeError("Unknown encoding: "+M);let z=v(H,M)|0,T=L(z),j=T.write(H,M);return j!==z&&(T=T.slice(0,j)),T}V(R,"fromString");function S(H){let M=H.length<0?0:_(H.length)|0,z=L(M);for(let T=0;T<M;T+=1)z[T]=H[T]&255;return z}V(S,"fromArrayLike");function F(H){if(Y0(H,Uint8Array)){let M=new Uint8Array(H);return K(M.buffer,M.byteOffset,M.byteLength)}return S(H)}V(F,"fromArrayView");function K(H,M,z){if(M<0||H.byteLength<M)throw RangeError('"offset" is outside of buffer bounds');if(H.byteLength<M+(z||0))throw RangeError('"length" is outside of buffer bounds');let T;return M===void 0&&z===void 0?T=new Uint8Array(H):z===void 0?T=new Uint8Array(H,M):T=new Uint8Array(H,M,z),Object.setPrototypeOf(T,G.prototype),T}V(K,"fromArrayBuffer");function Q(H){if(G.isBuffer(H)){let M=_(H.length)|0,z=L(M);return z.length===0||H.copy(z,0,0,M),z}if(H.length!==void 0)return typeof H.length!="number"||oW(H.length)?L(0):S(H);if(H.type==="Buffer"&&Array.isArray(H.data))return S(H.data)}V(Q,"fromObject");function _(H){if(H>=X)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+X.toString(16)+" bytes");return H|0}V(_,"checked");function E(H){return+H!=H&&(H=0),G.alloc(+H)}V(E,"SlowBuffer"),G.isBuffer=V(function(H){return H!=null&&H._isBuffer===!0&&H!==G.prototype},"isBuffer"),G.compare=V(function(H,M){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),Y0(M,Uint8Array)&&(M=G.from(M,M.offset,M.byteLength)),!G.isBuffer(H)||!G.isBuffer(M))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(H===M)return 0;let z=H.length,T=M.length;for(let j=0,O=Math.min(z,T);j<O;++j)if(H[j]!==M[j]){z=H[j],T=M[j];break}return z<T?-1:T<z?1:0},"compare"),G.isEncoding=V(function(H){switch(String(H).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},"isEncoding"),G.concat=V(function(H,M){if(!Array.isArray(H))throw TypeError('"list" argument must be an Array of Buffers');if(H.length===0)return G.alloc(0);let z;if(M===void 0)for(M=0,z=0;z<H.length;++z)M+=H[z].length;let T=G.allocUnsafe(M),j=0;for(z=0;z<H.length;++z){let O=H[z];if(Y0(O,Uint8Array))j+O.length>T.length?(G.isBuffer(O)||(O=G.from(O)),O.copy(T,j)):Uint8Array.prototype.set.call(T,O,j);else if(G.isBuffer(O))O.copy(T,j);else throw TypeError('"list" argument must be an Array of Buffers');j+=O.length}return T},"concat");function v(H,M){if(G.isBuffer(H))return H.length;if(ArrayBuffer.isView(H)||Y0(H,ArrayBuffer))return H.byteLength;if(typeof H!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof H);let z=H.length,T=arguments.length>2&&arguments[2]===!0;if(!T&&z===0)return 0;let j=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return z;case"utf8":case"utf-8":return rW(H).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z*2;case"hex":return z>>>1;case"base64":return o4(H).length;default:if(j)return T?-1:rW(H).length;M=(""+M).toLowerCase(),j=!0}}V(v,"byteLength"),G.byteLength=v;function x(H,M,z){let T=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((z===void 0||z>this.length)&&(z=this.length),z<=0)||(z>>>=0,M>>>=0,z<=M))return"";for(H||(H="utf8");;)switch(H){case"hex":return s(this,M,z);case"utf8":case"utf-8":return b(this,M,z);case"ascii":return d(this,M,z);case"latin1":case"binary":return J1(this,M,z);case"base64":return m(this,M,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s1(this,M,z);default:if(T)throw TypeError("Unknown encoding: "+H);H=(H+"").toLowerCase(),T=!0}}V(x,"slowToString"),G.prototype._isBuffer=!0;function q(H,M,z){let T=H[M];H[M]=H[z],H[z]=T}V(q,"swap"),G.prototype.swap16=V(function(){let H=this.length;if(H%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<H;M+=2)q(this,M,M+1);return this},"swap16"),G.prototype.swap32=V(function(){let H=this.length;if(H%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<H;M+=4)q(this,M,M+3),q(this,M+1,M+2);return this},"swap32"),G.prototype.swap64=V(function(){let H=this.length;if(H%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<H;M+=8)q(this,M,M+7),q(this,M+1,M+6),q(this,M+2,M+5),q(this,M+3,M+4);return this},"swap64"),G.prototype.toString=V(function(){let H=this.length;return H===0?"":arguments.length===0?b(this,0,H):x.apply(this,arguments)},"toString"),G.prototype.toLocaleString=G.prototype.toString,G.prototype.equals=V(function(H){if(!G.isBuffer(H))throw TypeError("Argument must be a Buffer");return this===H?!0:G.compare(this,H)===0},"equals"),G.prototype.inspect=V(function(){let H="",M=W.INSPECT_MAX_BYTES;return H=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(H+=" ... "),"<Buffer "+H+">"},"inspect"),J&&(G.prototype[J]=G.prototype.inspect),G.prototype.compare=V(function(H,M,z,T,j){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),!G.isBuffer(H))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof H);if(M===void 0&&(M=0),z===void 0&&(z=H?H.length:0),T===void 0&&(T=0),j===void 0&&(j=this.length),M<0||z>H.length||T<0||j>this.length)throw RangeError("out of range index");if(T>=j&&M>=z)return 0;if(T>=j)return-1;if(M>=z)return 1;if(M>>>=0,z>>>=0,T>>>=0,j>>>=0,this===H)return 0;let O=j-T,I=z-M,P1=Math.min(O,I),A1=this.slice(T,j),w1=H.slice(M,z);for(let F1=0;F1<P1;++F1)if(A1[F1]!==w1[F1]){O=A1[F1],I=w1[F1];break}return O<I?-1:I<O?1:0},"compare");function h(H,M,z,T,j){if(H.length===0)return-1;if(typeof z=="string"?(T=z,z=0):z>2147483647?z=2147483647:z<-2147483648&&(z=-2147483648),z=+z,oW(z)&&(z=j?0:H.length-1),z<0&&(z=H.length+z),z>=H.length){if(j)return-1;z=H.length-1}else if(z<0)if(j)z=0;else return-1;if(typeof M=="string"&&(M=G.from(M,T)),G.isBuffer(M))return M.length===0?-1:N(H,M,z,T,j);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?j?Uint8Array.prototype.indexOf.call(H,M,z):Uint8Array.prototype.lastIndexOf.call(H,M,z):N(H,[M],z,T,j);throw TypeError("val must be string, number or Buffer")}V(h,"bidirectionalIndexOf");function N(H,M,z,T,j){let O=1,I=H.length,P1=M.length;if(T!==void 0&&(T=String(T).toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(H.length<2||M.length<2)return-1;O=2,I/=2,P1/=2,z/=2}function A1(F1,T1){return O===1?F1[T1]:F1.readUInt16BE(T1*O)}V(A1,"read");let w1;if(j){let F1=-1;for(w1=z;w1<I;w1++)if(A1(H,w1)===A1(M,F1===-1?0:w1-F1)){if(F1===-1&&(F1=w1),w1-F1+1===P1)return F1*O}else F1!==-1&&(w1-=w1-F1),F1=-1}else for(z+P1>I&&(z=I-P1),w1=z;w1>=0;w1--){let F1=!0;for(let T1=0;T1<P1;T1++)if(A1(H,w1+T1)!==A1(M,T1)){F1=!1;break}if(F1)return w1}return-1}V(N,"arrayIndexOf"),G.prototype.includes=V(function(H,M,z){return this.indexOf(H,M,z)!==-1},"includes"),G.prototype.indexOf=V(function(H,M,z){return h(this,H,M,z,!0)},"indexOf"),G.prototype.lastIndexOf=V(function(H,M,z){return h(this,H,M,z,!1)},"lastIndexOf");function A(H,M,z,T){z=Number(z)||0;let j=H.length-z;T?(T=Number(T),T>j&&(T=j)):T=j;let O=M.length;T>O/2&&(T=O/2);let I;for(I=0;I<T;++I){let P1=parseInt(M.substr(I*2,2),16);if(oW(P1))return I;H[z+I]=P1}return I}V(A,"hexWrite");function f(H,M,z,T){return LW(rW(M,H.length-z),H,z,T)}V(f,"utf8Write");function B(H,M,z,T){return LW(T9(M),H,z,T)}V(B,"asciiWrite");function C(H,M,z,T){return LW(o4(M),H,z,T)}V(C,"base64Write");function c(H,M,z,T){return LW(v9(M,H.length-z),H,z,T)}V(c,"ucs2Write"),G.prototype.write=V(function(H,M,z,T){if(M===void 0)T="utf8",z=this.length,M=0;else if(z===void 0&&typeof M=="string")T=M,z=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(z)?(z=z>>>0,T===void 0&&(T="utf8")):(T=z,z=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let j=this.length-M;if((z===void 0||z>j)&&(z=j),H.length>0&&(z<0||M<0)||M>this.length)throw RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let O=!1;for(;;)switch(T){case"hex":return A(this,H,M,z);case"utf8":case"utf-8":return f(this,H,M,z);case"ascii":case"latin1":case"binary":return B(this,H,M,z);case"base64":return C(this,H,M,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return c(this,H,M,z);default:if(O)throw TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),O=!0}},"write"),G.prototype.toJSON=V(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function m(H,M,z){return M===0&&z===H.length?$.fromByteArray(H):$.fromByteArray(H.slice(M,z))}V(m,"base64Slice");function b(H,M,z){z=Math.min(H.length,z);let T=[],j=M;for(;j<z;){let O=H[j],I=null,P1=O>239?4:O>223?3:O>191?2:1;if(j+P1<=z){let A1,w1,F1,T1;switch(P1){case 1:O<128&&(I=O);break;case 2:A1=H[j+1],(A1&192)===128&&(T1=(O&31)<<6|A1&63,T1>127&&(I=T1));break;case 3:A1=H[j+1],w1=H[j+2],(A1&192)===128&&(w1&192)===128&&(T1=(O&15)<<12|(A1&63)<<6|w1&63,T1>2047&&(T1<55296||T1>57343)&&(I=T1));break;case 4:A1=H[j+1],w1=H[j+2],F1=H[j+3],(A1&192)===128&&(w1&192)===128&&(F1&192)===128&&(T1=(O&15)<<18|(A1&63)<<12|(w1&63)<<6|F1&63,T1>65535&&T1<1114112&&(I=T1))}}I===null?(I=65533,P1=1):I>65535&&(I-=65536,T.push(I>>>10&1023|55296),I=56320|I&1023),T.push(I),j+=P1}return p(T)}V(b,"utf8Slice");var g=4096;function p(H){let M=H.length;if(M<=g)return String.fromCharCode.apply(String,H);let z="",T=0;for(;T<M;)z+=String.fromCharCode.apply(String,H.slice(T,T+=g));return z}V(p,"decodeCodePointsArray");function d(H,M,z){let T="";z=Math.min(H.length,z);for(let j=M;j<z;++j)T+=String.fromCharCode(H[j]&127);return T}V(d,"asciiSlice");function J1(H,M,z){let T="";z=Math.min(H.length,z);for(let j=M;j<z;++j)T+=String.fromCharCode(H[j]);return T}V(J1,"latin1Slice");function s(H,M,z){let T=H.length;(!M||M<0)&&(M=0),(!z||z<0||z>T)&&(z=T);let j="";for(let O=M;O<z;++O)j+=A$[H[O]];return j}V(s,"hexSlice");function s1(H,M,z){let T=H.slice(M,z),j="";for(let O=0;O<T.length-1;O+=2)j+=String.fromCharCode(T[O]+T[O+1]*256);return j}V(s1,"utf16leSlice"),G.prototype.slice=V(function(H,M){let z=this.length;H=~~H,M=M===void 0?z:~~M,H<0?(H+=z,H<0&&(H=0)):H>z&&(H=z),M<0?(M+=z,M<0&&(M=0)):M>z&&(M=z),M<H&&(M=H);let T=this.subarray(H,M);return Object.setPrototypeOf(T,G.prototype),T},"slice");function V1(H,M,z){if(H%1!==0||H<0)throw RangeError("offset is not uint");if(H+M>z)throw RangeError("Trying to access beyond buffer length")}V(V1,"checkOffset"),G.prototype.readUintLE=G.prototype.readUIntLE=V(function(H,M,z){H=H>>>0,M=M>>>0,z||V1(H,M,this.length);let T=this[H],j=1,O=0;for(;++O<M&&(j*=256);)T+=this[H+O]*j;return T},"readUIntLE"),G.prototype.readUintBE=G.prototype.readUIntBE=V(function(H,M,z){H=H>>>0,M=M>>>0,z||V1(H,M,this.length);let T=this[H+--M],j=1;for(;M>0&&(j*=256);)T+=this[H+--M]*j;return T},"readUIntBE"),G.prototype.readUint8=G.prototype.readUInt8=V(function(H,M){return H=H>>>0,M||V1(H,1,this.length),this[H]},"readUInt8"),G.prototype.readUint16LE=G.prototype.readUInt16LE=V(function(H,M){return H=H>>>0,M||V1(H,2,this.length),this[H]|this[H+1]<<8},"readUInt16LE"),G.prototype.readUint16BE=G.prototype.readUInt16BE=V(function(H,M){return H=H>>>0,M||V1(H,2,this.length),this[H]<<8|this[H+1]},"readUInt16BE"),G.prototype.readUint32LE=G.prototype.readUInt32LE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),(this[H]|this[H+1]<<8|this[H+2]<<16)+this[H+3]*16777216},"readUInt32LE"),G.prototype.readUint32BE=G.prototype.readUInt32BE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),this[H]*16777216+(this[H+1]<<16|this[H+2]<<8|this[H+3])},"readUInt32BE"),G.prototype.readBigUInt64LE=O0(V(function(H){H=H>>>0,L8(H,"offset");let M=this[H],z=this[H+7];(M===void 0||z===void 0)&&h8(H,this.length-8);let T=M+this[++H]*256+this[++H]*65536+this[++H]*16777216,j=this[++H]+this[++H]*256+this[++H]*65536+z*16777216;return BigInt(T)+(BigInt(j)<<BigInt(32))},"readBigUInt64LE")),G.prototype.readBigUInt64BE=O0(V(function(H){H=H>>>0,L8(H,"offset");let M=this[H],z=this[H+7];(M===void 0||z===void 0)&&h8(H,this.length-8);let T=M*16777216+this[++H]*65536+this[++H]*256+this[++H],j=this[++H]*16777216+this[++H]*65536+this[++H]*256+z;return(BigInt(T)<<BigInt(32))+BigInt(j)},"readBigUInt64BE")),G.prototype.readIntLE=V(function(H,M,z){H=H>>>0,M=M>>>0,z||V1(H,M,this.length);let T=this[H],j=1,O=0;for(;++O<M&&(j*=256);)T+=this[H+O]*j;return j*=128,T>=j&&(T-=Math.pow(2,8*M)),T},"readIntLE"),G.prototype.readIntBE=V(function(H,M,z){H=H>>>0,M=M>>>0,z||V1(H,M,this.length);let T=M,j=1,O=this[H+--T];for(;T>0&&(j*=256);)O+=this[H+--T]*j;return j*=128,O>=j&&(O-=Math.pow(2,8*M)),O},"readIntBE"),G.prototype.readInt8=V(function(H,M){return H=H>>>0,M||V1(H,1,this.length),this[H]&128?(255-this[H]+1)*-1:this[H]},"readInt8"),G.prototype.readInt16LE=V(function(H,M){H=H>>>0,M||V1(H,2,this.length);let z=this[H]|this[H+1]<<8;return z&32768?z|4294901760:z},"readInt16LE"),G.prototype.readInt16BE=V(function(H,M){H=H>>>0,M||V1(H,2,this.length);let z=this[H+1]|this[H]<<8;return z&32768?z|4294901760:z},"readInt16BE"),G.prototype.readInt32LE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),this[H]|this[H+1]<<8|this[H+2]<<16|this[H+3]<<24},"readInt32LE"),G.prototype.readInt32BE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),this[H]<<24|this[H+1]<<16|this[H+2]<<8|this[H+3]},"readInt32BE"),G.prototype.readBigInt64LE=O0(V(function(H){H=H>>>0,L8(H,"offset");let M=this[H],z=this[H+7];(M===void 0||z===void 0)&&h8(H,this.length-8);let T=this[H+4]+this[H+5]*256+this[H+6]*65536+(z<<24);return(BigInt(T)<<BigInt(32))+BigInt(M+this[++H]*256+this[++H]*65536+this[++H]*16777216)},"readBigInt64LE")),G.prototype.readBigInt64BE=O0(V(function(H){H=H>>>0,L8(H,"offset");let M=this[H],z=this[H+7];(M===void 0||z===void 0)&&h8(H,this.length-8);let T=(M<<24)+this[++H]*65536+this[++H]*256+this[++H];return(BigInt(T)<<BigInt(32))+BigInt(this[++H]*16777216+this[++H]*65536+this[++H]*256+z)},"readBigInt64BE")),G.prototype.readFloatLE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),Z.read(this,H,!0,23,4)},"readFloatLE"),G.prototype.readFloatBE=V(function(H,M){return H=H>>>0,M||V1(H,4,this.length),Z.read(this,H,!1,23,4)},"readFloatBE"),G.prototype.readDoubleLE=V(function(H,M){return H=H>>>0,M||V1(H,8,this.length),Z.read(this,H,!0,52,8)},"readDoubleLE"),G.prototype.readDoubleBE=V(function(H,M){return H=H>>>0,M||V1(H,8,this.length),Z.read(this,H,!1,52,8)},"readDoubleBE");function f1(H,M,z,T,j,O){if(!G.isBuffer(H))throw TypeError('"buffer" argument must be a Buffer instance');if(M>j||M<O)throw RangeError('"value" argument is out of bounds');if(z+T>H.length)throw RangeError("Index out of range")}V(f1,"checkInt"),G.prototype.writeUintLE=G.prototype.writeUIntLE=V(function(H,M,z,T){if(H=+H,M=M>>>0,z=z>>>0,!T){let I=Math.pow(2,8*z)-1;f1(this,H,M,z,I,0)}let j=1,O=0;for(this[M]=H&255;++O<z&&(j*=256);)this[M+O]=H/j&255;return M+z},"writeUIntLE"),G.prototype.writeUintBE=G.prototype.writeUIntBE=V(function(H,M,z,T){if(H=+H,M=M>>>0,z=z>>>0,!T){let I=Math.pow(2,8*z)-1;f1(this,H,M,z,I,0)}let j=z-1,O=1;for(this[M+j]=H&255;--j>=0&&(O*=256);)this[M+j]=H/O&255;return M+z},"writeUIntBE"),G.prototype.writeUint8=G.prototype.writeUInt8=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,1,255,0),this[M]=H&255,M+1},"writeUInt8"),G.prototype.writeUint16LE=G.prototype.writeUInt16LE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,2,65535,0),this[M]=H&255,this[M+1]=H>>>8,M+2},"writeUInt16LE"),G.prototype.writeUint16BE=G.prototype.writeUInt16BE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,2,65535,0),this[M]=H>>>8,this[M+1]=H&255,M+2},"writeUInt16BE"),G.prototype.writeUint32LE=G.prototype.writeUInt32LE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,4,4294967295,0),this[M+3]=H>>>24,this[M+2]=H>>>16,this[M+1]=H>>>8,this[M]=H&255,M+4},"writeUInt32LE"),G.prototype.writeUint32BE=G.prototype.writeUInt32BE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,4,4294967295,0),this[M]=H>>>24,this[M+1]=H>>>16,this[M+2]=H>>>8,this[M+3]=H&255,M+4},"writeUInt32BE");function kW(H,M,z,T,j){r4(M,T,j,H,z,7);let O=Number(M&BigInt(4294967295));H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O;let I=Number(M>>BigInt(32)&BigInt(4294967295));return H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,z}V(kW,"wrtBigUInt64LE");function GW(H,M,z,T,j){r4(M,T,j,H,z,7);let O=Number(M&BigInt(4294967295));H[z+7]=O,O=O>>8,H[z+6]=O,O=O>>8,H[z+5]=O,O=O>>8,H[z+4]=O;let I=Number(M>>BigInt(32)&BigInt(4294967295));return H[z+3]=I,I=I>>8,H[z+2]=I,I=I>>8,H[z+1]=I,I=I>>8,H[z]=I,z+8}V(GW,"wrtBigUInt64BE"),G.prototype.writeBigUInt64LE=O0(V(function(H,M=0){return kW(this,H,M,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),G.prototype.writeBigUInt64BE=O0(V(function(H,M=0){return GW(this,H,M,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),G.prototype.writeIntLE=V(function(H,M,z,T){if(H=+H,M=M>>>0,!T){let P1=Math.pow(2,8*z-1);f1(this,H,M,z,P1-1,-P1)}let j=0,O=1,I=0;for(this[M]=H&255;++j<z&&(O*=256);)H<0&&I===0&&this[M+j-1]!==0&&(I=1),this[M+j]=(H/O>>0)-I&255;return M+z},"writeIntLE"),G.prototype.writeIntBE=V(function(H,M,z,T){if(H=+H,M=M>>>0,!T){let P1=Math.pow(2,8*z-1);f1(this,H,M,z,P1-1,-P1)}let j=z-1,O=1,I=0;for(this[M+j]=H&255;--j>=0&&(O*=256);)H<0&&I===0&&this[M+j+1]!==0&&(I=1),this[M+j]=(H/O>>0)-I&255;return M+z},"writeIntBE"),G.prototype.writeInt8=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,1,127,-128),H<0&&(H=255+H+1),this[M]=H&255,M+1},"writeInt8"),G.prototype.writeInt16LE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,2,32767,-32768),this[M]=H&255,this[M+1]=H>>>8,M+2},"writeInt16LE"),G.prototype.writeInt16BE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,2,32767,-32768),this[M]=H>>>8,this[M+1]=H&255,M+2},"writeInt16BE"),G.prototype.writeInt32LE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,4,2147483647,-2147483648),this[M]=H&255,this[M+1]=H>>>8,this[M+2]=H>>>16,this[M+3]=H>>>24,M+4},"writeInt32LE"),G.prototype.writeInt32BE=V(function(H,M,z){return H=+H,M=M>>>0,z||f1(this,H,M,4,2147483647,-2147483648),H<0&&(H=4294967295+H+1),this[M]=H>>>24,this[M+1]=H>>>16,this[M+2]=H>>>8,this[M+3]=H&255,M+4},"writeInt32BE"),G.prototype.writeBigInt64LE=O0(V(function(H,M=0){return kW(this,H,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),G.prototype.writeBigInt64BE=O0(V(function(H,M=0){return GW(this,H,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function a4(H,M,z,T,j,O){if(z+T>H.length)throw RangeError("Index out of range");if(z<0)throw RangeError("Index out of range")}V(a4,"checkIEEE754");function d4(H,M,z,T,j){return M=+M,z=z>>>0,j||a4(H,M,z,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),Z.write(H,M,z,T,23,4),z+4}V(d4,"writeFloat"),G.prototype.writeFloatLE=V(function(H,M,z){return d4(this,H,M,!0,z)},"writeFloatLE"),G.prototype.writeFloatBE=V(function(H,M,z){return d4(this,H,M,!1,z)},"writeFloatBE");function s4(H,M,z,T,j){return M=+M,z=z>>>0,j||a4(H,M,z,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),Z.write(H,M,z,T,52,8),z+8}V(s4,"writeDouble"),G.prototype.writeDoubleLE=V(function(H,M,z){return s4(this,H,M,!0,z)},"writeDoubleLE"),G.prototype.writeDoubleBE=V(function(H,M,z){return s4(this,H,M,!1,z)},"writeDoubleBE"),G.prototype.copy=V(function(H,M,z,T){if(!G.isBuffer(H))throw TypeError("argument should be a Buffer");if(z||(z=0),!T&&T!==0&&(T=this.length),M>=H.length&&(M=H.length),M||(M=0),T>0&&T<z&&(T=z),T===z||H.length===0||this.length===0)return 0;if(M<0)throw RangeError("targetStart out of bounds");if(z<0||z>=this.length)throw RangeError("Index out of range");if(T<0)throw RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),H.length-M<T-z&&(T=H.length-M+z);let j=T-z;return this===H&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,z,T):Uint8Array.prototype.set.call(H,this.subarray(z,T),M),j},"copy"),G.prototype.fill=V(function(H,M,z,T){if(typeof H=="string"){if(typeof M=="string"?(T=M,M=0,z=this.length):typeof z=="string"&&(T=z,z=this.length),T!==void 0&&typeof T!="string")throw TypeError("encoding must be a string");if(typeof T=="string"&&!G.isEncoding(T))throw TypeError("Unknown encoding: "+T);if(H.length===1){let O=H.charCodeAt(0);(T==="utf8"&&O<128||T==="latin1")&&(H=O)}}else typeof H=="number"?H=H&255:typeof H=="boolean"&&(H=Number(H));if(M<0||this.length<M||this.length<z)throw RangeError("Out of range index");if(z<=M)return this;M=M>>>0,z=z===void 0?this.length:z>>>0,H||(H=0);let j;if(typeof H=="number")for(j=M;j<z;++j)this[j]=H;else{let O=G.isBuffer(H)?H:G.from(H,T),I=O.length;if(I===0)throw TypeError('The value "'+H+'" is invalid for argument "value"');for(j=0;j<z-M;++j)this[j+M]=O[j%I]}return this},"fill");var E8={};function nW(H,M,z){var T;E8[H]=(T=class extends z{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${H}]`,this.stack,delete this.name}get code(){return H}set code(j){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:j,writable:!0})}toString(){return`${this.name} [${H}]: ${this.message}`}},V(T,"NodeError"),T)}V(nW,"E"),nW("ERR_BUFFER_OUT_OF_BOUNDS",function(H){return H?`${H} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),nW("ERR_INVALID_ARG_TYPE",function(H,M){return`The "${H}" argument must be of type number. Received type ${typeof M}`},TypeError),nW("ERR_OUT_OF_RANGE",function(H,M,z){let T=`The value of "${H}" is out of range.`,j=z;return Number.isInteger(z)&&Math.abs(z)>4294967296?j=n4(String(z)):typeof z=="bigint"&&(j=String(z),(z>BigInt(2)**BigInt(32)||z<-(BigInt(2)**BigInt(32)))&&(j=n4(j)),j+="n"),T+=` It must be ${M}. Received ${j}`,T},RangeError);function n4(H){let M="",z=H.length,T=H[0]==="-"?1:0;for(;z>=T+4;z-=3)M=`_${H.slice(z-3,z)}${M}`;return`${H.slice(0,z)}${M}`}V(n4,"addNumericalSeparator");function E9(H,M,z){L8(M,"offset"),(H[M]===void 0||H[M+z]===void 0)&&h8(M,H.length-(z+1))}V(E9,"checkBounds");function r4(H,M,z,T,j,O){if(H>z||H<M){let I=typeof M=="bigint"?"n":"",P1;throw O>3?M===0||M===BigInt(0)?P1=`>= 0${I} and < 2${I} ** ${(O+1)*8}${I}`:P1=`>= -(2${I} ** ${(O+1)*8-1}${I}) and < 2 ** ${(O+1)*8-1}${I}`:P1=`>= ${M}${I} and <= ${z}${I}`,new E8.ERR_OUT_OF_RANGE("value",P1,H)}E9(T,j,O)}V(r4,"checkIntBI");function L8(H,M){if(typeof H!="number")throw new E8.ERR_INVALID_ARG_TYPE(M,"number",H)}V(L8,"validateNumber");function h8(H,M,z){throw Math.floor(H)!==H?(L8(H,z),new E8.ERR_OUT_OF_RANGE(z||"offset","an integer",H)):M<0?new E8.ERR_BUFFER_OUT_OF_BOUNDS:new E8.ERR_OUT_OF_RANGE(z||"offset",`>= ${z?1:0} and <= ${M}`,H)}V(h8,"boundsError");var j$=/[^+/0-9A-Za-z-_]/g;function h9(H){if(H=H.split("=")[0],H=H.trim().replace(j$,""),H.length<2)return"";for(;H.length%4!==0;)H=H+"=";return H}V(h9,"base64clean");function rW(H,M){M=M||1/0;let z,T=H.length,j=null,O=[];for(let I=0;I<T;++I){if(z=H.charCodeAt(I),z>55295&&z<57344){if(!j){if(z>56319){(M-=3)>-1&&O.push(239,191,189);continue}else if(I+1===T){(M-=3)>-1&&O.push(239,191,189);continue}j=z;continue}if(z<56320){(M-=3)>-1&&O.push(239,191,189),j=z;continue}z=(j-55296<<10|z-56320)+65536}else j&&(M-=3)>-1&&O.push(239,191,189);if(j=null,z<128){if((M-=1)<0)break;O.push(z)}else if(z<2048){if((M-=2)<0)break;O.push(z>>6|192,z&63|128)}else if(z<65536){if((M-=3)<0)break;O.push(z>>12|224,z>>6&63|128,z&63|128)}else if(z<1114112){if((M-=4)<0)break;O.push(z>>18|240,z>>12&63|128,z>>6&63|128,z&63|128)}else throw Error("Invalid code point")}return O}V(rW,"utf8ToBytes");function T9(H){let M=[];for(let z=0;z<H.length;++z)M.push(H.charCodeAt(z)&255);return M}V(T9,"asciiToBytes");function v9(H,M){let z,T,j,O=[];for(let I=0;I<H.length&&!((M-=2)<0);++I)z=H.charCodeAt(I),T=z>>8,j=z%256,O.push(j),O.push(T);return O}V(v9,"utf16leToBytes");function o4(H){return $.toByteArray(h9(H))}V(o4,"base64ToBytes");function LW(H,M,z,T){let j;for(j=0;j<T&&!(j+z>=M.length||j>=H.length);++j)M[j+z]=H[j];return j}V(LW,"blitBuffer");function Y0(H,M){return H instanceof M||H!=null&&H.constructor!=null&&H.constructor.name!=null&&H.constructor.name===M.name}V(Y0,"isInstance");function oW(H){return H!==H}V(oW,"numberIsNaN");var A$=function(){let H="0123456789abcdef",M=Array(256);for(let z=0;z<16;++z){let T=z*16;for(let j=0;j<16;++j)M[T+j]=H[z]+H[j]}return M}();function O0(H){return typeof BigInt>"u"?f9:H}V(O0,"defineBigIntMethod");function f9(){throw Error("BigInt not supported")}V(f9,"BufferBigIntNotDefined")}),B4,K9,EZ,i,r,u=d1(()=>{B4=globalThis,K9=globalThis.setImmediate??((W)=>setTimeout(W,0)),EZ=globalThis.clearImmediate??((W)=>clearTimeout(W)),i=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:_Z().Buffer,r=globalThis.process??{},r.env??(r.env={});try{r.nextTick(()=>{})}catch{let W=Promise.resolve();r.nextTick=W.then.bind(W)}}),S8=o((W,$)=>{u();var Z=typeof Reflect=="object"?Reflect:null,J=Z&&typeof Z.apply=="function"?Z.apply:V(function(h,N,A){return Function.prototype.apply.call(h,N,A)},"ReflectApply"),X;Z&&typeof Z.ownKeys=="function"?X=Z.ownKeys:Object.getOwnPropertySymbols?X=V(function(h){return Object.getOwnPropertyNames(h).concat(Object.getOwnPropertySymbols(h))},"ReflectOwnKeys"):X=V(function(h){return Object.getOwnPropertyNames(h)},"ReflectOwnKeys");function Y(h){console&&console.warn&&console.warn(h)}V(Y,"ProcessEmitWarning");var L=Number.isNaN||V(function(h){return h!==h},"NumberIsNaN");function G(){G.init.call(this)}V(G,"EventEmitter"),$.exports=G,$.exports.once=v,G.EventEmitter=G,G.prototype._events=void 0,G.prototype._eventsCount=0,G.prototype._maxListeners=void 0;var U=10;function D(h){if(typeof h!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof h)}V(D,"checkListener"),Object.defineProperty(G,"defaultMaxListeners",{enumerable:!0,get:V(function(){return U},"get"),set:V(function(h){if(typeof h!="number"||h<0||L(h))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+h+".");U=h},"set")}),G.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},G.prototype.setMaxListeners=V(function(h){if(typeof h!="number"||h<0||L(h))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+h+".");return this._maxListeners=h,this},"setMaxListeners");function P(h){return h._maxListeners===void 0?G.defaultMaxListeners:h._maxListeners}V(P,"_getMaxListeners"),G.prototype.getMaxListeners=V(function(){return P(this)},"getMaxListeners"),G.prototype.emit=V(function(h){for(var N=[],A=1;A<arguments.length;A++)N.push(arguments[A]);var f=h==="error",B=this._events;if(B!==void 0)f=f&&B.error===void 0;else if(!f)return!1;if(f){var C;if(N.length>0&&(C=N[0]),C instanceof Error)throw C;var c=Error("Unhandled error."+(C?" ("+C.message+")":""));throw c.context=C,c}var m=B[h];if(m===void 0)return!1;if(typeof m=="function")J(m,this,N);else for(var b=m.length,g=Q(m,b),A=0;A<b;++A)J(g[A],this,N);return!0},"emit");function w(h,N,A,f){var B,C,c;if(D(A),C=h._events,C===void 0?(C=h._events=Object.create(null),h._eventsCount=0):(C.newListener!==void 0&&(h.emit("newListener",N,A.listener?A.listener:A),C=h._events),c=C[N]),c===void 0)c=C[N]=A,++h._eventsCount;else if(typeof c=="function"?c=C[N]=f?[A,c]:[c,A]:f?c.unshift(A):c.push(A),B=P(h),B>0&&c.length>B&&!c.warned){c.warned=!0;var m=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(N)+" listeners added. Use emitter.setMaxListeners() to increase limit");m.name="MaxListenersExceededWarning",m.emitter=h,m.type=N,m.count=c.length,Y(m)}return h}V(w,"_addListener"),G.prototype.addListener=V(function(h,N){return w(this,h,N,!1)},"addListener"),G.prototype.on=G.prototype.addListener,G.prototype.prependListener=V(function(h,N){return w(this,h,N,!0)},"prependListener");function R(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}V(R,"onceWrapper");function S(h,N,A){var f={fired:!1,wrapFn:void 0,target:h,type:N,listener:A},B=R.bind(f);return B.listener=A,f.wrapFn=B,B}V(S,"_onceWrap"),G.prototype.once=V(function(h,N){return D(N),this.on(h,S(this,h,N)),this},"once"),G.prototype.prependOnceListener=V(function(h,N){return D(N),this.prependListener(h,S(this,h,N)),this},"prependOnceListener"),G.prototype.removeListener=V(function(h,N){var A,f,B,C,c;if(D(N),f=this._events,f===void 0)return this;if(A=f[h],A===void 0)return this;if(A===N||A.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete f[h],f.removeListener&&this.emit("removeListener",h,A.listener||N));else if(typeof A!="function"){for(B=-1,C=A.length-1;C>=0;C--)if(A[C]===N||A[C].listener===N){c=A[C].listener,B=C;break}if(B<0)return this;B===0?A.shift():_(A,B),A.length===1&&(f[h]=A[0]),f.removeListener!==void 0&&this.emit("removeListener",h,c||N)}return this},"removeListener"),G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=V(function(h){var N,A,f;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[h]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[h]),this;if(arguments.length===0){var B=Object.keys(A),C;for(f=0;f<B.length;++f)C=B[f],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(N=A[h],typeof N=="function")this.removeListener(h,N);else if(N!==void 0)for(f=N.length-1;f>=0;f--)this.removeListener(h,N[f]);return this},"removeAllListeners");function F(h,N,A){var f=h._events;if(f===void 0)return[];var B=f[N];return B===void 0?[]:typeof B=="function"?A?[B.listener||B]:[B]:A?E(B):Q(B,B.length)}V(F,"_listeners"),G.prototype.listeners=V(function(h){return F(this,h,!0)},"listeners"),G.prototype.rawListeners=V(function(h){return F(this,h,!1)},"rawListeners"),G.listenerCount=function(h,N){return typeof h.listenerCount=="function"?h.listenerCount(N):K.call(h,N)},G.prototype.listenerCount=K;function K(h){var N=this._events;if(N!==void 0){var A=N[h];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}V(K,"listenerCount"),G.prototype.eventNames=V(function(){return this._eventsCount>0?X(this._events):[]},"eventNames");function Q(h,N){for(var A=Array(N),f=0;f<N;++f)A[f]=h[f];return A}V(Q,"arrayClone");function _(h,N){for(;N+1<h.length;N++)h[N]=h[N+1];h.pop()}V(_,"spliceOne");function E(h){for(var N=Array(h.length),A=0;A<N.length;++A)N[A]=h[A].listener||h[A];return N}V(E,"unwrapListeners");function v(h,N){return new Promise(function(A,f){function B(c){h.removeListener(N,C),f(c)}V(B,"errorListener");function C(){typeof h.removeListener=="function"&&h.removeListener("error",B),A([].slice.call(arguments))}V(C,"resolver"),q(h,N,C,{once:!0}),N!=="error"&&x(h,B,{once:!0})})}V(v,"once");function x(h,N,A){typeof h.on=="function"&&q(h,"error",N,A)}V(x,"addErrorHandlerIfEventEmitter");function q(h,N,A,f){if(typeof h.on=="function")f.once?h.once(N,A):h.on(N,A);else if(typeof h.addEventListener=="function")h.addEventListener(N,V(function B(C){f.once&&h.removeEventListener(N,B),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof h)}V(q,"eventTargetAgnosticAddListener")}),Q7={};S0(Q7,{Socket:()=>w8,isIP:()=>S7});function S7(W){return 0}var U7,Y9,lW,w8,tW=d1(()=>{u(),U7=Q8(S8(),1),V(S7,"isIP"),Y9=/^[^.]+\./,lW=class W extends U7.EventEmitter{constructor(){super(...arguments);t(this,"opts",{}),t(this,"connecting",!1),t(this,"pending",!0),t(this,"writable",!0),t(this,"encrypted",!1),t(this,"authorized",!1),t(this,"destroyed",!1),t(this,"ws",null),t(this,"writeBuffer"),t(this,"tlsState",0),t(this,"tlsRead"),t(this,"tlsWrite")}static get poolQueryViaFetch(){return W.opts.poolQueryViaFetch??W.defaults.poolQueryViaFetch}static set poolQueryViaFetch($){W.opts.poolQueryViaFetch=$}static get fetchEndpoint(){return W.opts.fetchEndpoint??W.defaults.fetchEndpoint}static set fetchEndpoint($){W.opts.fetchEndpoint=$}static get fetchConnectionCache(){return!0}static set fetchConnectionCache($){console.warn("The `fetchConnectionCache` option is deprecated (now always `true`)")}static get fetchFunction(){return W.opts.fetchFunction??W.defaults.fetchFunction}static set fetchFunction($){W.opts.fetchFunction=$}static get webSocketConstructor(){return W.opts.webSocketConstructor??W.defaults.webSocketConstructor}static set webSocketConstructor($){W.opts.webSocketConstructor=$}get webSocketConstructor(){return this.opts.webSocketConstructor??W.webSocketConstructor}set webSocketConstructor($){this.opts.webSocketConstructor=$}static get wsProxy(){return W.opts.wsProxy??W.defaults.wsProxy}static set wsProxy($){W.opts.wsProxy=$}get wsProxy(){return this.opts.wsProxy??W.wsProxy}set wsProxy($){this.opts.wsProxy=$}static get coalesceWrites(){return W.opts.coalesceWrites??W.defaults.coalesceWrites}static set coalesceWrites($){W.opts.coalesceWrites=$}get coalesceWrites(){return this.opts.coalesceWrites??W.coalesceWrites}set coalesceWrites($){this.opts.coalesceWrites=$}static get useSecureWebSocket(){return W.opts.useSecureWebSocket??W.defaults.useSecureWebSocket}static set useSecureWebSocket($){W.opts.useSecureWebSocket=$}get useSecureWebSocket(){return this.opts.useSecureWebSocket??W.useSecureWebSocket}set useSecureWebSocket($){this.opts.useSecureWebSocket=$}static get forceDisablePgSSL(){return W.opts.forceDisablePgSSL??W.defaults.forceDisablePgSSL}static set forceDisablePgSSL($){W.opts.forceDisablePgSSL=$}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??W.forceDisablePgSSL}set forceDisablePgSSL($){this.opts.forceDisablePgSSL=$}static get disableSNI(){return W.opts.disableSNI??W.defaults.disableSNI}static set disableSNI($){W.opts.disableSNI=$}get disableSNI(){return this.opts.disableSNI??W.disableSNI}set disableSNI($){this.opts.disableSNI=$}static get disableWarningInBrowsers(){return W.opts.disableWarningInBrowsers??W.defaults.disableWarningInBrowsers}static set disableWarningInBrowsers($){W.opts.disableWarningInBrowsers=$}get disableWarningInBrowsers(){return this.opts.disableWarningInBrowsers??W.disableWarningInBrowsers}set disableWarningInBrowsers($){this.opts.disableWarningInBrowsers=$}static get pipelineConnect(){return W.opts.pipelineConnect??W.defaults.pipelineConnect}static set pipelineConnect($){W.opts.pipelineConnect=$}get pipelineConnect(){return this.opts.pipelineConnect??W.pipelineConnect}set pipelineConnect($){this.opts.pipelineConnect=$}static get subtls(){return W.opts.subtls??W.defaults.subtls}static set subtls($){W.opts.subtls=$}get subtls(){return this.opts.subtls??W.subtls}set subtls($){this.opts.subtls=$}static get pipelineTLS(){return W.opts.pipelineTLS??W.defaults.pipelineTLS}static set pipelineTLS($){W.opts.pipelineTLS=$}get pipelineTLS(){return this.opts.pipelineTLS??W.pipelineTLS}set pipelineTLS($){this.opts.pipelineTLS=$}static get rootCerts(){return W.opts.rootCerts??W.defaults.rootCerts}static set rootCerts($){W.opts.rootCerts=$}get rootCerts(){return this.opts.rootCerts??W.rootCerts}set rootCerts($){this.opts.rootCerts=$}wsProxyAddrForHost($,Z){let J=this.wsProxy;if(J===void 0)throw Error("No WebSocket proxy is configured. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#wsproxy-string--host-string-port-number--string--string");return typeof J=="function"?J($,Z):`${J}?address=${$}:${Z}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,Z,J){this.connecting=!0,J&&this.once("connect",J);let X=V(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),Y=V((G,U=!1)=>{G.binaryType="arraybuffer",G.addEventListener("error",(D)=>{this.emit("error",D),this.emit("close")}),G.addEventListener("message",(D)=>{if(this.tlsState===0){let P=i.from(D.data);this.emit("data",P)}}),G.addEventListener("close",()=>{this.emit("close")}),U?X():G.addEventListener("open",X)},"configureWebSocket"),L;try{L=this.wsProxyAddrForHost(Z,typeof $=="string"?parseInt($,10):$)}catch(G){this.emit("error",G),this.emit("close");return}try{let G=(this.useSecureWebSocket?"wss:":"ws:")+"//"+L;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(G),Y(this.ws);else try{this.ws=new WebSocket(G),Y(this.ws)}catch{this.ws=new __unstable_WebSocket(G),Y(this.ws)}}catch(G){let U=(this.useSecureWebSocket?"https:":"http:")+"//"+L;fetch(U,{headers:{Upgrade:"websocket"}}).then((D)=>{if(this.ws=D.webSocket,this.ws==null)throw G;this.ws.accept(),Y(this.ws,!0)}).catch((D)=>{this.emit("error",Error(`All attempts to open a WebSocket to connect to the database failed. Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined. Details: ${D}`)),this.emit("close")})}}async startTls($){if(this.subtls===void 0)throw Error("For Postgres SSL connections, you must set `neonConfig.subtls` to the subtls library. See https://github.com/neondatabase/serverless/blob/main/CONFIG.md for more information.");this.tlsState=1;let Z=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),X=J.read.bind(J),Y=this.rawWrite.bind(this),{read:L,write:G}=await this.subtls.startTls($,Z,X,Y,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=L,this.tlsWrite=G,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit("secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let $=await this.tlsRead();if($===void 0)break;{let Z=i.from($);this.emit("data",Z)}}}rawWrite($){if(!this.coalesceWrites){this.ws&&this.ws.send($);return}if(this.writeBuffer===void 0)this.writeBuffer=$,setTimeout(()=>{this.ws&&this.ws.send(this.writeBuffer),this.writeBuffer=void 0},0);else{let Z=new Uint8Array(this.writeBuffer.length+$.length);Z.set(this.writeBuffer),Z.set($,this.writeBuffer.length),this.writeBuffer=Z}}write($,Z="utf8",J=(X)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=i.from($,Z)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,Z,J)}):(this.tlsWrite($),J()),!0)}end($=i.alloc(0),Z="utf8",J=()=>{}){return this.write($,Z,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},V(lW,"Socket"),t(lW,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:V((W,$,Z)=>{let J;return Z?.jwtAuth?J=W.replace(Y9,"apiauth."):J=W.replace(Y9,"api."),"https://"+J+"/sql"},"fetchEndpoint"),fetchConnectionCache:!0,fetchFunction:void 0,webSocketConstructor:void 0,wsProxy:V((W)=>W+"/v2","wsProxy"),useSecureWebSocket:!0,forceDisablePgSSL:!0,coalesceWrites:!0,pipelineConnect:"password",subtls:void 0,rootCerts:"",pipelineTLS:!1,disableSNI:!1,disableWarningInBrowsers:!1}),t(lW,"opts",{}),w8=lW}),_7={};S0(_7,{parse:()=>M9});function M9(W,$=!1){let{protocol:Z}=new URL(W),J="http:"+W.substring(Z.length),{username:X,password:Y,host:L,hostname:G,port:U,pathname:D,search:P,searchParams:w,hash:R}=new URL(J);Y=decodeURIComponent(Y),X=decodeURIComponent(X),D=decodeURIComponent(D);let S=X+":"+Y,F=$?Object.fromEntries(w.entries()):P;return{href:W,protocol:Z,auth:S,username:X,password:Y,host:L,hostname:G,port:U,pathname:D,search:P,query:F,hash:R}}var E7=d1(()=>{u(),V(M9,"parse")}),h7=o((W)=>{u(),W.parse=function(X,Y){return new Z(X,Y).parse()};var $=class X{constructor(Y,L){this.source=Y,this.transform=L||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var Y=this.source[this.position++];return Y==="\\"?{value:this.source[this.position++],escaped:!0}:{value:Y,escaped:!1}}record(Y){this.recorded.push(Y)}newEntry(Y){var L;(this.recorded.length>0||Y)&&(L=this.recorded.join(""),L==="NULL"&&!Y&&(L=null),L!==null&&(L=this.transform(L)),this.entries.push(L),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var Y=this.nextCharacter();if(Y.value==="=")break}}parse(Y){var L,G,U;for(this.consumeDimensions();!this.isEof();)if(L=this.nextCharacter(),L.value==="{"&&!U)this.dimension++,this.dimension>1&&(G=new X(this.source.substr(this.position-1),this.transform),this.entries.push(G.parse(!0)),this.position+=G.position-2);else if(L.value==="}"&&!U){if(this.dimension--,!this.dimension&&(this.newEntry(),Y))return this.entries}else L.value==='"'&&!L.escaped?(U&&this.newEntry(!0),U=!U):L.value===","&&!U?this.newEntry():this.record(L.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};V($,"ArrayParser");var Z=$;function J(X){return X}V(J,"identity")}),T7=o((W,$)=>{u();var Z=h7();$.exports={create:V(function(J,X){return{parse:V(function(){return Z.parse(J,X)},"parse")}},"create")}}),hZ=o((W,$)=>{u();var Z=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,X=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Y=/^-?infinity$/;$.exports=V(function(P){if(Y.test(P))return Number(P.replace("i","I"));var w=Z.exec(P);if(!w)return L(P)||null;var R=!!w[8],S=parseInt(w[1],10);R&&(S=U(S));var F=parseInt(w[2],10)-1,K=w[3],Q=parseInt(w[4],10),_=parseInt(w[5],10),E=parseInt(w[6],10),v=w[7];v=v?1000*parseFloat(v):0;var x,q=G(P);return q!=null?(x=new Date(Date.UTC(S,F,K,Q,_,E,v)),D(S)&&x.setUTCFullYear(S),q!==0&&x.setTime(x.getTime()-q)):(x=new Date(S,F,K,Q,_,E,v),D(S)&&x.setFullYear(S)),x},"parseDate");function L(P){var w=J.exec(P);if(w){var R=parseInt(w[1],10),S=!!w[4];S&&(R=U(R));var F=parseInt(w[2],10)-1,K=w[3],Q=new Date(R,F,K);return D(R)&&Q.setFullYear(R),Q}}V(L,"getDate");function G(P){if(P.endsWith("+00"))return 0;var w=X.exec(P.split(" ")[1]);if(w){var R=w[1];if(R==="Z")return 0;var S=R==="-"?-1:1,F=parseInt(w[2],10)*3600+parseInt(w[3]||0,10)*60+parseInt(w[4]||0,10);return F*S*1000}}V(G,"timeZoneOffset");function U(P){return-(P-1)}V(U,"bcYearToNegativeYear");function D(P){return P>=0&&P<100}V(D,"is0To99")}),TZ=o((W,$)=>{u(),$.exports=J;var Z=Object.prototype.hasOwnProperty;function J(X){for(var Y=1;Y<arguments.length;Y++){var L=arguments[Y];for(var G in L)Z.call(L,G)&&(X[G]=L[G])}return X}V(J,"extend")}),vZ=o((W,$)=>{u();var Z=TZ();$.exports=J;function J(E){if(!(this instanceof J))return new J(E);Z(this,_(E))}V(J,"PostgresInterval");var X=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var E=X.filter(this.hasOwnProperty,this);return this.milliseconds&&E.indexOf("seconds")<0&&E.push("seconds"),E.length===0?"0":E.map(function(v){var x=this[v]||0;return v==="seconds"&&this.milliseconds&&(x=(x+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),x+" "+v},this).join(" ")};var Y={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},L=["years","months","days"],G=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var E=L.map(x,this).join(""),v=G.map(x,this).join("");return"P"+E+"T"+v;function x(q){var h=this[q]||0;return q==="seconds"&&this.milliseconds&&(h=(h+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),h+Y[q]}};var U="([+-]?\\d+)",D=U+"\\s+years?",P=U+"\\s+mons?",w=U+"\\s+days?",R="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",S=new RegExp([D,P,w,R].map(function(E){return"("+E+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},K=["hours","minutes","seconds","milliseconds"];function Q(E){var v=E+"000000".slice(E.length);return parseInt(v,10)/1000}V(Q,"parseMilliseconds");function _(E){if(!E)return{};var v=S.exec(E),x=v[8]==="-";return Object.keys(F).reduce(function(q,h){var N=F[h],A=v[N];return!A||(A=h==="milliseconds"?Q(A):parseInt(A,10),!A)||(x&&~K.indexOf(h)&&(A*=-1),q[h]=A),q},{})}V(_,"parse")}),fZ=o((W,$)=>{u(),$.exports=V(function(Z){if(/^\\x/.test(Z))return new i(Z.substr(2),"hex");for(var J="",X=0;X<Z.length;)if(Z[X]!=="\\")J+=Z[X],++X;else if(/[0-7]{3}/.test(Z.substr(X+1,3)))J+=String.fromCharCode(parseInt(Z.substr(X+1,3),8)),X+=4;else{for(var Y=1;X+Y<Z.length&&Z[X+Y]==="\\";)Y++;for(var L=0;L<Math.floor(Y/2);++L)J+="\\";X+=Math.floor(Y/2)*2}return new i(J,"binary")},"parseBytea")}),jZ=o((W,$)=>{u();var Z=h7(),J=T7(),X=hZ(),Y=vZ(),L=fZ();function G(f){return V(function(B){return B===null?B:f(B)},"nullAllowed")}V(G,"allowNull");function U(f){return f===null?f:f==="TRUE"||f==="t"||f==="true"||f==="y"||f==="yes"||f==="on"||f==="1"}V(U,"parseBool");function D(f){return f?Z.parse(f,U):null}V(D,"parseBoolArray");function P(f){return parseInt(f,10)}V(P,"parseBaseTenInt");function w(f){return f?Z.parse(f,G(P)):null}V(w,"parseIntegerArray");function R(f){return f?Z.parse(f,G(function(B){return x(B).trim()})):null}V(R,"parseBigIntegerArray");var S=V(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=h(C)),C});return B.parse()},"parsePointArray"),F=V(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=parseFloat(C)),C});return B.parse()},"parseFloatArray"),K=V(function(f){if(!f)return null;var B=J.create(f);return B.parse()},"parseStringArray"),Q=V(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=X(C)),C});return B.parse()},"parseDateArray"),_=V(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=Y(C)),C});return B.parse()},"parseIntervalArray"),E=V(function(f){return f?Z.parse(f,G(L)):null},"parseByteAArray"),v=V(function(f){return parseInt(f,10)},"parseInteger"),x=V(function(f){var B=String(f);return/^\d+$/.test(B)?B:f},"parseBigInteger"),q=V(function(f){return f?Z.parse(f,G(JSON.parse)):null},"parseJsonArray"),h=V(function(f){return f[0]!=="("?null:(f=f.substring(1,f.length-1).split(","),{x:parseFloat(f[0]),y:parseFloat(f[1])})},"parsePoint"),N=V(function(f){if(f[0]!=="<"&&f[1]!=="(")return null;for(var B="(",C="",c=!1,m=2;m<f.length-1;m++){if(c||(B+=f[m]),f[m]===")"){c=!0;continue}else if(!c)continue;f[m]!==","&&(C+=f[m])}var b=h(B);return b.radius=parseFloat(C),b},"parseCircle"),A=V(function(f){f(20,x),f(21,v),f(23,v),f(26,v),f(700,parseFloat),f(701,parseFloat),f(16,U),f(1082,X),f(1114,X),f(1184,X),f(600,h),f(651,K),f(718,N),f(1000,D),f(1001,E),f(1005,w),f(1007,w),f(1028,w),f(1016,R),f(1017,S),f(1021,F),f(1022,F),f(1231,F),f(1014,K),f(1015,K),f(1008,K),f(1009,K),f(1040,K),f(1041,K),f(1115,Q),f(1182,Q),f(1185,Q),f(1186,Y),f(1187,_),f(17,L),f(114,JSON.parse.bind(JSON)),f(3802,JSON.parse.bind(JSON)),f(199,q),f(3807,q),f(3907,K),f(2951,K),f(791,K),f(1183,K),f(1270,K)},"init");$.exports={init:A}}),AZ=o((W,$)=>{u();var Z=1e6;function J(X){var Y=X.readInt32BE(0),L=X.readUInt32BE(4),G="";Y<0&&(Y=~Y+(L===0),L=~L+1>>>0,G="-");var U="",D,P,w,R,S,F;{if(D=Y%Z,Y=Y/Z>>>0,P=4294967296*D+L,L=P/Z>>>0,w=""+(P-Z*L),L===0&&Y===0)return G+w+U;for(R="",S=6-w.length,F=0;F<S;F++)R+="0";U=R+w+U}{if(D=Y%Z,Y=Y/Z>>>0,P=4294967296*D+L,L=P/Z>>>0,w=""+(P-Z*L),L===0&&Y===0)return G+w+U;for(R="",S=6-w.length,F=0;F<S;F++)R+="0";U=R+w+U}{if(D=Y%Z,Y=Y/Z>>>0,P=4294967296*D+L,L=P/Z>>>0,w=""+(P-Z*L),L===0&&Y===0)return G+w+U;for(R="",S=6-w.length,F=0;F<S;F++)R+="0";U=R+w+U}return D=Y%Z,P=4294967296*D+L,w=""+P%Z,G+w+U}V(J,"readInt8"),$.exports=J}),NZ=o((W,$)=>{u();var Z=AZ(),J=V(function(K,Q,_,E,v){_=_||0,E=E||!1,v=v||function(c,m,b){return c*Math.pow(2,b)+m};var x=_>>3,q=V(function(c){return E?~c&255:c},"inv"),h=255,N=8-_%8;Q<N&&(h=255<<8-Q&255,N=Q),_&&(h=h>>_%8);var A=0;_%8+Q>=8&&(A=v(0,q(K[x])&h,N));for(var f=Q+_>>3,B=x+1;B<f;B++)A=v(A,q(K[B]),8);var C=(Q+_)%8;return C>0&&(A=v(A,q(K[f])>>8-C,C)),A},"parseBits"),X=V(function(K,Q,_){var E=Math.pow(2,_-1)-1,v=J(K,1),x=J(K,_,1);if(x===0)return 0;var q=1,h=V(function(A,f,B){A===0&&(A=1);for(var C=1;C<=B;C++)q/=2,(f&1<<B-C)>0&&(A+=q);return A},"parsePrecisionBits"),N=J(K,Q,_+1,!1,h);return x==Math.pow(2,_+1)-1?N===0?v===0?1/0:-1/0:NaN:(v===0?1:-1)*Math.pow(2,x-E)*N},"parseFloatFromBits"),Y=V(function(K){return J(K,1)==1?-1*(J(K,15,1,!0)+1):J(K,15,1)},"parseInt16"),L=V(function(K){return J(K,1)==1?-1*(J(K,31,1,!0)+1):J(K,31,1)},"parseInt32"),G=V(function(K){return X(K,23,8)},"parseFloat32"),U=V(function(K){return X(K,52,11)},"parseFloat64"),D=V(function(K){var Q=J(K,16,32);if(Q==49152)return NaN;for(var _=Math.pow(1e4,J(K,16,16)),E=0,v=[],x=J(K,16),q=0;q<x;q++)E+=J(K,16,64+16*q)*_,_/=1e4;var h=Math.pow(10,J(K,16,48));return(Q===0?1:-1)*Math.round(E*h)/h},"parseNumeric"),P=V(function(K,Q){var _=J(Q,1),E=J(Q,63,1),v=new Date((_===0?1:-1)*E/1000+946684800000);return K||v.setTime(v.getTime()+v.getTimezoneOffset()*60000),v.usec=E%1000,v.getMicroSeconds=function(){return this.usec},v.setMicroSeconds=function(x){this.usec=x},v.getUTCMicroSeconds=function(){return this.usec},v},"parseDate"),w=V(function(K){for(var Q=J(K,32),_=J(K,32,32),E=J(K,32,64),v=96,x=[],q=0;q<Q;q++)x[q]=J(K,32,v),v+=32,v+=32;var h=V(function(A){var f=J(K,32,v);if(v+=32,f==4294967295)return null;var B;if(A==23||A==20)return B=J(K,f*8,v),v+=f*8,B;if(A==25)return B=K.toString(this.encoding,v>>3,(v+=f<<3)>>3),B;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),N=V(function(A,f){var B=[],C;if(A.length>1){var c=A.shift();for(C=0;C<c;C++)B[C]=N(A,f);A.unshift(c)}else for(C=0;C<A[0];C++)B[C]=h(f);return B},"parse");return N(x,E)},"parseArray"),R=V(function(K){return K.toString("utf8")},"parseText"),S=V(function(K){return K===null?null:J(K,8)>0},"parseBool"),F=V(function(K){K(20,Z),K(21,Y),K(23,L),K(26,L),K(1700,D),K(700,G),K(701,U),K(16,S),K(1114,P.bind(null,!1)),K(1184,P.bind(null,!0)),K(1000,w),K(1007,w),K(1016,w),K(1008,w),K(1009,w),K(25,R)},"init");$.exports={init:F}}),CZ=o((W,$)=>{u(),$.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}}),b4=o((W)=>{u();var $=jZ(),Z=NZ(),J=T7(),X=CZ();W.getTypeParser=G,W.setTypeParser=U,W.arrayParser=J,W.builtins=X;var Y={text:{},binary:{}};function L(D){return String(D)}V(L,"noParse");function G(D,P){return P=P||"text",Y[P]&&Y[P][D]||L}V(G,"getTypeParser");function U(D,P,w){typeof P=="function"&&(w=P,P="text"),Y[P][D]=w}V(U,"setTypeParser"),$.init(function(D,P){Y.text[D]=P}),Z.init(function(D,P){Y.binary[D]=P})}),z9=o((W,$)=>{u();var Z=b4();function J(X){this._types=X||Z,this.text={},this.binary={}}V(J,"TypeOverrides"),J.prototype.getOverrides=function(X){switch(X){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(X,Y,L){typeof Y=="function"&&(L=Y,Y="text"),this.getOverrides(Y)[X]=L},J.prototype.getTypeParser=function(X,Y){return Y=Y||"text",this.getOverrides(Y)[X]||this._types.getTypeParser(X,Y)},$.exports=J});function iW(W){let $=1779033703,Z=3144134277,J=1013904242,X=2773480762,Y=1359893119,L=2600822924,G=528734635,U=1541459225,D=0,P=0,w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],R=V((E,v)=>E>>>v|E<<32-v,"rrot"),S=new Uint32Array(64),F=new Uint8Array(64),K=V(()=>{for(let B=0,C=0;B<16;B++,C+=4)S[B]=F[C]<<24|F[C+1]<<16|F[C+2]<<8|F[C+3];for(let B=16;B<64;B++){let C=R(S[B-15],7)^R(S[B-15],18)^S[B-15]>>>3,c=R(S[B-2],17)^R(S[B-2],19)^S[B-2]>>>10;S[B]=S[B-16]+C+S[B-7]+c|0}let E=$,v=Z,x=J,q=X,h=Y,N=L,A=G,f=U;for(let B=0;B<64;B++){let C=R(h,6)^R(h,11)^R(h,25),c=h&N^~h&A,m=f+C+c+w[B]+S[B]|0,b=R(E,2)^R(E,13)^R(E,22),g=E&v^E&x^v&x,p=b+g|0;f=A,A=N,N=h,h=q+m|0,q=x,x=v,v=E,E=m+p|0}$=$+E|0,Z=Z+v|0,J=J+x|0,X=X+q|0,Y=Y+h|0,L=L+N|0,G=G+A|0,U=U+f|0,P=0},"process"),Q=V((E)=>{typeof E=="string"&&(E=new TextEncoder().encode(E));for(let v=0;v<E.length;v++)F[P++]=E[v],P===64&&K();D+=E.length},"add"),_=V(()=>{if(F[P++]=128,P==64&&K(),P+8>64){for(;P<64;)F[P++]=0;K()}for(;P<58;)F[P++]=0;let E=D*8;F[P++]=E/1099511627776&255,F[P++]=E/4294967296&255,F[P++]=E>>>24,F[P++]=E>>>16&255,F[P++]=E>>>8&255,F[P++]=E&255,K();let v=new Uint8Array(32);return v[0]=$>>>24,v[1]=$>>>16&255,v[2]=$>>>8&255,v[3]=$&255,v[4]=Z>>>24,v[5]=Z>>>16&255,v[6]=Z>>>8&255,v[7]=Z&255,v[8]=J>>>24,v[9]=J>>>16&255,v[10]=J>>>8&255,v[11]=J&255,v[12]=X>>>24,v[13]=X>>>16&255,v[14]=X>>>8&255,v[15]=X&255,v[16]=Y>>>24,v[17]=Y>>>16&255,v[18]=Y>>>8&255,v[19]=Y&255,v[20]=L>>>24,v[21]=L>>>16&255,v[22]=L>>>8&255,v[23]=L&255,v[24]=G>>>24,v[25]=G>>>16&255,v[26]=G>>>8&255,v[27]=G&255,v[28]=U>>>24,v[29]=U>>>16&255,v[30]=U>>>8&255,v[31]=U&255,v},"digest");return W===void 0?{add:Q,digest:_}:(Q(W),_())}var qZ=d1(()=>{u(),V(iW,"sha256")}),a0,k9,OZ=d1(()=>{u(),a0=class W{constructor(){t(this,"_dataLength",0),t(this,"_bufferLength",0),t(this,"_state",new Int32Array(4)),t(this,"_buffer",new ArrayBuffer(68)),t(this,"_buffer8"),t(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,Z=!1){return this.onePassHasher.start().appendByteArray($).end(Z)}static hashStr($,Z=!1){return this.onePassHasher.start().appendStr($).end(Z)}static hashAsciiStr($,Z=!1){return this.onePassHasher.start().appendAsciiStr($).end(Z)}static _hex($){let{hexChars:Z,hexOut:J}=W,X,Y,L,G;for(G=0;G<4;G+=1)for(Y=G*8,X=$[G],L=0;L<8;L+=2)J[Y+1+L]=Z.charAt(X&15),X>>>=4,J[Y+0+L]=Z.charAt(X&15),X>>>=4;return J.join("")}static _md5cycle($,Z){let J=$[0],X=$[1],Y=$[2],L=$[3];J+=(X&Y|~X&L)+Z[0]-680876936|0,J=(J<<7|J>>>25)+X|0,L+=(J&X|~J&Y)+Z[1]-389564586|0,L=(L<<12|L>>>20)+J|0,Y+=(L&J|~L&X)+Z[2]+606105819|0,Y=(Y<<17|Y>>>15)+L|0,X+=(Y&L|~Y&J)+Z[3]-1044525330|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&L)+Z[4]-176418897|0,J=(J<<7|J>>>25)+X|0,L+=(J&X|~J&Y)+Z[5]+1200080426|0,L=(L<<12|L>>>20)+J|0,Y+=(L&J|~L&X)+Z[6]-1473231341|0,Y=(Y<<17|Y>>>15)+L|0,X+=(Y&L|~Y&J)+Z[7]-45705983|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&L)+Z[8]+1770035416|0,J=(J<<7|J>>>25)+X|0,L+=(J&X|~J&Y)+Z[9]-1958414417|0,L=(L<<12|L>>>20)+J|0,Y+=(L&J|~L&X)+Z[10]-42063|0,Y=(Y<<17|Y>>>15)+L|0,X+=(Y&L|~Y&J)+Z[11]-1990404162|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&L)+Z[12]+1804603682|0,J=(J<<7|J>>>25)+X|0,L+=(J&X|~J&Y)+Z[13]-40341101|0,L=(L<<12|L>>>20)+J|0,Y+=(L&J|~L&X)+Z[14]-1502002290|0,Y=(Y<<17|Y>>>15)+L|0,X+=(Y&L|~Y&J)+Z[15]+1236535329|0,X=(X<<22|X>>>10)+Y|0,J+=(X&L|Y&~L)+Z[1]-165796510|0,J=(J<<5|J>>>27)+X|0,L+=(J&Y|X&~Y)+Z[6]-1069501632|0,L=(L<<9|L>>>23)+J|0,Y+=(L&X|J&~X)+Z[11]+643717713|0,Y=(Y<<14|Y>>>18)+L|0,X+=(Y&J|L&~J)+Z[0]-373897302|0,X=(X<<20|X>>>12)+Y|0,J+=(X&L|Y&~L)+Z[5]-701558691|0,J=(J<<5|J>>>27)+X|0,L+=(J&Y|X&~Y)+Z[10]+38016083|0,L=(L<<9|L>>>23)+J|0,Y+=(L&X|J&~X)+Z[15]-660478335|0,Y=(Y<<14|Y>>>18)+L|0,X+=(Y&J|L&~J)+Z[4]-405537848|0,X=(X<<20|X>>>12)+Y|0,J+=(X&L|Y&~L)+Z[9]+568446438|0,J=(J<<5|J>>>27)+X|0,L+=(J&Y|X&~Y)+Z[14]-1019803690|0,L=(L<<9|L>>>23)+J|0,Y+=(L&X|J&~X)+Z[3]-187363961|0,Y=(Y<<14|Y>>>18)+L|0,X+=(Y&J|L&~J)+Z[8]+1163531501|0,X=(X<<20|X>>>12)+Y|0,J+=(X&L|Y&~L)+Z[13]-1444681467|0,J=(J<<5|J>>>27)+X|0,L+=(J&Y|X&~Y)+Z[2]-51403784|0,L=(L<<9|L>>>23)+J|0,Y+=(L&X|J&~X)+Z[7]+1735328473|0,Y=(Y<<14|Y>>>18)+L|0,X+=(Y&J|L&~J)+Z[12]-1926607734|0,X=(X<<20|X>>>12)+Y|0,J+=(X^Y^L)+Z[5]-378558|0,J=(J<<4|J>>>28)+X|0,L+=(J^X^Y)+Z[8]-2022574463|0,L=(L<<11|L>>>21)+J|0,Y+=(L^J^X)+Z[11]+1839030562|0,Y=(Y<<16|Y>>>16)+L|0,X+=(Y^L^J)+Z[14]-35309556|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^L)+Z[1]-1530992060|0,J=(J<<4|J>>>28)+X|0,L+=(J^X^Y)+Z[4]+1272893353|0,L=(L<<11|L>>>21)+J|0,Y+=(L^J^X)+Z[7]-155497632|0,Y=(Y<<16|Y>>>16)+L|0,X+=(Y^L^J)+Z[10]-1094730640|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^L)+Z[13]+681279174|0,J=(J<<4|J>>>28)+X|0,L+=(J^X^Y)+Z[0]-358537222|0,L=(L<<11|L>>>21)+J|0,Y+=(L^J^X)+Z[3]-722521979|0,Y=(Y<<16|Y>>>16)+L|0,X+=(Y^L^J)+Z[6]+76029189|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^L)+Z[9]-640364487|0,J=(J<<4|J>>>28)+X|0,L+=(J^X^Y)+Z[12]-421815835|0,L=(L<<11|L>>>21)+J|0,Y+=(L^J^X)+Z[15]+530742520|0,Y=(Y<<16|Y>>>16)+L|0,X+=(Y^L^J)+Z[2]-995338651|0,X=(X<<23|X>>>9)+Y|0,J+=(Y^(X|~L))+Z[0]-198630844|0,J=(J<<6|J>>>26)+X|0,L+=(X^(J|~Y))+Z[7]+1126891415|0,L=(L<<10|L>>>22)+J|0,Y+=(J^(L|~X))+Z[14]-1416354905|0,Y=(Y<<15|Y>>>17)+L|0,X+=(L^(Y|~J))+Z[5]-57434055|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~L))+Z[12]+1700485571|0,J=(J<<6|J>>>26)+X|0,L+=(X^(J|~Y))+Z[3]-1894986606|0,L=(L<<10|L>>>22)+J|0,Y+=(J^(L|~X))+Z[10]-1051523|0,Y=(Y<<15|Y>>>17)+L|0,X+=(L^(Y|~J))+Z[1]-2054922799|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~L))+Z[8]+1873313359|0,J=(J<<6|J>>>26)+X|0,L+=(X^(J|~Y))+Z[15]-30611744|0,L=(L<<10|L>>>22)+J|0,Y+=(J^(L|~X))+Z[6]-1560198380|0,Y=(Y<<15|Y>>>17)+L|0,X+=(L^(Y|~J))+Z[13]+1309151649|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~L))+Z[4]-145523070|0,J=(J<<6|J>>>26)+X|0,L+=(X^(J|~Y))+Z[11]-1120210379|0,L=(L<<10|L>>>22)+J|0,Y+=(J^(L|~X))+Z[2]+718787259|0,Y=(Y<<15|Y>>>17)+L|0,X+=(L^(Y|~J))+Z[9]-343485551|0,X=(X<<21|X>>>11)+Y|0,$[0]=J+$[0]|0,$[1]=X+$[1]|0,$[2]=Y+$[2]|0,$[3]=L+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,L;for(L=0;L<$.length;L+=1){if(Y=$.charCodeAt(L),Y<128)Z[X++]=Y;else if(Y<2048)Z[X++]=(Y>>>6)+192,Z[X++]=Y&63|128;else if(Y<55296||Y>56319)Z[X++]=(Y>>>12)+224,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128;else{if(Y=(Y-55296)*1024+($.charCodeAt(++L)-56320)+65536,Y>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");Z[X++]=(Y>>>18)+240,Z[X++]=Y>>>12&63|128,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128}X>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),X-=64,J[0]=J[16])}return this._bufferLength=X,this}appendAsciiStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,L=0;for(;;){for(Y=Math.min($.length-L,64-X);Y--;)Z[X++]=$.charCodeAt(L++);if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}appendByteArray($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,L=0;for(;;){for(Y=Math.min($.length-L,64-X);Y--;)Z[X++]=$[L++];if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}getState(){let $=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[$[0],$[1],$[2],$[3]]}}setState($){let{buffer:Z,state:J}=$,X=this._state,Y;for(this._dataLength=$.length,this._bufferLength=$.buflen,X[0]=J[0],X[1]=J[1],X[2]=J[2],X[3]=J[3],Y=0;Y<Z.length;Y+=1)this._buffer8[Y]=Z.charCodeAt(Y)}end($=!1){let Z=this._bufferLength,J=this._buffer8,X=this._buffer32,Y=(Z>>2)+1;this._dataLength+=Z;let L=this._dataLength*8;if(J[Z]=128,J[Z+1]=J[Z+2]=J[Z+3]=0,X.set(W.buffer32Identity.subarray(Y),Y),Z>55&&(W._md5cycle(this._state,X),X.set(W.buffer32Identity)),L<=4294967295)X[14]=L;else{let G=L.toString(16).match(/(.*?)(.{0,8})$/);if(G===null)return;let U=parseInt(G[2],16),D=parseInt(G[1],16)||0;X[14]=U,X[15]=D}return W._md5cycle(this._state,X),$?this._state:W._hex(this._state)}},V(a0,"Md5"),t(a0,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),t(a0,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),t(a0,"hexChars","0123456789abcdef"),t(a0,"hexOut",[]),t(a0,"onePassHasher",new a0),k9=a0}),U9={};S0(U9,{createHash:()=>f7,createHmac:()=>j7,randomBytes:()=>v7});function v7(W){return crypto.getRandomValues(i.alloc(W))}function f7(W){if(W==="sha256")return{update:V(function($){return{digest:V(function(){return i.from(iW($))},"digest")}},"update")};if(W==="md5")return{update:V(function($){return{digest:V(function(){return typeof $=="string"?k9.hashStr($):k9.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function j7(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:V(function(Z){return{digest:V(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof Z=="string"&&(Z=new TextEncoder().encode(Z));let J=$.length;if(J>64)$=iW($);else if(J<64){let U=new Uint8Array(64);U.set($),$=U}let X=new Uint8Array(64),Y=new Uint8Array(64);for(let U=0;U<64;U++)X[U]=54^$[U],Y[U]=92^$[U];let L=new Uint8Array(Z.length+64);L.set(X,0),L.set(Z,64);let G=new Uint8Array(96);return G.set(Y,0),G.set(iW(L),64),i.from(iW(G))},"digest")}},"update")}}var A7=d1(()=>{u(),qZ(),OZ(),V(v7,"randomBytes"),V(f7,"createHash"),V(j7,"createHmac")}),I4=o((W,$)=>{u(),$.exports={host:"localhost",user:r.platform==="win32"?r.env.USERNAME:r.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Z=b4(),J=Z.getTypeParser(20,"text"),X=Z.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(Y){Z.setTypeParser(20,"text",Y?Z.getTypeParser(23,"text"):J),Z.setTypeParser(1016,"text",Y?Z.getTypeParser(1007,"text"):X)})}),y4=o((W,$)=>{u();var Z=(A7(),B1(U9)),J=I4();function X(F){var K=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+K+'"'}V(X,"escapeElement");function Y(F){for(var K="{",Q=0;Q<F.length;Q++)Q>0&&(K=K+","),F[Q]===null||typeof F[Q]>"u"?K=K+"NULL":Array.isArray(F[Q])?K=K+Y(F[Q]):F[Q]instanceof i?K+="\\\\x"+F[Q].toString("hex"):K+=X(L(F[Q]));return K=K+"}",K}V(Y,"arrayString");var L=V(function(F,K){if(F==null)return null;if(F instanceof i)return F;if(ArrayBuffer.isView(F)){var Q=i.from(F.buffer,F.byteOffset,F.byteLength);return Q.length===F.byteLength?Q:Q.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?P(F):D(F):Array.isArray(F)?Y(F):typeof F=="object"?G(F,K):F.toString()},"prepareValue");function G(F,K){if(F&&typeof F.toPostgres=="function"){if(K=K||[],K.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return K.push(F),L(F.toPostgres(L),K)}return JSON.stringify(F)}V(G,"prepareObject");function U(F,K){for(F=""+F;F.length<K;)F="0"+F;return F}V(U,"pad");function D(F){var K=-F.getTimezoneOffset(),Q=F.getFullYear(),_=Q<1;_&&(Q=Math.abs(Q)+1);var E=U(Q,4)+"-"+U(F.getMonth()+1,2)+"-"+U(F.getDate(),2)+"T"+U(F.getHours(),2)+":"+U(F.getMinutes(),2)+":"+U(F.getSeconds(),2)+"."+U(F.getMilliseconds(),3);return K<0?(E+="-",K*=-1):E+="+",E+=U(Math.floor(K/60),2)+":"+U(K%60,2),_&&(E+=" BC"),E}V(D,"dateToString");function P(F){var K=F.getUTCFullYear(),Q=K<1;Q&&(K=Math.abs(K)+1);var _=U(K,4)+"-"+U(F.getUTCMonth()+1,2)+"-"+U(F.getUTCDate(),2)+"T"+U(F.getUTCHours(),2)+":"+U(F.getUTCMinutes(),2)+":"+U(F.getUTCSeconds(),2)+"."+U(F.getUTCMilliseconds(),3);return _+="+00:00",Q&&(_+=" BC"),_}V(P,"dateToStringUTC");function w(F,K,Q){return F=typeof F=="string"?{text:F}:F,K&&(typeof K=="function"?F.callback=K:F.values=K),Q&&(F.callback=Q),F}V(w,"normalizeQueryConfig");var R=V(function(F){return Z.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),S=V(function(F,K,Q){var _=R(K+F),E=R(i.concat([i.from(_),Q]));return"md5"+E},"postgresMd5PasswordHash");$.exports={prepareValue:V(function(F){return L(F)},"prepareValueWrapper"),normalizeQueryConfig:w,postgresMd5PasswordHash:S,md5:R}}),aW={};S0(aW,{default:()=>N7});var N7,g4=d1(()=>{u(),N7={}}),xZ=o((W,$)=>{u();var Z=(A7(),B1(U9));function J(K){if(K.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let Q=Z.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:Q,response:"n,,n=*,r="+Q,message:"SASLInitialResponse"}}V(J,"startSession");function X(K,Q,_){if(K.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof _!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let E=D(_);if(E.nonce.startsWith(K.clientNonce)){if(E.nonce.length===K.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var v=i.from(E.salt,"base64"),x=F(Q,v,E.iteration),q=S(x,"Client Key"),h=R(q),N="n=*,r="+K.clientNonce,A="r="+E.nonce+",s="+E.salt+",i="+E.iteration,f="c=biws,r="+E.nonce,B=N+","+A+","+f,C=S(h,B),c=w(q,C),m=c.toString("base64"),b=S(x,"Server Key"),g=S(b,B);K.message="SASLResponse",K.serverSignature=g.toString("base64"),K.response=f+",p="+m}V(X,"continueSession");function Y(K,Q){if(K.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:_}=P(Q);if(_!==K.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}V(Y,"finalizeSession");function L(K){if(typeof K!="string")throw TypeError("SASL: text must be a string");return K.split("").map((Q,_)=>K.charCodeAt(_)).every((Q)=>Q>=33&&Q<=43||Q>=45&&Q<=126)}V(L,"isPrintableChars");function G(K){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(K)}V(G,"isBase64");function U(K){if(typeof K!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(K.split(",").map((Q)=>{if(!/^.=/.test(Q))throw Error("SASL: Invalid attribute pair entry");let _=Q[0],E=Q.substring(2);return[_,E]}))}V(U,"parseAttributePairs");function D(K){let Q=U(K),_=Q.get("r");if(_){if(!L(_))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let E=Q.get("s");if(E){if(!G(E))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let v=Q.get("i");if(v){if(!/^[1-9][0-9]*$/.test(v))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let x=parseInt(v,10);return{nonce:_,salt:E,iteration:x}}V(D,"parseServerFirstMessage");function P(K){let Q=U(K).get("v");if(Q){if(!G(Q))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:Q}}V(P,"parseServerFinalMessage");function w(K,Q){if(!i.isBuffer(K))throw TypeError("first argument must be a Buffer");if(!i.isBuffer(Q))throw TypeError("second argument must be a Buffer");if(K.length!==Q.length)throw Error("Buffer lengths must match");if(K.length===0)throw Error("Buffers cannot be empty");return i.from(K.map((_,E)=>K[E]^Q[E]))}V(w,"xorBuffers");function R(K){return Z.createHash("sha256").update(K).digest()}V(R,"sha256");function S(K,Q){return Z.createHmac("sha256",K).update(Q).digest()}V(S,"hmacSha256");function F(K,Q,_){for(var E=S(K,i.concat([Q,i.from([0,0,0,1])])),v=E,x=0;x<_-1;x++)E=S(K,E),v=w(v,E);return v}V(F,"Hi"),$.exports={startSession:J,continueSession:X,finalizeSession:Y}}),V9={};S0(V9,{join:()=>C7});function C7(...W){return W.join("/")}var q7=d1(()=>{u(),V(C7,"join")}),P9={};S0(P9,{stat:()=>O7});function O7(W,$){$(Error("No filesystem"))}var x7=d1(()=>{u(),V(O7,"stat")}),F9={};S0(F9,{default:()=>B7});var B7,b7=d1(()=>{u(),B7={}}),I7={};S0(I7,{StringDecoder:()=>y7});var H9,y7,BZ=d1(()=>{u(),H9=class{constructor($){t(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},V(H9,"StringDecoder"),y7=H9}),bZ=o((W,$)=>{u();var{Transform:Z}=(b7(),B1(F9)),{StringDecoder:J}=(BZ(),B1(I7)),X=Symbol("last"),Y=Symbol("decoder");function L(w,R,S){let F;if(this.overflow){if(F=this[Y].write(w).split(this.matcher),F.length===1)return S();F.shift(),this.overflow=!1}else this[X]+=this[Y].write(w),F=this[X].split(this.matcher);this[X]=F.pop();for(let K=0;K<F.length;K++)try{U(this,this.mapper(F[K]))}catch(Q){return S(Q)}if(this.overflow=this[X].length>this.maxLength,this.overflow&&!this.skipOverflow){S(Error("maximum buffer reached"));return}S()}V(L,"transform");function G(w){if(this[X]+=this[Y].end(),this[X])try{U(this,this.mapper(this[X]))}catch(R){return w(R)}w()}V(G,"flush");function U(w,R){R!==void 0&&w.push(R)}V(U,"push");function D(w){return w}V(D,"noop");function P(w,R,S){switch(w=w||/\r?\n/,R=R||D,S=S||{},arguments.length){case 1:typeof w=="function"?(R=w,w=/\r?\n/):typeof w=="object"&&!(w instanceof RegExp)&&!w[Symbol.split]&&(S=w,w=/\r?\n/);break;case 2:typeof w=="function"?(S=R,R=w,w=/\r?\n/):typeof R=="object"&&(S=R,R=D)}S=Object.assign({},S),S.autoDestroy=!0,S.transform=L,S.flush=G,S.readableObjectMode=!0;let F=new Z(S);return F[X]="",F[Y]=new J("utf8"),F.matcher=w,F.mapper=R,F.maxLength=S.maxLength,F.skipOverflow=S.skipOverflow||!1,F.overflow=!1,F._destroy=function(K,Q){this._writableState.errorEmitted=!1,Q(K)},F}V(P,"split"),$.exports=P}),IZ=o((W,$)=>{u();var Z=(q7(),B1(V9)),J=(b7(),B1(F9)).Stream,X=bZ(),Y=(g4(),B1(aW)),L=5432,G=r.platform==="win32",U=r.stderr,D=56,P=7,w=61440,R=32768;function S(q){return(q&w)==R}V(S,"isRegFile");var F=["host","port","database","user","password"],K=F.length,Q=F[K-1];function _(){var q=U instanceof J&&U.writable===!0;if(q){var h=Array.prototype.slice.call(arguments).concat(`
28
+ `);U.write(Y.format.apply(Y,h))}}V(_,"warn"),Object.defineProperty($.exports,"isWin",{get:V(function(){return G},"get"),set:V(function(q){G=q},"set")}),$.exports.warnTo=function(q){var h=U;return U=q,h},$.exports.getFileName=function(q){var h=q||r.env,N=h.PGPASSFILE||(G?Z.join(h.APPDATA||"./","postgresql","pgpass.conf"):Z.join(h.HOME||"./",".pgpass"));return N},$.exports.usePgPass=function(q,h){return Object.prototype.hasOwnProperty.call(r.env,"PGPASSWORD")?!1:G?!0:(h=h||"<unkn>",S(q.mode)?q.mode&(D|P)?(_('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',h),!1):!0:(_('WARNING: password file "%s" is not a plain file',h),!1))};var E=$.exports.match=function(q,h){return F.slice(0,-1).reduce(function(N,A,f){return f==1&&Number(q[A]||L)===Number(h[A])?N&&!0:N&&(h[A]==="*"||h[A]===q[A])},!0)};$.exports.getPassword=function(q,h,N){var A,f=h.pipe(X());function B(m){var b=v(m);b&&x(b)&&E(q,b)&&(A=b[Q],f.end())}V(B,"onLine");var C=V(function(){h.destroy(),N(A)},"onEnd"),c=V(function(m){h.destroy(),_("WARNING: error on reading file: %s",m),N(void 0)},"onErr");h.on("error",c),f.on("data",B).on("end",C).on("error",c)};var v=$.exports.parseLine=function(q){if(q.length<11||q.match(/^\s+#/))return null;for(var h="",N="",A=0,f=0,B=0,C={},c=!1,m=V(function(g,p,d){var J1=q.substring(p,d);Object.hasOwnProperty.call(r.env,"PGPASS_NO_DEESCAPE")||(J1=J1.replace(/\\([:\\])/g,"$1")),C[F[g]]=J1},"addToObj"),b=0;b<q.length-1;b+=1){if(h=q.charAt(b+1),N=q.charAt(b),c=A==K-1,c){m(A,f);break}b>=0&&h==":"&&N!=="\\"&&(m(A,f,b+1),f=b+2,A+=1)}return C=Object.keys(C).length===K?C:null,C},x=$.exports.isValidEntry=function(q){for(var h={0:function(C){return C.length>0},1:function(C){return C==="*"?!0:(C=Number(C),isFinite(C)&&C>0&&C<9007199254740992&&Math.floor(C)===C)},2:function(C){return C.length>0},3:function(C){return C.length>0},4:function(C){return C.length>0}},N=0;N<F.length;N+=1){var A=h[N],f=q[F[N]]||"",B=A(f);if(!B)return!1}return!0}}),yZ=o((W,$)=>{u();var Z=(q7(),B1(V9)),J=(x7(),B1(P9)),X=IZ();$.exports=function(Y,L){var G=X.getFileName();J.stat(G,function(U,D){if(U||!X.usePgPass(D,G))return L(void 0);var P=J.createReadStream(G);X.getPassword(Y,P,L)})},$.exports.warnTo=X.warnTo}),g7={};S0(g7,{default:()=>m7});var m7,gZ=d1(()=>{u(),m7={}}),mZ=o((W,$)=>{u();var Z=(E7(),B1(_7)),J=(x7(),B1(P9));function X(Y){if(Y.charAt(0)==="/"){var G=Y.split(" ");return{host:G[0],database:G[1]}}var L=Z.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(Y)?encodeURI(Y).replace(/\%25(\d\d)/g,"%$1"):Y,!0),G=L.query;for(var U in G)Array.isArray(G[U])&&(G[U]=G[U][G[U].length-1]);var D=(L.auth||":").split(":");if(G.user=D[0],G.password=D.splice(1).join(":"),G.port=L.port,L.protocol=="socket:")return G.host=decodeURI(L.pathname),G.database=L.query.db,G.client_encoding=L.query.encoding,G;G.host||(G.host=L.hostname);var P=L.pathname;if(!G.host&&P&&/^%2f/i.test(P)){var w=P.split("/");G.host=decodeURIComponent(w[0]),P=w.splice(1).join("/")}switch(P&&P.charAt(0)==="/"&&(P=P.slice(1)||null),G.database=P&&decodeURI(P),(G.ssl==="true"||G.ssl==="1")&&(G.ssl=!0),G.ssl==="0"&&(G.ssl=!1),(G.sslcert||G.sslkey||G.sslrootcert||G.sslmode)&&(G.ssl={}),G.sslcert&&(G.ssl.cert=J.readFileSync(G.sslcert).toString()),G.sslkey&&(G.ssl.key=J.readFileSync(G.sslkey).toString()),G.sslrootcert&&(G.ssl.ca=J.readFileSync(G.sslrootcert).toString()),G.sslmode){case"disable":{G.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{G.ssl.rejectUnauthorized=!1;break}}return G}V(X,"parse"),$.exports=X,X.parse=X}),D9=o((W,$)=>{u();var Z=(gZ(),B1(g7)),J=I4(),X=mZ().parse,Y=V(function(w,R,S){return S===void 0?S=r.env["PG"+w.toUpperCase()]:S===!1||(S=r.env[S]),R[w]||S||J[w]},"val"),L=V(function(){switch(r.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return J.ssl},"readSSLConfigFromEnvironment"),G=V(function(w){return"'"+(""+w).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),U=V(function(w,R,S){var F=R[S];F!=null&&w.push(S+"="+G(F))},"add"),D=class{constructor(R){R=typeof R=="string"?X(R):R||{},R.connectionString&&(R=Object.assign({},R,X(R.connectionString))),this.user=Y("user",R),this.database=Y("database",R),this.database===void 0&&(this.database=this.user),this.port=parseInt(Y("port",R),10),this.host=Y("host",R),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:Y("password",R)}),this.binary=Y("binary",R),this.options=Y("options",R),this.ssl=typeof R.ssl>"u"?L():R.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=Y("client_encoding",R),this.replication=Y("replication",R),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=Y("application_name",R,"PGAPPNAME"),this.fallback_application_name=Y("fallback_application_name",R,!1),this.statement_timeout=Y("statement_timeout",R,!1),this.lock_timeout=Y("lock_timeout",R,!1),this.idle_in_transaction_session_timeout=Y("idle_in_transaction_session_timeout",R,!1),this.query_timeout=Y("query_timeout",R,!1),R.connectionTimeoutMillis===void 0?this.connect_timeout=r.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(R.connectionTimeoutMillis/1000),R.keepAlive===!1?this.keepalives=0:R.keepAlive===!0&&(this.keepalives=1),typeof R.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(R.keepAliveInitialDelayMillis/1000))}getLibpqConnectionString(R){var S=[];U(S,this,"user"),U(S,this,"password"),U(S,this,"port"),U(S,this,"application_name"),U(S,this,"fallback_application_name"),U(S,this,"connect_timeout"),U(S,this,"options");var F=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(U(S,F,"sslmode"),U(S,F,"sslca"),U(S,F,"sslkey"),U(S,F,"sslcert"),U(S,F,"sslrootcert"),this.database&&S.push("dbname="+G(this.database)),this.replication&&S.push("replication="+G(this.replication)),this.host&&S.push("host="+G(this.host)),this.isDomainSocket)return R(null,S.join(" "));this.client_encoding&&S.push("client_encoding="+G(this.client_encoding)),Z.lookup(this.host,function(K,Q){return K?R(K,null):(S.push("hostaddr="+G(Q)),R(null,S.join(" ")))})}};V(D,"ConnectionParameters");var P=D;$.exports=P}),cZ=o((W,$)=>{u();var Z=b4(),J=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,X=class{constructor(G,U){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=U,this.RowCtor=null,this.rowAsArray=G==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(G){var U;G.text?U=J.exec(G.text):U=J.exec(G.command),U&&(this.command=U[1],U[3]?(this.oid=parseInt(U[2],10),this.rowCount=parseInt(U[3],10)):U[2]&&(this.rowCount=parseInt(U[2],10)))}_parseRowAsArray(G){for(var U=Array(G.length),D=0,P=G.length;D<P;D++){var w=G[D];w!==null?U[D]=this._parsers[D](w):U[D]=null}return U}parseRow(G){for(var U={},D=0,P=G.length;D<P;D++){var w=G[D],R=this.fields[D].name;w!==null?U[R]=this._parsers[D](w):U[R]=null}return U}addRow(G){this.rows.push(G)}addFields(G){this.fields=G,this.fields.length&&(this._parsers=Array(G.length));for(var U=0;U<G.length;U++){var D=G[U];this._types?this._parsers[U]=this._types.getTypeParser(D.dataTypeID,D.format||"text"):this._parsers[U]=Z.getTypeParser(D.dataTypeID,D.format||"text")}}};V(X,"Result");var Y=X;$.exports=Y}),uZ=o((W,$)=>{u();var{EventEmitter:Z}=S8(),J=cZ(),X=y4(),Y=class extends Z{constructor(U,D,P){super(),U=X.normalizeQueryConfig(U,D,P),this.text=U.text,this.values=U.values,this.rows=U.rows,this.types=U.types,this.name=U.name,this.binary=U.binary,this.portal=U.portal||"",this.callback=U.callback,this._rowMode=U.rowMode,r.domain&&U.callback&&(this.callback=r.domain.bind(U.callback)),this._result=new J(this._rowMode,this.types),this._results=this._result,this.isPreparedStatement=!1,this._canceledDueToError=!1,this._promise=null}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new J(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(U){this._checkForMultirow(),this._result.addFields(U.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(U){let D;if(!this._canceledDueToError){try{D=this._result.parseRow(U.fields)}catch(P){this._canceledDueToError=P;return}this.emit("row",D,this._result),this._accumulateRows&&this._result.addRow(D)}}handleCommandComplete(U,D){this._checkForMultirow(),this._result.addCommandComplete(U),this.rows&&D.sync()}handleEmptyQuery(U){this.rows&&U.sync()}handleError(U,D){if(this._canceledDueToError&&(U=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(U);this.emit("error",U)}handleReadyForQuery(U){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,U);if(this.callback)try{this.callback(null,this._results)}catch(D){r.nextTick(()=>{throw D})}this.emit("end",this._results)}submit(U){if(typeof this.text!="string"&&typeof this.name!="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let D=U.parsedStatements[this.name];return this.text&&D&&this.text!==D?Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(U):U.query(this.text),null)}hasBeenParsed(U){return this.name&&U.parsedStatements[this.name]}handlePortalSuspended(U){this._getRows(U,this.rows)}_getRows(U,D){U.execute({portal:this.portal,rows:D}),D?U.flush():U.sync()}prepare(U){this.isPreparedStatement=!0,this.hasBeenParsed(U)||U.parse({text:this.text,name:this.name,types:this.types});try{U.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:X.prepareValue})}catch(D){this.handleError(D,U);return}U.describe({type:"P",name:this.portal||""}),this._getRows(U,this.rows)}handleCopyInResponse(U){U.sendCopyFail("No source stream defined")}handleCopyData(U,D){}};V(Y,"Query");var L=Y;$.exports=L}),c7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.NoticeMessage=W.DataRowMessage=W.CommandCompleteMessage=W.ReadyForQueryMessage=W.NotificationResponseMessage=W.BackendKeyDataMessage=W.AuthenticationMD5Password=W.ParameterStatusMessage=W.ParameterDescriptionMessage=W.RowDescriptionMessage=W.Field=W.CopyResponse=W.CopyDataMessage=W.DatabaseError=W.copyDone=W.emptyQuery=W.replicationStart=W.portalSuspended=W.noData=W.closeComplete=W.bindComplete=W.parseComplete=void 0,W.parseComplete={name:"parseComplete",length:5},W.bindComplete={name:"bindComplete",length:5},W.closeComplete={name:"closeComplete",length:5},W.noData={name:"noData",length:5},W.portalSuspended={name:"portalSuspended",length:5},W.replicationStart={name:"replicationStart",length:4},W.emptyQuery={name:"emptyQuery",length:4},W.copyDone={name:"copyDone",length:4};var $=class extends Error{constructor(b,g,p){super(b),this.length=g,this.name=p}};V($,"DatabaseError");var Z=$;W.DatabaseError=Z;var J=class{constructor(b,g){this.length=b,this.chunk=g,this.name="copyData"}};V(J,"CopyDataMessage");var X=J;W.CopyDataMessage=X;var Y=class{constructor(b,g,p,d){this.length=b,this.name=g,this.binary=p,this.columnTypes=Array(d)}};V(Y,"CopyResponse");var L=Y;W.CopyResponse=L;var G=class{constructor(b,g,p,d,J1,s,s1){this.name=b,this.tableID=g,this.columnID=p,this.dataTypeID=d,this.dataTypeSize=J1,this.dataTypeModifier=s,this.format=s1}};V(G,"Field");var U=G;W.Field=U;var D=class{constructor(b,g){this.length=b,this.fieldCount=g,this.name="rowDescription",this.fields=Array(this.fieldCount)}};V(D,"RowDescriptionMessage");var P=D;W.RowDescriptionMessage=P;var w=class{constructor(b,g){this.length=b,this.parameterCount=g,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}};V(w,"ParameterDescriptionMessage");var R=w;W.ParameterDescriptionMessage=R;var S=class{constructor(b,g,p){this.length=b,this.parameterName=g,this.parameterValue=p,this.name="parameterStatus"}};V(S,"ParameterStatusMessage");var F=S;W.ParameterStatusMessage=F;var K=class{constructor(b,g){this.length=b,this.salt=g,this.name="authenticationMD5Password"}};V(K,"AuthenticationMD5Password");var Q=K;W.AuthenticationMD5Password=Q;var _=class{constructor(b,g,p){this.length=b,this.processID=g,this.secretKey=p,this.name="backendKeyData"}};V(_,"BackendKeyDataMessage");var E=_;W.BackendKeyDataMessage=E;var v=class{constructor(b,g,p,d){this.length=b,this.processId=g,this.channel=p,this.payload=d,this.name="notification"}};V(v,"NotificationResponseMessage");var x=v;W.NotificationResponseMessage=x;var q=class{constructor(b,g){this.length=b,this.status=g,this.name="readyForQuery"}};V(q,"ReadyForQueryMessage");var h=q;W.ReadyForQueryMessage=h;var N=class{constructor(b,g){this.length=b,this.text=g,this.name="commandComplete"}};V(N,"CommandCompleteMessage");var A=N;W.CommandCompleteMessage=A;var f=class{constructor(b,g){this.length=b,this.fields=g,this.name="dataRow",this.fieldCount=g.length}};V(f,"DataRowMessage");var B=f;W.DataRowMessage=B;var C=class{constructor(b,g){this.length=b,this.message=g,this.name="notice"}};V(C,"NoticeMessage");var c=C;W.NoticeMessage=c}),lZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Writer=void 0;var $=class{constructor(X=256){this.size=X,this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(X)}ensure(X){if(this.buffer.length-this.offset<X){let Y=this.buffer,L=Y.length+(Y.length>>1)+X;this.buffer=i.allocUnsafe(L),Y.copy(this.buffer)}}addInt32(X){return this.ensure(4),this.buffer[this.offset++]=X>>>24&255,this.buffer[this.offset++]=X>>>16&255,this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addInt16(X){return this.ensure(2),this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addCString(X){if(!X)this.ensure(1);else{let Y=i.byteLength(X);this.ensure(Y+1),this.buffer.write(X,this.offset,"utf-8"),this.offset+=Y}return this.buffer[this.offset++]=0,this}addString(X=""){let Y=i.byteLength(X);return this.ensure(Y),this.buffer.write(X,this.offset),this.offset+=Y,this}add(X){return this.ensure(X.length),X.copy(this.buffer,this.offset),this.offset+=X.length,this}join(X){if(X){this.buffer[this.headerPosition]=X;let Y=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(Y,this.headerPosition+1)}return this.buffer.slice(X?0:5,this.offset)}flush(X){let Y=this.join(X);return this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(this.size),Y}};V($,"Writer");var Z=$;W.Writer=Z}),pZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.serialize=void 0;var $=lZ(),Z=new $.Writer,J=V((b)=>{Z.addInt16(3).addInt16(0);for(let d of Object.keys(b))Z.addCString(d).addCString(b[d]);Z.addCString("client_encoding").addCString("UTF8");let g=Z.addCString("").flush(),p=g.length+4;return new $.Writer().addInt32(p).add(g).flush()},"startup"),X=V(()=>{let b=i.allocUnsafe(8);return b.writeInt32BE(8,0),b.writeInt32BE(80877103,4),b},"requestSsl"),Y=V((b)=>Z.addCString(b).flush(112),"password"),L=V(function(b,g){return Z.addCString(b).addInt32(i.byteLength(g)).addString(g),Z.flush(112)},"sendSASLInitialResponseMessage"),G=V(function(b){return Z.addString(b).flush(112)},"sendSCRAMClientFinalMessage"),U=V((b)=>Z.addCString(b).flush(81),"query"),D=[],P=V((b)=>{let g=b.name||"";g.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",g,g.length),console.error("This can cause conflicts and silent errors executing queries"));let p=b.types||D,d=p.length,J1=Z.addCString(g).addCString(b.text).addInt16(d);for(let s=0;s<d;s++)J1.addInt32(p[s]);return Z.flush(80)},"parse"),w=new $.Writer,R=V(function(b,g){for(let p=0;p<b.length;p++){let d=g?g(b[p],p):b[p];d==null?(Z.addInt16(0),w.addInt32(-1)):d instanceof i?(Z.addInt16(1),w.addInt32(d.length),w.add(d)):(Z.addInt16(0),w.addInt32(i.byteLength(d)),w.addString(d))}},"writeValues"),S=V((b={})=>{let g=b.portal||"",p=b.statement||"",d=b.binary||!1,J1=b.values||D,s=J1.length;return Z.addCString(g).addCString(p),Z.addInt16(s),R(J1,b.valueMapper),Z.addInt16(s),Z.add(w.flush()),Z.addInt16(d?1:0),Z.flush(66)},"bind"),F=i.from([69,0,0,0,9,0,0,0,0,0]),K=V((b)=>{if(!b||!b.portal&&!b.rows)return F;let g=b.portal||"",p=b.rows||0,d=i.byteLength(g),J1=4+d+1+4,s=i.allocUnsafe(1+J1);return s[0]=69,s.writeInt32BE(J1,1),s.write(g,5,"utf-8"),s[d+5]=0,s.writeUInt32BE(p,s.length-4),s},"execute"),Q=V((b,g)=>{let p=i.allocUnsafe(16);return p.writeInt32BE(16,0),p.writeInt16BE(1234,4),p.writeInt16BE(5678,6),p.writeInt32BE(b,8),p.writeInt32BE(g,12),p},"cancel"),_=V((b,g)=>{let p=4+i.byteLength(g)+1,d=i.allocUnsafe(1+p);return d[0]=b,d.writeInt32BE(p,1),d.write(g,5,"utf-8"),d[p]=0,d},"cstringMessage"),E=Z.addCString("P").flush(68),v=Z.addCString("S").flush(68),x=V((b)=>b.name?_(68,`${b.type}${b.name||""}`):b.type==="P"?E:v,"describe"),q=V((b)=>{let g=`${b.type}${b.name||""}`;return _(67,g)},"close"),h=V((b)=>Z.add(b).flush(100),"copyData"),N=V((b)=>_(102,b),"copyFail"),A=V((b)=>i.from([b,0,0,0,4]),"codeOnlyBuffer"),f=A(72),B=A(83),C=A(88),c=A(99),m={startup:J,password:Y,requestSsl:X,sendSASLInitialResponseMessage:L,sendSCRAMClientFinalMessage:G,query:U,parse:P,bind:S,execute:K,describe:x,close:q,flush:V(()=>f,"flush"),sync:V(()=>B,"sync"),end:V(()=>C,"end"),copyData:h,copyDone:V(()=>c,"copyDone"),copyFail:N,cancel:Q};W.serialize=m}),iZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.BufferReader=void 0;var $=i.allocUnsafe(0),Z=class{constructor(Y=0){this.offset=Y,this.buffer=$,this.encoding="utf-8"}setBuffer(Y,L){this.offset=Y,this.buffer=L}int16(){let Y=this.buffer.readInt16BE(this.offset);return this.offset+=2,Y}byte(){let Y=this.buffer[this.offset];return this.offset++,Y}int32(){let Y=this.buffer.readInt32BE(this.offset);return this.offset+=4,Y}uint32(){let Y=this.buffer.readUInt32BE(this.offset);return this.offset+=4,Y}string(Y){let L=this.buffer.toString(this.encoding,this.offset,this.offset+Y);return this.offset+=Y,L}cstring(){let Y=this.offset,L=Y;for(;this.buffer[L++]!==0;);return this.offset=L,this.buffer.toString(this.encoding,Y,L-1)}bytes(Y){let L=this.buffer.slice(this.offset,this.offset+Y);return this.offset+=Y,L}};V(Z,"BufferReader");var J=Z;W.BufferReader=J}),tZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Parser=void 0;var $=c7(),Z=iZ(),J=1,X=4,Y=J+X,L=i.allocUnsafe(0),G=class{constructor(P){if(this.buffer=L,this.bufferLength=0,this.bufferOffset=0,this.reader=new Z.BufferReader,P?.mode==="binary")throw Error("Binary mode not supported yet");this.mode=P?.mode||"text"}parse(P,w){this.mergeBuffer(P);let R=this.bufferOffset+this.bufferLength,S=this.bufferOffset;for(;S+Y<=R;){let F=this.buffer[S],K=this.buffer.readUInt32BE(S+J),Q=J+K;if(Q+S<=R){let _=this.handlePacket(S+Y,F,K,this.buffer);w(_),S+=Q}else break}S===R?(this.buffer=L,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=R-S,this.bufferOffset=S)}mergeBuffer(P){if(this.bufferLength>0){let w=this.bufferLength+P.byteLength;if(w+this.bufferOffset>this.buffer.byteLength){let R;if(w<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)R=this.buffer;else{let S=this.buffer.byteLength*2;for(;w>=S;)S*=2;R=i.allocUnsafe(S)}this.buffer.copy(R,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=R,this.bufferOffset=0}P.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=w}else this.buffer=P,this.bufferOffset=0,this.bufferLength=P.byteLength}handlePacket(P,w,R,S){switch(w){case 50:return $.bindComplete;case 49:return $.parseComplete;case 51:return $.closeComplete;case 110:return $.noData;case 115:return $.portalSuspended;case 99:return $.copyDone;case 87:return $.replicationStart;case 73:return $.emptyQuery;case 68:return this.parseDataRowMessage(P,R,S);case 67:return this.parseCommandCompleteMessage(P,R,S);case 90:return this.parseReadyForQueryMessage(P,R,S);case 65:return this.parseNotificationMessage(P,R,S);case 82:return this.parseAuthenticationResponse(P,R,S);case 83:return this.parseParameterStatusMessage(P,R,S);case 75:return this.parseBackendKeyData(P,R,S);case 69:return this.parseErrorMessage(P,R,S,"error");case 78:return this.parseErrorMessage(P,R,S,"notice");case 84:return this.parseRowDescriptionMessage(P,R,S);case 116:return this.parseParameterDescriptionMessage(P,R,S);case 71:return this.parseCopyInMessage(P,R,S);case 72:return this.parseCopyOutMessage(P,R,S);case 100:return this.parseCopyData(P,R,S);default:return new $.DatabaseError("received invalid response: "+w.toString(16),R,"error")}}parseReadyForQueryMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.string(1);return new $.ReadyForQueryMessage(w,S)}parseCommandCompleteMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.cstring();return new $.CommandCompleteMessage(w,S)}parseCopyData(P,w,R){let S=R.slice(P,P+(w-4));return new $.CopyDataMessage(w,S)}parseCopyInMessage(P,w,R){return this.parseCopyMessage(P,w,R,"copyInResponse")}parseCopyOutMessage(P,w,R){return this.parseCopyMessage(P,w,R,"copyOutResponse")}parseCopyMessage(P,w,R,S){this.reader.setBuffer(P,R);let F=this.reader.byte()!==0,K=this.reader.int16(),Q=new $.CopyResponse(w,S,F,K);for(let _=0;_<K;_++)Q.columnTypes[_]=this.reader.int16();return Q}parseNotificationMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int32(),F=this.reader.cstring(),K=this.reader.cstring();return new $.NotificationResponseMessage(w,S,F,K)}parseRowDescriptionMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int16(),F=new $.RowDescriptionMessage(w,S);for(let K=0;K<S;K++)F.fields[K]=this.parseField();return F}parseField(){let P=this.reader.cstring(),w=this.reader.uint32(),R=this.reader.int16(),S=this.reader.uint32(),F=this.reader.int16(),K=this.reader.int32(),Q=this.reader.int16()===0?"text":"binary";return new $.Field(P,w,R,S,F,K,Q)}parseParameterDescriptionMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int16(),F=new $.ParameterDescriptionMessage(w,S);for(let K=0;K<S;K++)F.dataTypeIDs[K]=this.reader.int32();return F}parseDataRowMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int16(),F=Array(S);for(let K=0;K<S;K++){let Q=this.reader.int32();F[K]=Q===-1?null:this.reader.string(Q)}return new $.DataRowMessage(w,F)}parseParameterStatusMessage(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.cstring(),F=this.reader.cstring();return new $.ParameterStatusMessage(w,S,F)}parseBackendKeyData(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int32(),F=this.reader.int32();return new $.BackendKeyDataMessage(w,S,F)}parseAuthenticationResponse(P,w,R){this.reader.setBuffer(P,R);let S=this.reader.int32(),F={name:"authenticationOk",length:w};switch(S){case 0:break;case 3:F.length===8&&(F.name="authenticationCleartextPassword");break;case 5:if(F.length===12){F.name="authenticationMD5Password";let K=this.reader.bytes(4);return new $.AuthenticationMD5Password(w,K)}break;case 10:{F.name="authenticationSASL",F.mechanisms=[];let K;do K=this.reader.cstring(),K&&F.mechanisms.push(K);while(K)}break;case 11:F.name="authenticationSASLContinue",F.data=this.reader.string(w-8);break;case 12:F.name="authenticationSASLFinal",F.data=this.reader.string(w-8);break;default:throw Error("Unknown authenticationOk message type "+S)}return F}parseErrorMessage(P,w,R,S){this.reader.setBuffer(P,R);let F={},K=this.reader.string(1);for(;K!=="\x00";)F[K]=this.reader.cstring(),K=this.reader.string(1);let Q=F.M,_=S==="notice"?new $.NoticeMessage(w,Q):new $.DatabaseError(Q,w,S);return _.severity=F.S,_.code=F.C,_.detail=F.D,_.hint=F.H,_.position=F.P,_.internalPosition=F.p,_.internalQuery=F.q,_.where=F.W,_.schema=F.s,_.table=F.t,_.column=F.c,_.dataType=F.d,_.constraint=F.n,_.file=F.F,_.line=F.L,_.routine=F.R,_}};V(G,"Parser");var U=G;W.Parser=U}),u7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.DatabaseError=W.serialize=W.parse=void 0;var $=c7();Object.defineProperty(W,"DatabaseError",{enumerable:!0,get:V(function(){return $.DatabaseError},"get")});var Z=pZ();Object.defineProperty(W,"serialize",{enumerable:!0,get:V(function(){return Z.serialize},"get")});var J=tZ();function X(Y,L){let G=new J.Parser;return Y.on("data",(U)=>G.parse(U,L)),new Promise((U)=>Y.on("end",()=>U()))}V(X,"parse"),W.parse=X}),l7={};S0(l7,{connect:()=>p7});function p7({socket:W,servername:$}){return W.startTls($),W}var aZ=d1(()=>{u(),V(p7,"connect")}),i7=o((W,$)=>{u();var Z=(tW(),B1(Q7)),J=S8().EventEmitter,{parse:X,serialize:Y}=u7(),L=Y.flush(),G=Y.sync(),U=Y.end(),D=class extends J{constructor(R){super(),R=R||{},this.stream=R.stream||new Z.Socket,this._keepAlive=R.keepAlive,this._keepAliveInitialDelayMillis=R.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=R.ssl||!1,this._ending=!1,this._emitMessage=!1;var S=this;this.on("newListener",function(F){F==="message"&&(S._emitMessage=!0)})}connect(R,S){var F=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(R,S),this.stream.once("connect",function(){F._keepAlive&&F.stream.setKeepAlive(!0,F._keepAliveInitialDelayMillis),F.emit("connect")});let K=V(function(Q){F._ending&&(Q.code==="ECONNRESET"||Q.code==="EPIPE")||F.emit("error",Q)},"reportStreamError");if(this.stream.on("error",K),this.stream.on("close",function(){F.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(Q){var _=Q.toString("utf8");switch(_){case"S":break;case"N":return F.stream.end(),F.emit("error",Error("The server does not support SSL connections"));default:return F.stream.end(),F.emit("error",Error("There was an error establishing an SSL connection"))}var E=(aZ(),B1(l7));let v={socket:F.stream};F.ssl!==!0&&(Object.assign(v,F.ssl),("key"in F.ssl)&&(v.key=F.ssl.key)),Z.isIP(S)===0&&(v.servername=S);try{F.stream=E.connect(v)}catch(x){return F.emit("error",x)}F.attachListeners(F.stream),F.stream.on("error",K),F.emit("sslconnect")})}attachListeners(R){R.on("end",()=>{this.emit("end")}),X(R,(S)=>{var F=S.name==="error"?"errorMessage":S.name;this._emitMessage&&this.emit("message",S),this.emit(F,S)})}requestSsl(){this.stream.write(Y.requestSsl())}startup(R){this.stream.write(Y.startup(R))}cancel(R,S){this._send(Y.cancel(R,S))}password(R){this._send(Y.password(R))}sendSASLInitialResponseMessage(R,S){this._send(Y.sendSASLInitialResponseMessage(R,S))}sendSCRAMClientFinalMessage(R){this._send(Y.sendSCRAMClientFinalMessage(R))}_send(R){return this.stream.writable?this.stream.write(R):!1}query(R){this._send(Y.query(R))}parse(R){this._send(Y.parse(R))}bind(R){this._send(Y.bind(R))}execute(R){this._send(Y.execute(R))}flush(){this.stream.writable&&this.stream.write(L)}sync(){this._ending=!0,this._send(L),this._send(G)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(U,()=>{this.stream.end()})}close(R){this._send(Y.close(R))}describe(R){this._send(Y.describe(R))}sendCopyFromChunk(R){this._send(Y.copyData(R))}endCopyFrom(){this._send(Y.copyDone())}sendCopyFail(R){this._send(Y.copyFail(R))}};V(D,"Connection");var P=D;$.exports=P}),dZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(g4(),B1(aW)),X=y4(),Y=xZ(),L=yZ(),G=z9(),U=D9(),D=uZ(),P=I4(),w=i7(),R=class extends Z{constructor(K){super(),this.connectionParameters=new U(K),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var Q=K||{};this._Promise=Q.Promise||B4.Promise,this._types=new G(Q.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=Q.connection||new w({stream:Q.stream,ssl:this.connectionParameters.ssl,keepAlive:Q.keepAlive||!1,keepAliveInitialDelayMillis:Q.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=Q.binary||P.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=Q.connectionTimeoutMillis||0}_errorAllQueries(K){let Q=V((_)=>{r.nextTick(()=>{_.handleError(K,this.connection)})},"enqueueError");this.activeQuery&&(Q(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(Q),this.queryQueue.length=0}_connect(K){var Q=this,_=this.connection;if(this._connectionCallback=K,this._connecting||this._connected){let E=Error("Client has already been connected. You cannot reuse a client.");r.nextTick(()=>{K(E)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{_._ending=!0,_.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){Q.ssl?_.requestSsl():_.startup(Q.getStartupConf())}),_.on("sslconnect",function(){_.startup(Q.getStartupConf())}),this._attachListeners(_),_.once("end",()=>{let E=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(E),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(E):this._handleErrorEvent(E):this._connectionError||this._handleErrorEvent(E)),r.nextTick(()=>{this.emit("end")})})}connect(K){if(K){this._connect(K);return}return new this._Promise((Q,_)=>{this._connect((E)=>{E?_(E):Q()})})}_attachListeners(K){K.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),K.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),K.on("authenticationSASL",this._handleAuthSASL.bind(this)),K.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),K.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),K.on("backendKeyData",this._handleBackendKeyData.bind(this)),K.on("error",this._handleErrorEvent.bind(this)),K.on("errorMessage",this._handleErrorMessage.bind(this)),K.on("readyForQuery",this._handleReadyForQuery.bind(this)),K.on("notice",this._handleNotice.bind(this)),K.on("rowDescription",this._handleRowDescription.bind(this)),K.on("dataRow",this._handleDataRow.bind(this)),K.on("portalSuspended",this._handlePortalSuspended.bind(this)),K.on("emptyQuery",this._handleEmptyQuery.bind(this)),K.on("commandComplete",this._handleCommandComplete.bind(this)),K.on("parseComplete",this._handleParseComplete.bind(this)),K.on("copyInResponse",this._handleCopyInResponse.bind(this)),K.on("copyData",this._handleCopyData.bind(this)),K.on("notification",this._handleNotification.bind(this))}_checkPgPass(K){let Q=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then((_)=>{if(_!==void 0){if(typeof _!="string"){Q.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=_}else this.connectionParameters.password=this.password=null;K()}).catch((_)=>{Q.emit("error",_)}):this.password!==null?K():L(this.connectionParameters,(_)=>{_!==void 0&&(this.connectionParameters.password=this.password=_),K()})}_handleAuthCleartextPassword(K){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(K){this._checkPgPass(()=>{let Q=X.postgresMd5PasswordHash(this.user,this.password,K.salt);this.connection.password(Q)})}_handleAuthSASL(K){this._checkPgPass(()=>{this.saslSession=Y.startSession(K.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(K){Y.continueSession(this.saslSession,this.password,K.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}_handleAuthSASLFinal(K){Y.finalizeSession(this.saslSession,K.data),this.saslSession=null}_handleBackendKeyData(K){this.processID=K.processID,this.secretKey=K.secretKey}_handleReadyForQuery(K){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:Q}=this;this.activeQuery=null,this.readyForQuery=!0,Q&&Q.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(K){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(K);this.emit("error",K)}}_handleErrorEvent(K){if(this._connecting)return this._handleErrorWhileConnecting(K);this._queryable=!1,this._errorAllQueries(K),this.emit("error",K)}_handleErrorMessage(K){if(this._connecting)return this._handleErrorWhileConnecting(K);let Q=this.activeQuery;if(!Q){this._handleErrorEvent(K);return}this.activeQuery=null,Q.handleError(K,this.connection)}_handleRowDescription(K){this.activeQuery.handleRowDescription(K)}_handleDataRow(K){this.activeQuery.handleDataRow(K)}_handlePortalSuspended(K){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(K){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(K){this.activeQuery.handleCommandComplete(K,this.connection)}_handleParseComplete(K){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(K){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(K){this.activeQuery.handleCopyData(K,this.connection)}_handleNotification(K){this.emit("notification",K)}_handleNotice(K){this.emit("notice",K)}getStartupConf(){var K=this.connectionParameters,Q={user:K.user,database:K.database},_=K.application_name||K.fallback_application_name;return _&&(Q.application_name=_),K.replication&&(Q.replication=""+K.replication),K.statement_timeout&&(Q.statement_timeout=String(parseInt(K.statement_timeout,10))),K.lock_timeout&&(Q.lock_timeout=String(parseInt(K.lock_timeout,10))),K.idle_in_transaction_session_timeout&&(Q.idle_in_transaction_session_timeout=String(parseInt(K.idle_in_transaction_session_timeout,10))),K.options&&(Q.options=K.options),Q}cancel(K,Q){if(K.activeQuery===Q){var _=this.connection;this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){_.cancel(K.processID,K.secretKey)})}else K.queryQueue.indexOf(Q)!==-1&&K.queryQueue.splice(K.queryQueue.indexOf(Q),1)}setTypeParser(K,Q,_){return this._types.setTypeParser(K,Q,_)}getTypeParser(K,Q){return this._types.getTypeParser(K,Q)}escapeIdentifier(K){return'"'+K.replace(/"/g,'""')+'"'}escapeLiteral(K){for(var Q=!1,_="'",E=0;E<K.length;E++){var v=K[E];v==="'"?_+=v+v:v==="\\"?(_+=v+v,Q=!0):_+=v}return _+="'",Q===!0&&(_=" E"+_),_}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let K=this.activeQuery.submit(this.connection);K&&r.nextTick(()=>{this.activeQuery.handleError(K,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(K,Q,_){var E,v,x,q,h;if(K==null)throw TypeError("Client was passed a null or undefined query");return typeof K.submit=="function"?(x=K.query_timeout||this.connectionParameters.query_timeout,v=E=K,typeof Q=="function"&&(E.callback=E.callback||Q)):(x=this.connectionParameters.query_timeout,E=new D(K,Q,_),E.callback||(v=new this._Promise((N,A)=>{E.callback=(f,B)=>f?A(f):N(B)}))),x&&(h=E.callback,q=setTimeout(()=>{var N=Error("Query read timeout");r.nextTick(()=>{E.handleError(N,this.connection)}),h(N),E.callback=()=>{};var A=this.queryQueue.indexOf(E);A>-1&&this.queryQueue.splice(A,1),this._pulseQueryQueue()},x),E.callback=(N,A)=>{clearTimeout(q),h(N,A)}),this.binary&&!E.binary&&(E.binary=!0),E._result&&!E._result._types&&(E._result._types=this._types),this._queryable?this._ending?(r.nextTick(()=>{E.handleError(Error("Client was closed and is not queryable"),this.connection)}),v):(this.queryQueue.push(E),this._pulseQueryQueue(),v):(r.nextTick(()=>{E.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),v)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(K){if(this._ending=!0,!this.connection._connecting)if(K)K();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),K)this.connection.once("end",K);else return new this._Promise((Q)=>{this.connection.once("end",Q)})}};V(R,"Client");var S=R;S.Query=D,$.exports=S}),sZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=V(function(){},"NOOP"),X=V((F,K)=>{let Q=F.findIndex(K);return Q===-1?void 0:F.splice(Q,1)[0]},"removeWhere"),Y=class{constructor(K,Q,_){this.client=K,this.idleListener=Q,this.timeoutId=_}};V(Y,"IdleItem");var L=Y,G=class{constructor(K){this.callback=K}};V(G,"PendingItem");var U=G;function D(){throw Error("Release called on client which has already been released to the pool.")}V(D,"throwOnDoubleRelease");function P(F,K){if(K)return{callback:K,result:void 0};let Q,_,E=V(function(x,q){x?Q(x):_(q)},"cb"),v=new F(function(x,q){_=x,Q=q}).catch((x)=>{throw Error.captureStackTrace(x),x});return{callback:E,result:v}}V(P,"promisify");function w(F,K){return V(function Q(_){_.client=K,K.removeListener("error",Q),K.on("error",()=>{F.log("additional client error after disconnection due to error",_)}),F._remove(K),F.emit("error",_,K)},"idleListener")}V(w,"makeIdleListener");var R=class extends Z{constructor(K,Q){super(),this.options=Object.assign({},K),K!=null&&"password"in K&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:K.password}),K!=null&&K.ssl&&K.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Q||m4().Client,this.Promise=this.options.Promise||B4.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map((Q)=>{this._remove(Q.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let K=this._pendingQueue.shift();if(this._idle.length){let Q=this._idle.pop();clearTimeout(Q.timeoutId);let _=Q.client;_.ref&&_.ref();let E=Q.idleListener;return this._acquireClient(_,K,E,!1)}if(!this._isFull())return this.newClient(K);throw Error("unexpected condition")}_remove(K){let Q=X(this._idle,(_)=>_.client===K);Q!==void 0&&clearTimeout(Q.timeoutId),this._clients=this._clients.filter((_)=>_!==K),K.end(),this.emit("remove",K)}connect(K){if(this.ending){let E=Error("Cannot use a pool after calling end on the pool");return K?K(E):this.Promise.reject(E)}let Q=P(this.Promise,K),_=Q.result;if(this._isFull()||this._idle.length){if(this._idle.length&&r.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new U(Q.callback)),_;let E=V((q,h,N)=>{clearTimeout(x),Q.callback(q,h,N)},"queueCallback"),v=new U(E),x=setTimeout(()=>{X(this._pendingQueue,(q)=>q.callback===E),v.timedOut=!0,Q.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return x.unref&&x.unref(),this._pendingQueue.push(v),_}return this.newClient(new U(Q.callback)),_}newClient(K){let Q=new this.Client(this.options);this._clients.push(Q);let _=w(this,Q);this.log("checking client timeout");let E,v=!1;this.options.connectionTimeoutMillis&&(E=setTimeout(()=>{this.log("ending client due to timeout"),v=!0,Q.connection?Q.connection.stream.destroy():Q.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),Q.connect((x)=>{if(E&&clearTimeout(E),Q.on("error",_),x)this.log("client failed to connect",x),this._clients=this._clients.filter((q)=>q!==Q),v&&(x=Error("Connection terminated due to connection timeout",{cause:x})),this._pulseQueue(),K.timedOut||K.callback(x,void 0,J);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let q=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(Q),this._idle.findIndex((h)=>h.client===Q)!==-1&&this._acquireClient(Q,new U((h,N,A)=>A()),_,!1)},this.options.maxLifetimeSeconds*1000);q.unref(),Q.once("end",()=>clearTimeout(q))}return this._acquireClient(Q,K,_,!0)}})}_acquireClient(K,Q,_,E){E&&this.emit("connect",K),this.emit("acquire",K),K.release=this._releaseOnce(K,_),K.removeListener("error",_),Q.timedOut?E&&this.options.verify?this.options.verify(K,K.release):K.release():E&&this.options.verify?this.options.verify(K,(v)=>{if(v)return K.release(v),Q.callback(v,void 0,J);Q.callback(void 0,K,K.release)}):Q.callback(void 0,K,K.release)}_releaseOnce(K,Q){let _=!1;return(E)=>{_&&D(),_=!0,this._release(K,Q,E)}}_release(K,Q,_){if(K.on("error",Q),K._poolUseCount=(K._poolUseCount||0)+1,this.emit("release",_,K),_||this.ending||!K._queryable||K._ending||K._poolUseCount>=this.options.maxUses){K._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(K),this._pulseQueue();return}if(this._expired.has(K)){this.log("remove expired client"),this._expired.delete(K),this._remove(K),this._pulseQueue();return}let E;this.options.idleTimeoutMillis&&this._isAboveMin()&&(E=setTimeout(()=>{this.log("remove idle client"),this._remove(K)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&E.unref()),this.options.allowExitOnIdle&&K.unref(),this._idle.push(new L(K,Q,E)),this._pulseQueue()}query(K,Q,_){if(typeof K=="function"){let v=P(this.Promise,K);return K9(function(){return v.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),v.result}typeof Q=="function"&&(_=Q,Q=void 0);let E=P(this.Promise,_);return _=E.callback,this.connect((v,x)=>{if(v)return _(v);let q=!1,h=V((N)=>{q||(q=!0,x.release(N),_(N))},"onError");x.once("error",h),this.log("dispatching query");try{x.query(K,Q,(N,A)=>{if(this.log("query dispatched"),x.removeListener("error",h),!q)return q=!0,x.release(N),N?_(N):_(void 0,A)})}catch(N){return x.release(N),_(N)}}),E.result}end(K){if(this.log("ending"),this.ending){let _=Error("Called end on pool more than once");return K?K(_):this.Promise.reject(_)}this.ending=!0;let Q=P(this.Promise,K);return this._endCallback=Q.callback,this._pulseQueue(),Q.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((K,Q)=>K+(this._expired.has(Q)?1:0),0)}get totalCount(){return this._clients.length}};V(R,"Pool");var S=R;$.exports=S}),t7={};S0(t7,{default:()=>a7});var a7,nZ=d1(()=>{u(),a7={}}),rZ=o((W,$)=>{$.exports={name:"pg",version:"8.8.0",description:"PostgreSQL client - pure javascript & libpq with the same API",keywords:["database","libpq","pg","postgre","postgres","postgresql","rdbms"],homepage:"https://github.com/brianc/node-postgres",repository:{type:"git",url:"git://github.com/brianc/node-postgres.git",directory:"packages/pg"},author:"Brian Carlson <brian.m.carlson@gmail.com>",main:"./lib",dependencies:{"buffer-writer":"2.0.0","packet-reader":"1.0.0","pg-connection-string":"^2.5.0","pg-pool":"^3.5.2","pg-protocol":"^1.5.0","pg-types":"^2.1.0",pgpass:"1.x"},devDependencies:{async:"2.6.4",bluebird:"3.5.2",co:"4.6.0","pg-copy-streams":"0.3.0"},peerDependencies:{"pg-native":">=3.0.1"},peerDependenciesMeta:{"pg-native":{optional:!0}},scripts:{test:"make test-all"},files:["lib","SPONSORS.md"],license:"MIT",engines:{node:">= 8.0.0"},gitHead:"c99fb2c127ddf8d712500db2c7b9a5491a178655"}}),oZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(g4(),B1(aW)),X=y4(),Y=$.exports=function(G,U,D){Z.call(this),G=X.normalizeQueryConfig(G,U,D),this.text=G.text,this.values=G.values,this.name=G.name,this.callback=G.callback,this.state="new",this._arrayMode=G.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(P){P==="row"&&(this._emitRowEvents=!0)}.bind(this))};J.inherits(Y,Z);var L={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};Y.prototype.handleError=function(G){var U=this.native.pq.resultErrorFields();if(U)for(var D in U){var P=L[D]||D;G[P]=U[D]}this.callback?this.callback(G):this.emit("error",G),this.state="error"},Y.prototype.then=function(G,U){return this._getPromise().then(G,U)},Y.prototype.catch=function(G){return this._getPromise().catch(G)},Y.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(G,U){this._once("end",G),this._once("error",U)}.bind(this)),this._promise)},Y.prototype.submit=function(G){this.state="running";var U=this;this.native=G.native,G.native.arrayMode=this._arrayMode;var D=V(function(R,S,F){if(G.native.arrayMode=!1,K9(function(){U.emit("_done")}),R)return U.handleError(R);U._emitRowEvents&&(F.length>1?S.forEach((K,Q)=>{K.forEach((_)=>{U.emit("row",_,F[Q])})}):S.forEach(function(K){U.emit("row",K,F)})),U.state="end",U.emit("end",F),U.callback&&U.callback(null,F)},"after");if(r.domain&&(D=r.domain.bind(D)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var P=(this.values||[]).map(X.prepareValue);if(G.namedQueries[this.name]){if(this.text&&G.namedQueries[this.name]!==this.text){let R=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return D(R)}return G.native.execute(this.name,P,D)}return G.native.prepare(this.name,this.text,P.length,function(R){return R?D(R):(G.namedQueries[U.name]=U.text,U.native.execute(U.name,P,D))})}else if(this.values){if(!Array.isArray(this.values)){let R=Error("Query values must be an array");return D(R)}var w=this.values.map(X.prepareValue);G.native.query(this.text,w,D)}else G.native.query(this.text,D)}}),eZ=o((W,$)=>{u();var Z=(nZ(),B1(t7)),J=z9(),X=rZ(),Y=S8().EventEmitter,L=(g4(),B1(aW)),G=D9(),U=oZ(),D=$.exports=function(P){Y.call(this),P=P||{},this._Promise=P.Promise||B4.Promise,this._types=new J(P.types),this.native=new Z({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var w=this.connectionParameters=new G(P);this.user=w.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:w.password}),this.database=w.database,this.host=w.host,this.port=w.port,this.namedQueries={}};D.Query=U,L.inherits(D,Y),D.prototype._errorAllQueries=function(P){let w=V((R)=>{r.nextTick(()=>{R.native=this.native,R.handleError(P)})},"enqueueError");this._hasActiveQuery()&&(w(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(w),this._queryQueue.length=0},D.prototype._connect=function(P){var w=this;if(this._connecting){r.nextTick(()=>P(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(R,S){if(R)return P(R);w.native.connect(S,function(F){if(F)return w.native.end(),P(F);w._connected=!0,w.native.on("error",function(K){w._queryable=!1,w._errorAllQueries(K),w.emit("error",K)}),w.native.on("notification",function(K){w.emit("notification",{channel:K.relname,payload:K.extra})}),w.emit("connect"),w._pulseQueryQueue(!0),P()})})},D.prototype.connect=function(P){if(P){this._connect(P);return}return new this._Promise((w,R)=>{this._connect((S)=>{S?R(S):w()})})},D.prototype.query=function(P,w,R){var S,F,K,Q,_;if(P==null)throw TypeError("Client was passed a null or undefined query");if(typeof P.submit=="function")K=P.query_timeout||this.connectionParameters.query_timeout,F=S=P,typeof w=="function"&&(P.callback=w);else if(K=this.connectionParameters.query_timeout,S=new U(P,w,R),!S.callback){let E,v;F=new this._Promise((x,q)=>{E=x,v=q}),S.callback=(x,q)=>x?v(x):E(q)}return K&&(_=S.callback,Q=setTimeout(()=>{var E=Error("Query read timeout");r.nextTick(()=>{S.handleError(E,this.connection)}),_(E),S.callback=()=>{};var v=this._queryQueue.indexOf(S);v>-1&&this._queryQueue.splice(v,1),this._pulseQueryQueue()},K),S.callback=(E,v)=>{clearTimeout(Q),_(E,v)}),this._queryable?this._ending?(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client was closed and is not queryable"))}),F):(this._queryQueue.push(S),this._pulseQueryQueue(),F):(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client has encountered a connection error and is not queryable"))}),F)},D.prototype.end=function(P){var w=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,P));var R;return P||(R=new this._Promise(function(S,F){P=V((K)=>K?F(K):S(),"cb")})),this.native.end(function(){w._errorAllQueries(Error("Connection terminated")),r.nextTick(()=>{w.emit("end"),P&&P()})}),R},D.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},D.prototype._pulseQueryQueue=function(P){if(this._connected&&!this._hasActiveQuery()){var w=this._queryQueue.shift();if(!w){P||this.emit("drain");return}this._activeQuery=w,w.submit(this);var R=this;w.once("_done",function(){R._pulseQueryQueue()})}},D.prototype.cancel=function(P){this._activeQuery===P?this.native.cancel(function(){}):this._queryQueue.indexOf(P)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(P),1)},D.prototype.ref=function(){},D.prototype.unref=function(){},D.prototype.setTypeParser=function(P,w,R){return this._types.setTypeParser(P,w,R)},D.prototype.getTypeParser=function(P,w){return this._types.getTypeParser(P,w)}}),V7=o((W,$)=>{u(),$.exports=eZ()}),m4=o((W,$)=>{u();var Z=dZ(),J=I4(),X=i7(),Y=sZ(),{DatabaseError:L}=u7(),G=V((D)=>{var P;return P=class extends Y{constructor(w){super(w,D)}},V(P,"BoundPool"),P},"poolFactory"),U=V(function(D){this.defaults=J,this.Client=D,this.Query=this.Client.Query,this.Pool=G(this.Client),this._pools=[],this.Connection=X,this.types=b4(),this.DatabaseError=L},"PG");typeof r.env.NODE_PG_FORCE_NATIVE<"u"?$.exports=new U(V7()):($.exports=new U(Z),Object.defineProperty($.exports,"native",{configurable:!0,enumerable:!1,get(){var D=null;try{D=new U(V7())}catch(P){if(P.code!=="MODULE_NOT_FOUND")throw P}return Object.defineProperty($.exports,"native",{value:D}),D}}))});u();u();tW();E7();u();var{defineProperty:WJ,defineProperties:$J,getOwnPropertyDescriptors:ZJ,getOwnPropertySymbols:P7}=Object,JJ=Object.prototype.hasOwnProperty,XJ=Object.prototype.propertyIsEnumerable,F7=V((W,$,Z)=>($ in W)?WJ(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,"__defNormalProp"),YJ=V((W,$)=>{for(var Z in $||($={}))JJ.call($,Z)&&F7(W,Z,$[Z]);if(P7)for(var Z of P7($))XJ.call($,Z)&&F7(W,Z,$[Z]);return W},"__spreadValues"),HJ=V((W,$)=>$J(W,ZJ($)),"__spreadProps"),kJ=1008000,D7=new Uint8Array(new Uint16Array([258]).buffer)[0]===2,GJ=new TextDecoder,R9=new TextEncoder,C4=R9.encode("0123456789abcdef"),q4=R9.encode("0123456789ABCDEF"),LJ=R9.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),d7=LJ.slice();d7[62]=45;d7[63]=95;var pW,O4;function s7(W,{alphabet:$,scratchArr:Z}={}){if(!pW)if(pW=new Uint16Array(256),O4=new Uint16Array(256),D7)for(let S=0;S<256;S++)pW[S]=C4[S&15]<<8|C4[S>>>4],O4[S]=q4[S&15]<<8|q4[S>>>4];else for(let S=0;S<256;S++)pW[S]=C4[S&15]|C4[S>>>4]<<8,O4[S]=q4[S&15]|q4[S>>>4]<<8;W.byteOffset%4!==0&&(W=new Uint8Array(W));let J=W.length,X=J>>>1,Y=J>>>2,L=Z||new Uint16Array(J),G=new Uint32Array(W.buffer,W.byteOffset,Y),U=new Uint32Array(L.buffer,L.byteOffset,X),D=$==="upper"?O4:pW,P=0,w=0,R;if(D7)for(;P<Y;)R=G[P++],U[w++]=D[R>>>8&255]<<16|D[R&255],U[w++]=D[R>>>24]<<16|D[R>>>16&255];else for(;P<Y;)R=G[P++],U[w++]=D[R>>>24]<<16|D[R>>>16&255],U[w++]=D[R>>>8&255]<<16|D[R&255];for(P<<=2;P<J;)L[P]=D[W[P++]];return GJ.decode(L.subarray(0,J))}V(s7,"_toHex");function n7(W,$={}){let Z="",J=W.length,X=kJ>>>1,Y=Math.ceil(J/X),L=new Uint16Array(Y>1?X:J);for(let G=0;G<Y;G++){let U=G*X,D=U+X;Z+=s7(W.subarray(U,D),HJ(YJ({},$),{scratchArr:L}))}return Z}V(n7,"_toHexChunked");function r7(W,$={}){return $.alphabet!=="upper"&&typeof W.toHex=="function"?W.toHex():n7(W,$)}V(r7,"toHex");u();var o7=class W{constructor($,Z){this.strings=$,this.values=Z}toParameterizedQuery($={query:"",params:[]}){let{strings:Z,values:J}=this;for(let X=0,Y=Z.length;X<Y;X++)if($.query+=Z[X],X<J.length){let L=J[X];if(L instanceof $$)$.query+=L.sql;else if(L instanceof x4)if(L.queryData instanceof W)L.queryData.toParameterizedQuery($);else{if(L.queryData.params?.length)throw Error("This query is not composable");$.query+=L.queryData.query}else{let{params:G}=$;G.push(L),$.query+="$"+G.length,(L instanceof i||ArrayBuffer.isView(L))&&($.query+="::bytea")}}return $}};V(o7,"SqlTemplate");var e7=o7,W$=class{constructor($){this.sql=$}};V(W$,"UnsafeRawSql");var $$=W$;u();function w9(){typeof window<"u"&&typeof document<"u"&&typeof console<"u"&&typeof console.warn=="function"&&console.warn(`
29
29
  ************************************************************
30
30
  * *
31
31
  * WARNING: Running SQL directly from the browser can have *
@@ -40,7 +40,7 @@ Expecting one of '${Z.join("', '")}'`);let J=`${W}Help`;return this.on(J,(X)=>{l
40
40
  * using the disableWarningInBrowsers configuration *
41
41
  * parameter. *
42
42
  * *
43
- ************************************************************`)}U(D9,"warnIfBrowser");tW();var kJ=Q8(K9()),GJ=Q8(I4()),$$=class W extends Error{constructor($){super($);t(this,"name","NeonDbError"),t(this,"severity"),t(this,"code"),t(this,"detail"),t(this,"hint"),t(this,"position"),t(this,"internalPosition"),t(this,"internalQuery"),t(this,"where"),t(this,"schema"),t(this,"table"),t(this,"column"),t(this,"dataType"),t(this,"constraint"),t(this,"file"),t(this,"line"),t(this,"routine"),t(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};U($$,"NeonDbError");var XW=$$,R7="transaction() expects an array of queries, or a function returning an array of queries",MJ=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function Z$(W){return W instanceof i?"\\x"+n7(W):W}U(Z$,"encodeBuffersAsBytea");function k9(W){let{query:$,params:Z}=W instanceof o7?W.toParameterizedQuery():W;return{query:$,params:Z.map((J)=>Z$((0,GJ.prepareValue)(J)))}}U(k9,"prepareQuery");function m4(W,{arrayMode:$,fullResults:Z,fetchOptions:J,isolationLevel:X,readOnly:Y,deferrable:M,authToken:G,disableWarningInBrowsers:V}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let R;try{R=L9(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:P,username:w,hostname:D,port:S,pathname:F}=R;if(P!=="postgres:"&&P!=="postgresql:"||!w||!D||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function L(_,...v){if(!(Array.isArray(_)&&Array.isArray(_.raw)&&Array.isArray(v)))throw Error('This function can now be called only as a tagged-template function: sql`SELECT ${value}`, not sql("SELECT $1", [value], options). For a conventional function call with value placeholders ($1, $2, etc.), use sql.query("SELECT $1", [value], options).');return new O4(Q,new o7(_,v))}U(L,"templateFn"),L.query=(_,v,T)=>new O4(Q,{query:_,params:v??[]},T),L.unsafe=(_)=>new W$(_),L.transaction=async(_,v)=>{if(typeof _=="function"&&(_=_(L)),!Array.isArray(_))throw Error(R7);_.forEach((q)=>{if(!(q instanceof O4))throw Error(R7)});let T=_.map((q)=>q.queryData),x=_.map((q)=>q.opts??{});return Q(T,x,v)};async function Q(_,v,T){let{fetchEndpoint:x,fetchFunction:q}=w8,E=Array.isArray(_)?{queries:_.map((J1)=>k9(J1))}:k9(_),N=J??{},A=$??!1,f=Z??!1,B=X,C=Y,c=M;T!==void 0&&(T.fetchOptions!==void 0&&(N={...N,...T.fetchOptions}),T.arrayMode!==void 0&&(A=T.arrayMode),T.fullResults!==void 0&&(f=T.fullResults),T.isolationLevel!==void 0&&(B=T.isolationLevel),T.readOnly!==void 0&&(C=T.readOnly),T.deferrable!==void 0&&(c=T.deferrable)),v!==void 0&&!Array.isArray(v)&&v.fetchOptions!==void 0&&(N={...N,...v.fetchOptions});let m=G;!Array.isArray(v)&&v?.authToken!==void 0&&(m=v.authToken);let b=typeof x=="function"?x(D,S,{jwtAuth:m!==void 0}):x,g={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await X$(m);p&&(g.Authorization=`Bearer ${p}`),Array.isArray(_)&&(B!==void 0&&(g["Neon-Batch-Isolation-Level"]=B),C!==void 0&&(g["Neon-Batch-Read-Only"]=String(C)),c!==void 0&&(g["Neon-Batch-Deferrable"]=String(c))),V||w8.disableWarningInBrowsers||D9();let d;try{d=await(q??fetch)(b,{method:"POST",body:JSON.stringify(E),headers:g,...N})}catch(J1){let s=new XW(`Error connecting to database: ${J1}`);throw s.sourceError=J1,s}if(d.ok){let J1=await d.json();if(Array.isArray(_)){let s=J1.results;if(!Array.isArray(s))throw new XW("Neon internal error: unexpected result format");return s.map((s1,V1)=>{let f1=v[V1]??{},kW=f1.arrayMode??A,GW=f1.fullResults??f;return G9(s1,{arrayMode:kW,fullResults:GW,types:f1.types})})}else{let s=v??{},s1=s.arrayMode??A,V1=s.fullResults??f;return G9(J1,{arrayMode:s1,fullResults:V1,types:s.types})}}else{let{status:J1}=d;if(J1===400){let s=await d.json(),s1=new XW(s.message);for(let V1 of MJ)s1[V1]=s[V1]??void 0;throw s1}else{let s=await d.text();throw new XW(`Server error (HTTP status ${J1}): ${s}`)}}}return U(Q,"execute"),L}U(m4,"neon");var J$=class{constructor($,Z,J){this.execute=$,this.queryData=Z,this.opts=J}then($,Z){return this.execute(this.queryData,this.opts).then($,Z)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};U(J$,"NeonQueryPromise");var O4=J$;function G9(W,{arrayMode:$,fullResults:Z,types:J}){let X=new kJ.default(J),Y=W.fields.map((V)=>V.name),M=W.fields.map((V)=>X.getTypeParser(V.dataTypeID)),G=$===!0?W.rows.map((V)=>V.map((R,P)=>R===null?null:M[P](R))):W.rows.map((V)=>Object.fromEntries(V.map((R,P)=>[Y[P],R===null?null:M[P](R)])));return Z?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=G,W._parsers=M,W._types=X,W):G}U(G9,"processQueryResult");async function X$(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let Z=new XW("Error getting auth token.");throw $ instanceof Error&&(Z=new XW(`Error getting auth token: ${$.message}`)),Z}}U(X$,"getAuthToken");u();var LJ=Q8(g4());u();var KJ=Q8(g4()),Y$=class extends KJ.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:Z}=this;Z.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&Z.useSecureWebSocket&&console.warn("SSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = true). Double encryption will increase latency and CPU usage. It may be appropriate to disable SSL in the Postgres connection parameters or set forceDisablePgSSL = true.");let J=typeof this.config!="string"&&this.config?.host!==void 0||typeof this.config!="string"&&this.config?.connectionString!==void 0||r.env.PGHOST!==void 0,X=r.env.USER??r.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===X&&this.database===X&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${X}, db: ${X}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let Y=super.connect($),M=Z.pipelineTLS&&this.ssl,G=Z.pipelineConnect==="password";if(!M&&!Z.pipelineConnect)return Y;let V=this.connection;if(M&&V.on("connect",()=>V.stream.emit("data","S")),G){V.removeAllListeners("authenticationCleartextPassword"),V.removeAllListeners("readyForQuery"),V.once("readyForQuery",()=>V.on("readyForQuery",this._handleReadyForQuery.bind(this)));let R=this.ssl?"sslconnect":"connect";V.on(R,()=>{this.neonConfig.disableWarningInBrowsers||D9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return Y}async _handleAuthSASLContinue($){if(typeof crypto>"u"||crypto.subtle===void 0||crypto.subtle.importKey===void 0)throw Error("Cannot use SASL auth when `crypto.subtle` is not defined");let Z=crypto.subtle,J=this.saslSession,X=this.password,Y=$.data;if(J.message!=="SASLInitialResponse"||typeof X!="string"||typeof Y!="string")throw Error("SASL: protocol error");let M=Object.fromEntries(Y.split(",").map((J1)=>{if(!/^.=/.test(J1))throw Error("SASL: Invalid attribute pair entry");let s=J1[0],s1=J1.substring(2);return[s,s1]})),G=M.r,V=M.s,R=M.i;if(!G||!/^[!-+--~]+$/.test(G))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable");if(!V||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(V))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64");if(!R||!/^[1-9][0-9]*$/.test(R))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!G.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(G.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let P=parseInt(R,10),w=i.from(V,"base64"),D=new TextEncoder,S=D.encode(X),F=await Z.importKey("raw",S,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),L=new Uint8Array(await Z.sign("HMAC",F,i.concat([w,i.from([0,0,0,1])]))),Q=L;for(var _=0;_<P-1;_++)L=new Uint8Array(await Z.sign("HMAC",F,L)),Q=i.from(Q.map((J1,s)=>Q[s]^L[s]));let v=Q,T=await Z.importKey("raw",v,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),x=new Uint8Array(await Z.sign("HMAC",T,D.encode("Client Key"))),q=await Z.digest("SHA-256",x),E="n=*,r="+J.clientNonce,N="r="+G+",s="+V+",i="+P,A="c=biws,r="+G,f=E+","+N+","+A,B=await Z.importKey("raw",q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await Z.sign("HMAC",B,D.encode(f))),c=i.from(x.map((J1,s)=>x[s]^C[s])),m=c.toString("base64");let b=await Z.importKey("raw",v,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),g=await Z.sign("HMAC",b,D.encode("Server Key")),p=await Z.importKey("raw",g,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var d=i.from(await Z.sign("HMAC",p,D.encode(f)));J.message="SASLResponse",J.serverSignature=d.toString("base64"),J.response=A+",p="+m,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};U(Y$,"NeonClient");var zJ=Y$;tW();var UJ=Q8(F9());function H$(W,$){if($)return{callback:$,result:void 0};let Z,J,X=U(function(M,G){M?Z(M):J(G)},"cb"),Y=new W(function(M,G){J=M,Z=G});return{callback:X,result:Y}}U(H$,"promisify");var k$=class extends LJ.Pool{constructor(){super(...arguments);t(this,"Client",zJ),t(this,"hasFetchUnsupportedListeners",!1),t(this,"addListener",this.on)}on($,Z){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,Z)}query($,Z,J){if(!w8.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,Z,J);typeof Z=="function"&&(J=Z,Z=void 0);let X=H$(this.Promise,J);J=X.callback;try{let Y=new UJ.default(this.options),M=encodeURIComponent,G=encodeURI,V=`postgresql://${M(Y.user)}:${M(Y.password)}@${M(Y.host)}/${G(Y.database)}`,R=typeof $=="string"?$:$.text,P=Z??$.values??[];m4(V,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(R,P,{types:$.types??this.options?.types}).then((w)=>J(void 0,w)).catch((w)=>J(w))}catch(Y){J(Y)}return X.result}};U(k$,"NeonPool");var G$=k$;tW();var dW=Q8(g4());var{DatabaseError:wQ,defaults:QQ,escapeIdentifier:SQ,escapeLiteral:_Q,types:vQ}=dW;/*! Bundled license information:
43
+ ************************************************************`)}V(w9,"warnIfBrowser");tW();var KJ=Q8(z9()),MJ=Q8(y4()),Z$=class W extends Error{constructor($){super($);t(this,"name","NeonDbError"),t(this,"severity"),t(this,"code"),t(this,"detail"),t(this,"hint"),t(this,"position"),t(this,"internalPosition"),t(this,"internalQuery"),t(this,"where"),t(this,"schema"),t(this,"table"),t(this,"column"),t(this,"dataType"),t(this,"constraint"),t(this,"file"),t(this,"line"),t(this,"routine"),t(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};V(Z$,"NeonDbError");var YW=Z$,R7="transaction() expects an array of queries, or a function returning an array of queries",zJ=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function J$(W){return W instanceof i?"\\x"+r7(W):W}V(J$,"encodeBuffersAsBytea");function G9(W){let{query:$,params:Z}=W instanceof e7?W.toParameterizedQuery():W;return{query:$,params:Z.map((J)=>J$((0,MJ.prepareValue)(J)))}}V(G9,"prepareQuery");function c4(W,{arrayMode:$,fullResults:Z,fetchOptions:J,isolationLevel:X,readOnly:Y,deferrable:L,authToken:G,disableWarningInBrowsers:U}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let D;try{D=M9(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:P,username:w,hostname:R,port:S,pathname:F}=D;if(P!=="postgres:"&&P!=="postgresql:"||!w||!R||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function K(_,...E){if(!(Array.isArray(_)&&Array.isArray(_.raw)&&Array.isArray(E)))throw Error('This function can now be called only as a tagged-template function: sql`SELECT ${value}`, not sql("SELECT $1", [value], options). For a conventional function call with value placeholders ($1, $2, etc.), use sql.query("SELECT $1", [value], options).');return new x4(Q,new e7(_,E))}V(K,"templateFn"),K.query=(_,E,v)=>new x4(Q,{query:_,params:E??[]},v),K.unsafe=(_)=>new $$(_),K.transaction=async(_,E)=>{if(typeof _=="function"&&(_=_(K)),!Array.isArray(_))throw Error(R7);_.forEach((q)=>{if(!(q instanceof x4))throw Error(R7)});let v=_.map((q)=>q.queryData),x=_.map((q)=>q.opts??{});return Q(v,x,E)};async function Q(_,E,v){let{fetchEndpoint:x,fetchFunction:q}=w8,h=Array.isArray(_)?{queries:_.map((J1)=>G9(J1))}:G9(_),N=J??{},A=$??!1,f=Z??!1,B=X,C=Y,c=L;v!==void 0&&(v.fetchOptions!==void 0&&(N={...N,...v.fetchOptions}),v.arrayMode!==void 0&&(A=v.arrayMode),v.fullResults!==void 0&&(f=v.fullResults),v.isolationLevel!==void 0&&(B=v.isolationLevel),v.readOnly!==void 0&&(C=v.readOnly),v.deferrable!==void 0&&(c=v.deferrable)),E!==void 0&&!Array.isArray(E)&&E.fetchOptions!==void 0&&(N={...N,...E.fetchOptions});let m=G;!Array.isArray(E)&&E?.authToken!==void 0&&(m=E.authToken);let b=typeof x=="function"?x(R,S,{jwtAuth:m!==void 0}):x,g={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await Y$(m);p&&(g.Authorization=`Bearer ${p}`),Array.isArray(_)&&(B!==void 0&&(g["Neon-Batch-Isolation-Level"]=B),C!==void 0&&(g["Neon-Batch-Read-Only"]=String(C)),c!==void 0&&(g["Neon-Batch-Deferrable"]=String(c))),U||w8.disableWarningInBrowsers||w9();let d;try{d=await(q??fetch)(b,{method:"POST",body:JSON.stringify(h),headers:g,...N})}catch(J1){let s=new YW(`Error connecting to database: ${J1}`);throw s.sourceError=J1,s}if(d.ok){let J1=await d.json();if(Array.isArray(_)){let s=J1.results;if(!Array.isArray(s))throw new YW("Neon internal error: unexpected result format");return s.map((s1,V1)=>{let f1=E[V1]??{},kW=f1.arrayMode??A,GW=f1.fullResults??f;return L9(s1,{arrayMode:kW,fullResults:GW,types:f1.types})})}else{let s=E??{},s1=s.arrayMode??A,V1=s.fullResults??f;return L9(J1,{arrayMode:s1,fullResults:V1,types:s.types})}}else{let{status:J1}=d;if(J1===400){let s=await d.json(),s1=new YW(s.message);for(let V1 of zJ)s1[V1]=s[V1]??void 0;throw s1}else{let s=await d.text();throw new YW(`Server error (HTTP status ${J1}): ${s}`)}}}return V(Q,"execute"),K}V(c4,"neon");var X$=class{constructor($,Z,J){this.execute=$,this.queryData=Z,this.opts=J}then($,Z){return this.execute(this.queryData,this.opts).then($,Z)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};V(X$,"NeonQueryPromise");var x4=X$;function L9(W,{arrayMode:$,fullResults:Z,types:J}){let X=new KJ.default(J),Y=W.fields.map((U)=>U.name),L=W.fields.map((U)=>X.getTypeParser(U.dataTypeID)),G=$===!0?W.rows.map((U)=>U.map((D,P)=>D===null?null:L[P](D))):W.rows.map((U)=>Object.fromEntries(U.map((D,P)=>[Y[P],D===null?null:L[P](D)])));return Z?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=G,W._parsers=L,W._types=X,W):G}V(L9,"processQueryResult");async function Y$(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let Z=new YW("Error getting auth token.");throw $ instanceof Error&&(Z=new YW(`Error getting auth token: ${$.message}`)),Z}}V(Y$,"getAuthToken");u();var UJ=Q8(m4());u();var VJ=Q8(m4()),H$=class extends VJ.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:Z}=this;Z.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&Z.useSecureWebSocket&&console.warn("SSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = true). Double encryption will increase latency and CPU usage. It may be appropriate to disable SSL in the Postgres connection parameters or set forceDisablePgSSL = true.");let J=typeof this.config!="string"&&this.config?.host!==void 0||typeof this.config!="string"&&this.config?.connectionString!==void 0||r.env.PGHOST!==void 0,X=r.env.USER??r.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===X&&this.database===X&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${X}, db: ${X}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let Y=super.connect($),L=Z.pipelineTLS&&this.ssl,G=Z.pipelineConnect==="password";if(!L&&!Z.pipelineConnect)return Y;let U=this.connection;if(L&&U.on("connect",()=>U.stream.emit("data","S")),G){U.removeAllListeners("authenticationCleartextPassword"),U.removeAllListeners("readyForQuery"),U.once("readyForQuery",()=>U.on("readyForQuery",this._handleReadyForQuery.bind(this)));let D=this.ssl?"sslconnect":"connect";U.on(D,()=>{this.neonConfig.disableWarningInBrowsers||w9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return Y}async _handleAuthSASLContinue($){if(typeof crypto>"u"||crypto.subtle===void 0||crypto.subtle.importKey===void 0)throw Error("Cannot use SASL auth when `crypto.subtle` is not defined");let Z=crypto.subtle,J=this.saslSession,X=this.password,Y=$.data;if(J.message!=="SASLInitialResponse"||typeof X!="string"||typeof Y!="string")throw Error("SASL: protocol error");let L=Object.fromEntries(Y.split(",").map((J1)=>{if(!/^.=/.test(J1))throw Error("SASL: Invalid attribute pair entry");let s=J1[0],s1=J1.substring(2);return[s,s1]})),G=L.r,U=L.s,D=L.i;if(!G||!/^[!-+--~]+$/.test(G))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable");if(!U||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(U))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64");if(!D||!/^[1-9][0-9]*$/.test(D))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!G.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(G.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let P=parseInt(D,10),w=i.from(U,"base64"),R=new TextEncoder,S=R.encode(X),F=await Z.importKey("raw",S,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),K=new Uint8Array(await Z.sign("HMAC",F,i.concat([w,i.from([0,0,0,1])]))),Q=K;for(var _=0;_<P-1;_++)K=new Uint8Array(await Z.sign("HMAC",F,K)),Q=i.from(Q.map((J1,s)=>Q[s]^K[s]));let E=Q,v=await Z.importKey("raw",E,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),x=new Uint8Array(await Z.sign("HMAC",v,R.encode("Client Key"))),q=await Z.digest("SHA-256",x),h="n=*,r="+J.clientNonce,N="r="+G+",s="+U+",i="+P,A="c=biws,r="+G,f=h+","+N+","+A,B=await Z.importKey("raw",q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await Z.sign("HMAC",B,R.encode(f))),c=i.from(x.map((J1,s)=>x[s]^C[s])),m=c.toString("base64");let b=await Z.importKey("raw",E,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),g=await Z.sign("HMAC",b,R.encode("Server Key")),p=await Z.importKey("raw",g,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var d=i.from(await Z.sign("HMAC",p,R.encode(f)));J.message="SASLResponse",J.serverSignature=d.toString("base64"),J.response=A+",p="+m,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};V(H$,"NeonClient");var PJ=H$;tW();var FJ=Q8(D9());function k$(W,$){if($)return{callback:$,result:void 0};let Z,J,X=V(function(L,G){L?Z(L):J(G)},"cb"),Y=new W(function(L,G){J=L,Z=G});return{callback:X,result:Y}}V(k$,"promisify");var G$=class extends UJ.Pool{constructor(){super(...arguments);t(this,"Client",PJ),t(this,"hasFetchUnsupportedListeners",!1),t(this,"addListener",this.on)}on($,Z){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,Z)}query($,Z,J){if(!w8.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,Z,J);typeof Z=="function"&&(J=Z,Z=void 0);let X=k$(this.Promise,J);J=X.callback;try{let Y=new FJ.default(this.options),L=encodeURIComponent,G=encodeURI,U=`postgresql://${L(Y.user)}:${L(Y.password)}@${L(Y.host)}/${G(Y.database)}`,D=typeof $=="string"?$:$.text,P=Z??$.values??[];c4(U,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(D,P,{types:$.types??this.options?.types}).then((w)=>J(void 0,w)).catch((w)=>J(w))}catch(Y){J(Y)}return X.result}};V(G$,"NeonPool");var L$=G$;tW();var dW=Q8(m4());var{DatabaseError:vQ,defaults:fQ,escapeIdentifier:jQ,escapeLiteral:AQ,types:NQ}=dW;/*! Bundled license information:
44
44
 
45
45
  ieee754/index.js:
46
46
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@@ -52,5 +52,5 @@ buffer/index.js:
52
52
  * @author Feross Aboukhadijeh <https://feross.org>
53
53
  * @license MIT
54
54
  *)
55
- */var M$=Symbol("release"),L$=class{#W;constructor(W){this.#W=W}async executeQuery(W){let $=await this.#W.query(W.sql,[...W.parameters]);if($.command==="INSERT"||$.command==="UPDATE"||$.command==="DELETE"){let Z=BigInt($.rowCount);return{numUpdatedOrDeletedRows:Z,numAffectedRows:Z,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[M$](){this.#W.release?.()}},K$=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new VJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},VJ=class{#W;#$=new WeakMap;#Z;constructor(W){this.#W=W}async init(){Object.assign(w8,this.#W),this.#Z=new G$(this.#W)}async acquireConnection(){let W=await this.#Z.connect(),$=this.#$.get(W);if(!$)$=new L$(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(gW.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(gW.raw("begin"))}async commitTransaction(W){await W.executeQuery(gW.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(gW.raw("rollback"))}async releaseConnection(W){W[M$]()}async destroy(){if(this.#Z){let W=this.#Z;this.#Z=void 0,await W.end()}}},CQ=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new PJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},PJ=class{#W;#$;constructor(W){this.#W=W,this.#$=new L$({query:m4(this.#W.connectionString,{fullResults:!0})})}async init(){}async acquireConnection(){return this.#$}async beginTransaction(W,$){throw Error("Transactions are not supported with Neon HTTP connections")}async commitTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async rollbackTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async releaseConnection(W){}async destroy(){}};function c4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function FJ({pg_host:W,environment:$,...Z}){let J=Z.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let X;if($==="production")X=W;else if($==="development")if(W.includes("localhost"))X="localhost";else X="postgres-ws-proxy";else if($==="test"||$==="staging")X="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(c4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let V=`${X}${$!=="production"?":5433":""}/${$==="production"?"v2":"v1"}`;if(console.assert(!V.startsWith("ws://")&&!V.startsWith("wss://"),"Expected built postgres neon proxy websocket URL to not include protocol (ws:// or wss://)!"),J)console.log("[getPostgresNeonWsProxyUrl] Loaded websocket proxy URL: ",V);return V}var z$=FJ;function U$(W){return!isNaN(W)&&Number.isInteger(W)&&Number.isFinite(W)&&W>0}function w9(W){if(typeof W==="number"){if(U$(W))return W}else if(typeof W==="string"){let $=Number.parseInt(W);if(U$($))return $}else throw TypeError(`Unexpected type for value to parse port number from: '${typeof W}'`);throw TypeError("Failed to parse port number for database configuration!")}function RJ(W){let $=process.env.SCHEMAVAULTS_DBH_DEBUG;if(typeof $==="string")if($.toLowerCase().includes("true"))return!0;else return!1;else if(W!=="production")return!0;else return!1}var V$=RJ;function DJ(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var G8=DJ;function wJ(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var P$=wJ;function QJ(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((R)=>typeof R!=="string"&&typeof R<"u"&&typeof R!=="number"&&typeof R!=="boolean")){let R=new Set(Object.values(W).map((P)=>typeof P));throw R.delete("undefined"),R.delete("string"),R.delete("number"),R.delete("boolean"),TypeError(`Received invalid database credentials; expected only strings or undefined in values object provided to parse credentials from. Received invalid types: ${Array.from(R).join(", ")}`)}let Z=G8(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!Z){if($)console.warn("POSTGRES_URL_NON_POOLING is not set in environment variables!")}else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres no-pooling connection url POSTGRES_URL_NON_POOLING: "${Z}"`);let J=G8(typeof W.POSTGRES_HOST==="string"?W.POSTGRES_HOST:void 0);if(!J)throw Error("POSTGRES_HOST is not set in environment variables!");else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using database POSTGRES_HOST: "${J}"`);let X=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)X=Number.parseInt(G8(W.POSTGRES_PORT)??"NaN");if(typeof X!=="number"||isNaN(X))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let Y=G8(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!Y)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let M=G8(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!M)throw Error("POSTGRES_USER is not defined in environment variables!");let G=G8(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!G)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let V="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)V=G8(W.POSTGRES_URL)??"";else V=P$({POSTGRES_DATABASE:Y,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_USER:M,POSTGRES_PASSWORD:G});if(!V)throw Error("Failed to load POSTGRES_URL from environment variables, or to construct it from other environment variables!");if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres connection url POSTGRES_URL: "${V}"`);return{POSTGRES_USER:M,POSTGRES_PASSWORD:G,POSTGRES_URL:V,POSTGRES_URL_NON_POOLING:Z,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_DATABASE:Y}}var u4=QJ;function SJ(W,$=!1){return u4(W,$)}var F$=SJ;class l4{credentials;kysely_db;env;debug;constructor(W){if(!c4(W.environment))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W.environment,this.debug=V$(this.env);let $=void 0;if(W.credentials){if(typeof W.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");$=u4(W.credentials,this.debug)}else $=F$(process.env,this.debug);if(!$)throw Error("Failed to parse database credentials from options or environment variables!");this.credentials=$;let J={dialect:this.initializeDbDialect(W),log:["query","error"]};this.kysely_db=new Q0(J)}get db(){return this.kysely_db}async destroy(){return await this.kysely_db.destroy()}async[Symbol.asyncDispose](){return await this.destroy()}}class p4 extends l4{initializeDbDialect(W){let $=this.debug,Z=this.env,J=this.credentials,X={connectionString:J.POSTGRES_URL,host:J.POSTGRES_HOST,user:J.POSTGRES_USER,password:J.POSTGRES_PASSWORD,database:J.POSTGRES_DATABASE,useSecureWebSocket:this.env==="production",port:w9(J.POSTGRES_PORT),wsProxy:(M)=>{if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}")`);let G;try{let V={pg_host:M,environment:Z,debug:this.debug};if(typeof W.wsProxyUrl>"u"||!W.wsProxyUrl)G=z$(V);else if(typeof W.wsProxyUrl==="string"&&W.wsProxyUrl&&W.wsProxyUrl.length>0)G=W.wsProxyUrl;else if(typeof W.wsProxyUrl==="function"&&W.wsProxyUrl){let R=W.wsProxyUrl;G=R(V)}else throw Error(`Invalid wsProxy url for host: "${M}". Not a string, undefined, or function!`)}catch(V){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}") => Failure: `,V),Error(`Failed to calculate wsProxy url for host: "${M}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}") => `,G);return G}};if(this.debug)X.pipelineTLS=!1,X.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",X);return new K$(X)}constructor(W){super(W);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}}class Q9{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let Z of $){if(!this.hasExpectedExtension(Z)){this.#W.onFileIgnored?.(Z,"Extension");continue}let J=this.#W.path.join(this.#W.migrationFolder,Z),X=this.#W.import?await this.#W.import(J):await import(J),Y=Z.substring(0,Z.lastIndexOf("."));if(R$(X?.default))W[Y]=X.default;else if(R$(X))W[Y]=X;else this.#W.onFileIgnored?.(Z,"NotMigration")}return W}hasExpectedExtension(W){return W.endsWith(".js")||W.endsWith(".ts")&&!W.endsWith(".d.ts")||W.endsWith(".mjs")||W.endsWith(".mts")&&!W.endsWith(".d.mts")||W.endsWith(".cjs")||W.endsWith(".cts")&&!W.endsWith(".d.cts")}}function R$(W){return Q1(W)&&R1(W.up)}import _J from"fs/promises";import vJ from"path";import{existsSync as D$}from"fs";function w$({db:W,migrationFolder:$}){return new J9({db:W,provider:new Q9({fs:_J,path:vJ,migrationFolder:$})})}function EJ(W){if(typeof W!=="object"||!W)throw TypeError("Expected migration result to be an object!");if(!("migrationName"in W)||typeof W.migrationName!=="string")throw TypeError("Expected migration result's 'migrationName' to be a string!");else if(!("direction"in W)||typeof W.direction!=="string")throw TypeError("Expected migration result's 'direction' to be a string!");else if(!("status"in W)||typeof W.status!=="string")throw TypeError("Expected migration result's 'status' to be a string!");else if(!["Up","Down"].includes(W.direction))throw TypeError("Expected migration result's 'direction' to be one of: 'Up' or 'Down'!");else if(!["Success","Error","NotExecuted"].includes(W.status))throw TypeError("Expected migration result's 'status' to be one of: 'Success', 'Error', or 'NotExecuted'!");return!0}function Q$(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)EJ($);return!0}async function S$({db:W,migrationFolder:$,...Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!D$($))throw Error(`migrationFolder '${$}' does not exist`);let J=w$({db:W,migrationFolder:$}),X;if(typeof Z.version==="string")X=await J.migrateTo(Z.version);else X=await J.migrateToLatest();let{error:Y,results:M}=X;if(Y)throw console.error(Y),Y;if(!M)return[];if(!Q$(M))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return M}async function _$({db:W,migrationFolder:$,version:Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!D$($))throw Error(`migrationFolder '${$}' does not exist`);let J=w$({db:W,migrationFolder:$}),{error:X,results:Y}=await J.migrateTo(Z);if(X)throw console.error(X),X;if(!Y)return[];if(!Q$(Y))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return Y}import v$ from"fs";import hJ from"path";function S9(W){let $=hJ.resolve(W);if(!v$.existsSync($))throw Error(`Env file not found: ${$}`);let Z=v$.readFileSync($,"utf-8");for(let J of Z.split(`
56
- `)){let X=J.trim();if(!X||X.startsWith("#"))continue;let Y=X.indexOf("=");if(Y===-1)continue;let M=X.slice(0,Y).trim(),G=X.slice(Y+1).trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);if(process.env[M]===void 0)process.env[M]=G}}var NJ=fJ(import.meta.url),{version:E$}=NJ("../package.json");if(typeof E$!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var HW=new i9;HW.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(E$);HW.command("migrate").description("Run database migrations forward (to latest or a specific version)").argument("<folder>","Path to the migration folder").argument("[version]","Target migration version (defaults to latest)").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)S9(Z.envFile);let J=i4.resolve(W),X=new p4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await S$({db:X.db,migrationFolder:J,version:$});for(let M of Y)console.log(`[${M.direction}] ${M.migrationName}: ${M.status}`);if(Y.length===0)console.log("No migrations to run.")}catch(Y){console.error("Migration failed:",Y),process.exit(1)}finally{await X.destroy()}});HW.command("reverse").description("Roll back database migrations to a specific version").argument("<folder>","Path to the migration folder").argument("<version>","Target version to roll back to").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)S9(Z.envFile);let J=i4.resolve(W),X=new p4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await _$({db:X.db,migrationFolder:J,version:$});for(let M of Y)console.log(`[${M.direction}] ${M.migrationName}: ${M.status}`);if(Y.length===0)console.log("No migrations to reverse.")}catch(Y){console.error("Reverse migration failed:",Y),process.exit(1)}finally{await X.destroy()}});HW.command("build-db-migrations").description("Build TypeScript Kysely migration files into JavaScript using Bun's bundler").argument("<migrations-src>","Directory containing .ts migration source files").requiredOption("--outdir <dir>","Output directory for compiled migration .js files").requiredOption("--sql-module <path>","Path to sql.ts source module to build alongside").option("--sql-outdir <dir>","Output directory for the built sql.js module (defaults to parent of --outdir)").option("--external <pkg...>","Packages to keep external in the bundle (default: @schemavaults/dbh, kysely)").option("--debug","Enable debug logging").action(async(W,$)=>{try{jJ("bun --version",{stdio:"ignore"})}catch{console.error("Error: 'bun' is required for build-db-migrations but was not found in PATH."),process.exit(1)}let Z=i4.dirname(TJ(import.meta.url)),X=["run",i4.resolve(Z,"build-db-migrations.js"),W];if(X.push("--outdir",$.outdir),X.push("--sql-module",$.sqlModule),$.sqlOutdir)X.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)X.push("--external",...$.external);if($.debug)X.push("--debug");AJ("bun",X,{stdio:"inherit",cwd:process.cwd()}).on("close",(M)=>{process.exit(M??1)})});var TS=HW;HW.parse();export{TS as default};
55
+ */var K$=Symbol("release"),M$=class{#W;constructor(W){this.#W=W}async executeQuery(W){let $=await this.#W.query(W.sql,[...W.parameters]);if($.command==="INSERT"||$.command==="UPDATE"||$.command==="DELETE"){let Z=BigInt($.rowCount);return{numUpdatedOrDeletedRows:Z,numAffectedRows:Z,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[K$](){this.#W.release?.()}},z$=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new DJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},DJ=class{#W;#$=new WeakMap;#Z;constructor(W){this.#W=W}async init(){Object.assign(w8,this.#W),this.#Z=new L$(this.#W)}async acquireConnection(){let W=await this.#Z.connect(),$=this.#$.get(W);if(!$)$=new M$(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(gW.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(gW.raw("begin"))}async commitTransaction(W){await W.executeQuery(gW.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(gW.raw("rollback"))}async releaseConnection(W){W[K$]()}async destroy(){if(this.#Z){let W=this.#Z;this.#Z=void 0,await W.end()}}},yQ=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new RJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},RJ=class{#W;#$;constructor(W){this.#W=W,this.#$=new M$({query:c4(this.#W.connectionString,{fullResults:!0})})}async init(){}async acquireConnection(){return this.#$}async beginTransaction(W,$){throw Error("Transactions are not supported with Neon HTTP connections")}async commitTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async rollbackTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async releaseConnection(W){}async destroy(){}};function u4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function wJ({pg_host:W,environment:$,...Z}){let J=Z.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let X;if($==="production")X=W;else if($==="development")if(W.includes("localhost"))X="localhost";else X="postgres-ws-proxy";else if($==="test"||$==="staging")X="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(u4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let U=`${X}${$!=="production"?":5433":""}/${$==="production"?"v2":"v1"}`;if(console.assert(!U.startsWith("ws://")&&!U.startsWith("wss://"),"Expected built postgres neon proxy websocket URL to not include protocol (ws:// or wss://)!"),J)console.log("[getPostgresNeonWsProxyUrl] Loaded websocket proxy URL: ",U);return U}var U$=wJ;function V$(W){return!isNaN(W)&&Number.isInteger(W)&&Number.isFinite(W)&&W>0}function Q9(W){if(typeof W==="number"){if(V$(W))return W}else if(typeof W==="string"){let $=Number.parseInt(W);if(V$($))return $}else throw TypeError(`Unexpected type for value to parse port number from: '${typeof W}'`);throw TypeError("Failed to parse port number for database configuration!")}function QJ(W){let $=process.env.SCHEMAVAULTS_DBH_DEBUG;if(typeof $==="string")if($.toLowerCase().includes("true"))return!0;else return!1;else if(W!=="production")return!0;else return!1}var P$=QJ;function SJ(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var G8=SJ;function _J(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var F$=_J;function EJ(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((D)=>typeof D!=="string"&&typeof D<"u"&&typeof D!=="number"&&typeof D!=="boolean")){let D=new Set(Object.values(W).map((P)=>typeof P));throw D.delete("undefined"),D.delete("string"),D.delete("number"),D.delete("boolean"),TypeError(`Received invalid database credentials; expected only strings or undefined in values object provided to parse credentials from. Received invalid types: ${Array.from(D).join(", ")}`)}let Z=G8(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!Z){if($)console.warn("POSTGRES_URL_NON_POOLING is not set in environment variables!")}else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres no-pooling connection url POSTGRES_URL_NON_POOLING: "${Z}"`);let J=G8(typeof W.POSTGRES_HOST==="string"?W.POSTGRES_HOST:void 0);if(!J)throw Error("POSTGRES_HOST is not set in environment variables!");else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using database POSTGRES_HOST: "${J}"`);let X=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)X=Number.parseInt(G8(W.POSTGRES_PORT)??"NaN");if(typeof X!=="number"||isNaN(X))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let Y=G8(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!Y)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let L=G8(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!L)throw Error("POSTGRES_USER is not defined in environment variables!");let G=G8(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!G)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let U="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)U=G8(W.POSTGRES_URL)??"";else U=F$({POSTGRES_DATABASE:Y,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_USER:L,POSTGRES_PASSWORD:G});if(!U)throw Error("Failed to load POSTGRES_URL from environment variables, or to construct it from other environment variables!");if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres connection url POSTGRES_URL: "${U}"`);return{POSTGRES_USER:L,POSTGRES_PASSWORD:G,POSTGRES_URL:U,POSTGRES_URL_NON_POOLING:Z,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_DATABASE:Y}}var l4=EJ;function hJ(W,$=!1){return l4(W,$)}var D$=hJ;class p4{credentials;kysely_db;env;debug;constructor(W){if(!u4(W.environment))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W.environment,this.debug=P$(this.env);let $=void 0;if(W.credentials){if(typeof W.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");$=l4(W.credentials,this.debug)}else $=D$(process.env,this.debug);if(!$)throw Error("Failed to parse database credentials from options or environment variables!");this.credentials=$;let J={dialect:this.initializeDbDialect(W),log:["query","error"]};this.kysely_db=new Q0(J)}get db(){return this.kysely_db}async destroy(){return await this.kysely_db.destroy()}async[Symbol.asyncDispose](){return await this.destroy()}}class i4 extends p4{initializeDbDialect(W){let $=this.debug,Z=this.env,J=this.credentials,X={connectionString:J.POSTGRES_URL,host:J.POSTGRES_HOST,user:J.POSTGRES_USER,password:J.POSTGRES_PASSWORD,database:J.POSTGRES_DATABASE,useSecureWebSocket:this.env==="production",port:Q9(J.POSTGRES_PORT),wsProxy:(L)=>{if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${L}")`);let G;try{let U={pg_host:L,environment:Z,debug:this.debug};if(typeof W.wsProxyUrl>"u"||!W.wsProxyUrl)G=U$(U);else if(typeof W.wsProxyUrl==="string"&&W.wsProxyUrl&&W.wsProxyUrl.length>0)G=W.wsProxyUrl;else if(typeof W.wsProxyUrl==="function"&&W.wsProxyUrl){let D=W.wsProxyUrl;G=D(U)}else throw Error(`Invalid wsProxy url for host: "${L}". Not a string, undefined, or function!`)}catch(U){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${L}") => Failure: `,U),Error(`Failed to calculate wsProxy url for host: "${L}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${L}") => `,G);return G}};if(this.debug)X.pipelineTLS=!1,X.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",X);return new z$(X)}constructor(W){super(W);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}}class S9{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let Z of $){if(!this.hasExpectedExtension(Z)){this.#W.onFileIgnored?.(Z,"Extension");continue}let J=this.#W.path.join(this.#W.migrationFolder,Z),X=this.#W.import?await this.#W.import(J):await import(J),Y=Z.substring(0,Z.lastIndexOf("."));if(R$(X?.default))W[Y]=X.default;else if(R$(X))W[Y]=X;else this.#W.onFileIgnored?.(Z,"NotMigration")}return W}hasExpectedExtension(W){return W.endsWith(".js")||W.endsWith(".ts")&&!W.endsWith(".d.ts")||W.endsWith(".mjs")||W.endsWith(".mts")&&!W.endsWith(".d.mts")||W.endsWith(".cjs")||W.endsWith(".cts")&&!W.endsWith(".d.cts")}}function R$(W){return Q1(W)&&D1(W.up)}import TJ from"fs/promises";import vJ from"path";import{existsSync as w$}from"fs";function Q$({db:W,migrationFolder:$}){return new X9({db:W,provider:new S9({fs:TJ,path:vJ,migrationFolder:$})})}function fJ(W){if(typeof W!=="object"||!W)throw TypeError("Expected migration result to be an object!");if(!("migrationName"in W)||typeof W.migrationName!=="string")throw TypeError("Expected migration result's 'migrationName' to be a string!");else if(!("direction"in W)||typeof W.direction!=="string")throw TypeError("Expected migration result's 'direction' to be a string!");else if(!("status"in W)||typeof W.status!=="string")throw TypeError("Expected migration result's 'status' to be a string!");else if(!["Up","Down"].includes(W.direction))throw TypeError("Expected migration result's 'direction' to be one of: 'Up' or 'Down'!");else if(!["Success","Error","NotExecuted"].includes(W.status))throw TypeError("Expected migration result's 'status' to be one of: 'Success', 'Error', or 'NotExecuted'!");return!0}function S$(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)fJ($);return!0}async function _$({db:W,migrationFolder:$,...Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!w$($))throw Error(`migrationFolder '${$}' does not exist`);let J=Q$({db:W,migrationFolder:$}),X;if(typeof Z.version==="string")X=await J.migrateTo(Z.version);else X=await J.migrateToLatest();let{error:Y,results:L}=X;if(Y)throw console.error(Y),Y;if(!L)return[];if(!S$(L))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return L}async function E$({db:W,migrationFolder:$,version:Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!w$($))throw Error(`migrationFolder '${$}' does not exist`);let J=Q$({db:W,migrationFolder:$}),{error:X,results:Y}=await J.migrateTo(Z);if(X)throw console.error(X),X;if(!Y)return[];if(!S$(Y))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return Y}import h$ from"fs";import jJ from"path";function _9(W){let $=jJ.resolve(W);if(!h$.existsSync($))throw Error(`Env file not found: ${$}`);let Z=h$.readFileSync($,"utf-8");for(let J of Z.split(`
56
+ `)){let X=J.trim();if(!X||X.startsWith("#"))continue;let Y=X.indexOf("=");if(Y===-1)continue;let L=X.slice(0,Y).trim(),G=X.slice(Y+1).trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);if(process.env[L]===void 0)process.env[L]=G}}import t4 from"fs";import T$ from"path";import{pathToFileURL as AJ}from"url";var NJ=[".ts",".mts",".cts",".js",".mjs",".cjs"],CJ=/^(\d{5})(?:\D|$)/;function qJ(W){if(W.startsWith("."))return!1;if(W.endsWith(".d.ts"))return!1;return NJ.some(($)=>W.endsWith($))}async function v$(W,$={}){let{duplicatesAsWarnings:Z=!1}=$,J=T$.resolve(W),X=[];if(!t4.existsSync(J))return{ok:!1,directory:J,migrationFiles:[],issues:[{level:"error",message:`Migration directory does not exist: ${J}`}]};if(!t4.statSync(J).isDirectory())return{ok:!1,directory:J,migrationFiles:[],issues:[{level:"error",message:`Migration path is not a directory: ${J}`}]};let G=t4.readdirSync(J,{withFileTypes:!0}).filter((P)=>P.isFile()&&qJ(P.name)).map((P)=>P.name).sort();if(G.length===0)return X.push({level:"error",message:`Migration directory is empty (no migration files found): ${J}`}),{ok:!1,directory:J,migrationFiles:G,issues:X};let U=new Map;for(let P of G){let w=CJ.exec(P);if(!w){X.push({level:"error",file:P,message:`File is not prefixed with a 5-digit migration number (e.g. 00000-my-migration.ts): ${P}`});continue}let R=w[1],S=U.get(R);if(S)S.push(P);else U.set(R,[P])}for(let[P,w]of U)if(w.length>1)X.push({level:Z?"warning":"error",message:`Duplicate migration number '${P}' used by ${w.length} files: ${w.join(", ")}`});for(let P of G){let w=T$.join(J,P),R;try{R=await import(AJ(w).href)}catch(S){X.push({level:"error",file:P,message:`Failed to import migration module '${P}': ${S instanceof Error?S.message:String(S)}`});continue}if(typeof R.up!=="function")X.push({level:"error",file:P,message:`Migration '${P}' does not export an up() function`});if(typeof R.down!=="function")X.push({level:"error",file:P,message:`Migration '${P}' does not export a down() function`})}return{ok:!X.some((P)=>P.level==="error"),directory:J,migrationFiles:G,issues:X}}var IJ=xJ(import.meta.url),{version:f$}=IJ("../package.json");if(typeof f$!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var _8=new t9;_8.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(f$);_8.command("migrate").description("Run database migrations forward (to latest or a specific version)").argument("<folder>","Path to the migration folder").argument("[version]","Target migration version (defaults to latest)").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)_9(Z.envFile);let J=sW.resolve(W),X=new i4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await _$({db:X.db,migrationFolder:J,version:$});for(let L of Y)console.log(`[${L.direction}] ${L.migrationName}: ${L.status}`);if(Y.length===0)console.log("No migrations to run.")}catch(Y){console.error("Migration failed:",Y),process.exit(1)}finally{await X.destroy()}});_8.command("reverse").description("Roll back database migrations to a specific version").argument("<folder>","Path to the migration folder").argument("<version>","Target version to roll back to").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)_9(Z.envFile);let J=sW.resolve(W),X=new i4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await E$({db:X.db,migrationFolder:J,version:$});for(let L of Y)console.log(`[${L.direction}] ${L.migrationName}: ${L.status}`);if(Y.length===0)console.log("No migrations to reverse.")}catch(Y){console.error("Reverse migration failed:",Y),process.exit(1)}finally{await X.destroy()}});_8.command("build-db-migrations").description("Build TypeScript Kysely migration files into JavaScript using Bun's bundler").argument("<migrations-src>","Directory containing .ts migration source files").requiredOption("--outdir <dir>","Output directory for compiled migration .js files").requiredOption("--sql-module <path>","Path to sql.ts source module to build alongside").option("--sql-outdir <dir>","Output directory for the built sql.js module (defaults to parent of --outdir)").option("--external <pkg...>","Packages to keep external in the bundle (default: @schemavaults/dbh, kysely)").option("--debug","Enable debug logging").action(async(W,$)=>{try{BJ("bun --version",{stdio:"ignore"})}catch{console.error("Error: 'bun' is required for build-db-migrations but was not found in PATH."),process.exit(1)}let Z=sW.dirname(OJ(import.meta.url)),X=["run",sW.resolve(Z,"build-db-migrations.js"),W];if(X.push("--outdir",$.outdir),X.push("--sql-module",$.sqlModule),$.sqlOutdir)X.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)X.push("--external",...$.external);if($.debug)X.push("--debug");bJ("bun",X,{stdio:"inherit",cwd:process.cwd()}).on("close",(L)=>{process.exit(L??1)})});_8.command("validate-migration-directory").alias("validate").description("Validate the shape of a migrations directory (5-digit prefixes, up()/down() exports, no duplicate numbers)").argument("<folder>","Path to the migrations directory").option("--duplicates-as-warnings","Report duplicate migration numbers as warnings instead of errors").action(async(W,$)=>{let Z=sW.resolve(W),J;try{J=await v$(Z,{duplicatesAsWarnings:$.duplicatesAsWarnings})}catch(X){console.error("Failed to validate migration directory:",X),process.exit(1)}for(let X of J.issues){let Y=X.level==="error"?"ERROR":"WARN";console.error(`[${Y}] ${X.message}`)}if(J.ok){let X=J.issues.filter((Y)=>Y.level==="warning").length;console.log(`✓ Migration directory is valid (${J.migrationFiles.length} migration${J.migrationFiles.length===1?"":"s"} checked${X>0?`, ${X} warning(s)`:""}): ${J.directory}`),process.exit(0)}else{let X=J.issues.filter((Y)=>Y.level==="error").length;console.error(`✗ Migration directory is invalid (${X} error(s)): ${J.directory}`),process.exit(1)}});var yS=_8;_8.parse();export{yS as default};