@schemavaults/dbh 0.8.2 → 0.8.4

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,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  import{createRequire as o7}from"node:module";var t7=Object.create;var{getPrototypeOf:s7,defineProperty:H9,getOwnPropertyNames:a7}=Object;var d7=Object.prototype.hasOwnProperty;var n7=(W,$,k)=>{k=W!=null?t7(s7(W)):{};let J=$||!W||!W.__esModule?H9(k,"default",{value:W,enumerable:!0}):k;for(let Z of a7(W))if(!d7.call(J,Z))H9(J,Z,{get:()=>W[Z],enumerable:!0});return J};var X0=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var $8=o7(import.meta.url);var k8=X0((r7)=>{class I4 extends Error{constructor(W,$,k){super(k);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=W,this.nestedError=void 0}}class z9 extends I4{constructor(W){super(1,"commander.invalidArgument",W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}r7.CommanderError=I4;r7.InvalidArgumentError=z9});var y8=X0((J$)=>{var{InvalidArgumentError:$$}=k8();class G9{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=($,k)=>{if(!this.argChoices.includes($))throw new $$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,k);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function k$(W){let $=W.name()+(W.variadic===!0?"...":"");return W.required?"<"+$+">":"["+$+"]"}J$.Argument=G9;J$.humanReadableArgName=k$});var y4=X0((H$)=>{var{humanReadableArgName:Y$}=y8();class M9{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),k=W._getHelpCommand();if(k&&!k._hidden)$.push(k);if(this.sortSubcommands)$.sort((J,Z)=>{return J.name().localeCompare(Z.name())});return $}compareOptions(W,$){let k=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return k(W).localeCompare(k($))}visibleOptions(W){let $=W.options.filter((J)=>!J.hidden),k=W._getHelpOption();if(k&&!k.hidden){let J=k.short&&W._findOption(k.short),Z=k.long&&W._findOption(k.long);if(!J&&!Z)$.push(k);else if(k.long&&!Z)$.push(W.createOption(k.long,k.description));else if(k.short&&!J)$.push(W.createOption(k.short,k.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(W){if(!this.showGlobalOptions)return[];let $=[];for(let k=W.parent;k;k=k.parent){let J=k.options.filter((Z)=>!Z.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((k)=>Y$(k)).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((k,J)=>{return Math.max(k,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(J))))},0)}longestOptionTermLength(W,$){return $.visibleOptions(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestGlobalOptionTermLength(W,$){return $.visibleGlobalOptions(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestArgumentTermLength(W,$){return $.visibleArguments(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleArgumentTerm($.argumentTerm(J))))},0)}commandUsage(W){let $=W._name;if(W._aliases[0])$=$+"|"+W._aliases[0];let k="";for(let J=W.parent;J;J=J.parent)k=J.name()+" "+k;return k+$+" "+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((k)=>JSON.stringify(k)).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 k=`(${$.join(", ")})`;if(W.description)return`${W.description} ${k}`;return k}return W.description}argumentDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((k)=>JSON.stringify(k)).join(", ")}`);if(W.defaultValue!==void 0)$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`);if($.length>0){let k=`(${$.join(", ")})`;if(W.description)return`${W.description} ${k}`;return k}return W.description}formatItemList(W,$,k){if($.length===0)return[];return[k.styleTitle(W),...$,""]}groupItems(W,$,k){let J=new Map;return W.forEach((Z)=>{let X=k(Z);if(!J.has(X))J.set(X,[])}),$.forEach((Z)=>{let X=k(Z);if(!J.has(X))J.set(X,[]);J.get(X).push(Z)}),J}formatHelp(W,$){let k=$.padWidth(W,$),J=$.helpWidth??80;function Z(R,h){return $.formatItem(R,k,h,$)}let X=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(W))}`,""],G=$.commandDescription(W);if(G.length>0)X=X.concat([$.boxWrap($.styleCommandDescription(G),J),""]);let z=$.visibleArguments(W).map((R)=>{return Z($.styleArgumentTerm($.argumentTerm(R)),$.styleArgumentDescription($.argumentDescription(R)))});if(X=X.concat(this.formatItemList("Arguments:",z,$)),this.groupItems(W.options,$.visibleOptions(W),(R)=>R.helpGroupHeading??"Options:").forEach((R,h)=>{let _=R.map((D)=>{return Z($.styleOptionTerm($.optionTerm(D)),$.styleOptionDescription($.optionDescription(D)))});X=X.concat(this.formatItemList(h,_,$))}),$.showGlobalOptions){let R=$.visibleGlobalOptions(W).map((h)=>{return Z($.styleOptionTerm($.optionTerm(h)),$.styleOptionDescription($.optionDescription(h)))});X=X.concat(this.formatItemList("Global Options:",R,$))}return this.groupItems(W.commands,$.visibleCommands(W),(R)=>R.helpGroup()||"Commands:").forEach((R,h)=>{let _=R.map((D)=>{return Z($.styleSubcommandTerm($.subcommandTerm(D)),$.styleSubcommandDescription($.subcommandDescription(D)))});X=X.concat(this.formatItemList(h,_,$))}),X.join(`
2
3
  `)}displayWidth(W){return L9(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,$,k,J){let X=" ".repeat(2);if(!k)return X+W;let G=W.padEnd($+W.length-J.displayWidth(W)),z=2,w=(this.helpWidth??80)-$-z-2,R;if(w<this.minWidthToWrap||J.preformatted(k))R=k;else R=J.boxWrap(k,w).replace(/\n/g,`
3
4
  `+" ".repeat($+z));return X+G+" ".repeat(z)+R.replace(/\n/g,`
@@ -23,7 +24,7 @@ Expecting one of '${k.join("', '")}'`);if(this._lifeCycleHooks[W])this._lifeCycl
23
24
  `),this.outputHelp({error:!0});let k=$||{},J=k.exitCode||1,Z=k.code||"commander.error";this._exit(J,Z,W)}_parseOptionsEnv(){this.options.forEach((W)=>{if(W.envVar&&W.envVar in XW.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()}`,XW.env[W.envVar]);else this.emit(`optionEnv:${W.name()}`)}})}_parseOptionsImplied(){let W=new v$(this.options),$=(k)=>{return this.getOptionValue(k)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(k))};this.options.filter((k)=>k.implied!==void 0&&$(k.attributeName())&&W.valueFromOption(this.getOptionValue(k.attributeName()),k)).forEach((k)=>{Object.keys(k.implied).filter((J)=>!$(J)).forEach((J)=>{this.setOptionValueWithSource(J,k.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 k=(X)=>{let G=X.attributeName(),z=this.getOptionValue(G),V=this.options.find((R)=>R.negate&&G===R.attributeName()),w=this.options.find((R)=>!R.negate&&G===R.attributeName());if(V&&(V.presetArg===void 0&&z===!1||V.presetArg!==void 0&&z===V.presetArg))return V;return w||X},J=(X)=>{let G=k(X),z=G.attributeName();if(this.getOptionValueSource(z)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},Z=`error: ${J(W)} cannot be used with ${J($)}`;this.error(Z,{code:"commander.conflictingOption"})}unknownOption(W){if(this._allowUnknownOption)return;let $="";if(W.startsWith("--")&&this._showSuggestionAfterError){let J=[],Z=this;do{let X=Z.createHelp().visibleOptions(Z).filter((G)=>G.long).map((G)=>G.long);J=J.concat(X),Z=Z.parent}while(Z&&!Z._enablePositionalOptions);$=w9(W,J)}let k=`error: unknown option '${W}'${$}`;this.error(k,{code:"commander.unknownOption"})}_excessArguments(W){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,k=$===1?"":"s",Z=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${k} but got ${W.length}.`;this.error(Z,{code:"commander.excessArguments"})}unknownCommand(){let W=this.args[0],$="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((Z)=>{if(J.push(Z.name()),Z.alias())J.push(Z.alias())}),$=w9(W,J)}let k=`error: unknown command '${W}'${$}`;this.error(k,{code:"commander.unknownCommand"})}version(W,$,k){if(W===void 0)return this._version;this._version=W,$=$||"-V, --version",k=k||"output the version number";let J=this.createOption($,k);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${W}
24
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 k=this.parent?._findCommand(W);if(k){let J=[k.name()].concat(k.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((k)=>{return D$(k)});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=A1.basename(W,A1.extname(W)),this}executableDir(W){if(W===void 0)return this._executableDir;return this._executableDir=W,this}helpInformation(W){let $=this.createHelp(),k=this._getOutputContext(W);$.prepareContext({error:k.error,helpWidth:k.helpWidth,outputHasColors:k.hasColors});let J=$.formatHelp(this,$);if(k.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(W){W=W||{};let $=!!W.error,k,J,Z;if($)k=(G)=>this._outputConfiguration.writeErr(G),J=this._outputConfiguration.getErrHasColors(),Z=this._outputConfiguration.getErrHelpWidth();else k=(G)=>this._outputConfiguration.writeOut(G),J=this._outputConfiguration.getOutHasColors(),Z=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(G)=>{if(!J)G=this._outputConfiguration.stripColor(G);return k(G)},hasColors:J,helpWidth:Z}}outputHelp(W){let $;if(typeof W==="function")$=W,W=void 0;let k=this._getOutputContext(W),J={error:k.error,write:k.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let Z=this.helpInformation({error:k.error});if($){if(Z=$(Z),typeof Z!=="string"&&!Buffer.isBuffer(Z))throw Error("outputHelp callback must return a string or a Buffer")}if(k.write(Z),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((X)=>X.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(XW.exitCode??0);if($===0&&W&&typeof W!=="function"&&W.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(W,$){let k=["beforeAll","before","after","afterAll"];if(!k.includes(W))throw Error(`Unexpected value for position to addHelpText.
25
26
  Expecting one of '${k.join("', '")}'`);let J=`${W}Help`;return this.on(J,(Z)=>{let X;if(typeof $==="function")X=$({error:Z.error,command:Z.command});else X=$;if(X)Z.write(`${X}
26
- `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function _9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let k,J="127.0.0.1",Z="9229",X;if((X=$.match(/^(--inspect(-brk)?)$/))!==null)k=X[1];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(k=X[1],/^\d+$/.test(X[3]))Z=X[3];else J=X[3];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)k=X[1],J=X[3],Z=X[4];if(k&&Z!=="0")return`${k}=${J}:${parseInt(Z)+1}`;return $})}function u4(){if(XW.env.NO_COLOR||XW.env.FORCE_COLOR==="0"||XW.env.FORCE_COLOR==="false")return!1;if(XW.env.FORCE_COLOR||XW.env.CLICOLOR_FORCE!==void 0)return!0;return}E$.Command=l4;E$.useColor=u4});var T9=X0((j$)=>{var{Argument:P9}=y8(),{Command:i4}=h9(),{CommanderError:O$,InvalidArgumentError:D9}=k8(),{Help:A$}=y4(),{Option:f9}=g4();j$.program=new i4;j$.createCommand=(W)=>new i4(W);j$.createOption=(W,$)=>new f9(W,$);j$.createArgument=(W,$)=>new P9(W,$);j$.Command=i4;j$.Option=f9;j$.Argument=P9;j$.Help=A$;j$.CommanderError=O$;j$.InvalidArgumentError=D9;j$.InvalidOptionArgumentError=D9});var v9=n7(T9(),1),{program:$J,createCommand:kJ,createArgument:JJ,createOption:ZJ,CommanderError:XJ,InvalidArgumentError:YJ,InvalidOptionArgumentError:HJ,Command:E9,Argument:zJ,Option:GJ,Help:MJ}=v9.default;import j4 from"path";import{fileURLToPath as m2}from"url";import{createRequire as c2}from"module";import{execSync as u2,spawn as l2}from"child_process";function aW(W){return typeof W>"u"||W===void 0}function _W(W){return typeof W==="string"}function u1(W){return typeof W==="number"}function Y0(W){return typeof W==="boolean"}function h0(W){return W===null}function S9(W){return W instanceof Date}function P0(W){return typeof W==="bigint"}function hW(W){return typeof W==="function"}function TW(W){return typeof W==="object"&&W!==null}function N9(W){return W[W.length-1]}function H(W){return Object.freeze(W)}function J8(W){if(bW(W))return W;else return[W]}function bW(W){return Array.isArray(W)}function yW(W){return W}var $W=H({is(W){return W.kind==="AlterTableNode"},create(W){return H({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return H({...W,...$})},cloneWithColumnAlteration(W,$){return H({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var i=H({is(W){return W.kind==="IdentifierNode"},create(W){return H({kind:"IdentifierNode",name:W})}});var X1=H({is(W){return W.kind==="CreateIndexNode"},create(W){return H({kind:"CreateIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});var m8=H({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return H({kind:"CreateSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var O9=["preserve rows","delete rows","drop"],BW=H({is(W){return W.kind==="CreateTableNode"},create(W){return H({kind:"CreateTableNode",table:W,columns:H([])})},cloneWithColumn(W,$){return H({...W,columns:H([...W.columns,$])})},cloneWithConstraint(W,$){return H({...W,constraints:W.constraints?H([...W.constraints,$]):H([$])})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWith(W,$){return H({...W,...$})}});var IW=H({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return H({kind:"SchemableIdentifierNode",identifier:i.create(W)})},createWithSchema(W,$){return H({kind:"SchemableIdentifierNode",schema:i.create(W),identifier:i.create($)})}});var l1=H({is(W){return W.kind==="DropIndexNode"},create(W,$){return H({kind:"DropIndexNode",name:IW.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var Z8=H({is(W){return W.kind==="DropSchemaNode"},create(W,$){return H({kind:"DropSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var X8=H({is(W){return W.kind==="DropTableNode"},create(W,$){return H({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return H({...W,...$})}});var AW=H({is(W){return W.kind==="AliasNode"},create(W,$){return H({kind:"AliasNode",node:W,alias:$})}});var mW=H({is(W){return W.kind==="TableNode"},create(W){return H({kind:"TableNode",table:IW.create(W)})},createWithSchema(W,$){return H({kind:"TableNode",table:IW.createWithSchema(W,$)})}});function LW(W){return TW(W)&&hW(W.toOperationNode)}function c8(W){return TW(W)&&"expressionType"in W&&LW(W)}function A9(W){return TW(W)&&"expression"in W&&_W(W.alias)&&LW(W)}var h1=H({is(W){return W.kind==="SelectModifierNode"},create(W,$){return H({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return H({kind:"SelectModifierNode",rawModifier:W})}});var cW=H({is(W){return W.kind==="AndNode"},create(W,$){return H({kind:"AndNode",left:W,right:$})}});var Y1=H({is(W){return W.kind==="OrNode"},create(W,$){return H({kind:"OrNode",left:W,right:$})}});var u8=H({is(W){return W.kind==="OnNode"},create(W){return H({kind:"OnNode",on:W})},cloneWithOperation(W,$,k){return H({...W,on:$==="And"?cW.create(W.on,k):Y1.create(W.on,k)})}});var H1=H({is(W){return W.kind==="JoinNode"},create(W,$){return H({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,k){return H({kind:"JoinNode",joinType:W,table:$,on:u8.create(k)})},cloneWithOn(W,$){return H({...W,on:W.on?u8.cloneWithOperation(W.on,"And",$):u8.create($)})}});var i1=H({is(W){return W.kind==="BinaryOperationNode"},create(W,$,k){return H({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:k})}});var u$=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],l$=["+","-","*","/","%","^","&","|","#","<<",">>"],j9=["->","->>"],i$=[...u$,...l$,"&&","||"],p$=["exists","not exists"],t$=["not","-",...p$],C9=[...i$,...j9,...t$,"between","between symmetric"],dW=H({is(W){return W.kind==="OperatorNode"},create(W){return H({kind:"OperatorNode",operator:W})}});function p4(W){return _W(W)&&j9.includes(W)}var WW=H({is(W){return W.kind==="ColumnNode"},create(W){return H({kind:"ColumnNode",column:i.create(W)})}});var D0=H({is(W){return W.kind==="SelectAllNode"},create(){return H({kind:"SelectAllNode"})}});var f0=H({is(W){return W.kind==="ReferenceNode"},create(W,$){return H({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return H({kind:"ReferenceNode",table:W,column:D0.create()})}});class t4{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return s4(this.#W)}}function l8(W){return TW(W)&&LW(W)&&_W(W.dynamicReference)}var z1=H({is(W){return W.kind==="OrderByItemNode"},create(W,$){return H({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return H({...W,...$})}});var YW=H({is(W){return W.kind==="RawNode"},create(W,$){return H({kind:"RawNode",sqlFragments:H(W),parameters:H($)})},createWithSql(W){return YW.create([W],[])},createWithChild(W){return YW.create(["",""],[W])},createWithChildren(W){return YW.create(Array(W.length+1).fill(""),W)}});var Q9=H({is(W){return W.kind==="CollateNode"},create(W){return H({kind:"CollateNode",collation:i.create(W)})}});class p1{#W;constructor(W){this.#W=H(W)}desc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("desc")})})}asc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("asc")})})}nullsLast(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new p1({node:z1.cloneWith(this.#W.node,{collation:Q9.create(W)})})}toOperationNode(){return this.#W.node}}var x9=new Set;function P1(W){if(x9.has(W))return;x9.add(W),console.log(W)}function d4(W){return W==="asc"||W==="desc"}function oW(W){if(W.length===2)return[a4(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return P1("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((k)=>a4(k));return[a4($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function a4(W,$){let k=s$(W);if(z1.is(k)){if($)throw Error("Cannot specify direction twice!");return k}return q9(k,$)}function s$(W){if(j1(W))return uW(W);if(l8(W))return W.toOperationNode();let[$,k]=W.split(" ");if(k)return P1("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),q9(nW($),k);return nW(W)}function q9(W,$){if(typeof $==="string"){if(!d4($))throw Error(`Invalid order by direction: ${$}`);return z1.create(W,YW.createWithSql($))}if(c8($))return P1("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),z1.create(W,$.toOperationNode());let k=z1.create(W);if(!$)return k;return $(new p1({node:k})).toOperationNode()}var T0=H({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return H({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return H({...W,traversal:$})}});var i8=H({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return H({kind:"JSONOperatorChainNode",operator:W,values:H([])})},cloneWithValue(W,$){return H({...W,values:H([...W.values,$])})}});var t1=H({is(W){return W.kind==="JSONPathNode"},create(W){return H({kind:"JSONPathNode",inOperator:W,pathLegs:H([])})},cloneWithLeg(W,$){return H({...W,pathLegs:H([...W.pathLegs,$])})}});function s4(W){if(_W(W))return nW(W);return W.toOperationNode()}function C1(W){if(bW(W))return W.map(($)=>xW($));else return[xW(W)]}function xW(W){if(j1(W))return uW(W);return s4(W)}function b9(W,$){let k=nW(W);if(p4($))return T0.create(k,i8.create(dW.create($)));let J=$.slice(0,-1);if(p4(J))return T0.create(k,t1.create(dW.create(J)));throw Error(`Invalid JSON operator: ${$}`)}function nW(W){if(!W.includes("."))return f0.create(WW.create(W));let k=W.split(".").map(o4);if(k.length===3)return a$(k);if(k.length===2)return d$(k);throw Error(`invalid column reference ${W}`)}function B9(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(o4);return AW.create(nW(k),i.create(J))}else return nW(W)}function n4(W){return WW.create(W)}function v0(W){if(W.includes(" ")){let[k,J]=W.split(" ").map(o4);if(!d4(J))throw Error(`invalid order direction "${J}" next to "${k}"`);return oW([k,J])[0]}else return n4(W)}function a$(W){let[$,k,J]=W;return f0.create(WW.create(J),mW.createWithSchema($,k))}function d$(W){let[$,k]=W;return f0.create(WW.create(k),mW.create($))}function o4(W){return W.trim()}var p8=H({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return H({kind:"PrimitiveValueListNode",values:H([...W])})}});var s1=H({is(W){return W.kind==="ValueListNode"},create(W){return H({kind:"ValueListNode",values:H(W)})}});var EW=H({is(W){return W.kind==="ValueNode"},create(W){return H({kind:"ValueNode",value:W})},createImmediate(W){return H({kind:"ValueNode",value:W,immediate:!0})}});function I9(W){if(bW(W))return n$(W);return zW(W)}function zW(W){if(j1(W))return uW(W);return EW.create(W)}function t8(W){return u1(W)||Y0(W)||h0(W)}function Y8(W){if(!t8(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return EW.createImmediate(W)}function n$(W){if(W.some(j1))return s1.create(W.map(($)=>zW($)));return p8.create(W)}var rW=H({is(W){return W.kind==="ParensNode"},create(W){return H({kind:"ParensNode",node:W})}});function MW(W){if(W.length===3)return s8(W[0],W[1],W[2]);else if(W.length===1)return zW(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function s8(W,$,k){if(o$($)&&g9(k))return i1.create(xW(W),r4($),EW.createImmediate(k));return i1.create(xW(W),r4($),I9(k))}function jW(W,$,k){return i1.create(xW(W),r4($),xW(k))}function e4(W,$){return E0(Object.entries(W).filter(([,k])=>!aW(k)).map(([k,J])=>s8(k,g9(J)?"is":"=",J)),$)}function E0(W,$,k=!0){let J=$==="and"?cW.create:Y1.create;if(W.length===0)return i1.create(EW.createImmediate(1),dW.create("="),EW.createImmediate($==="and"?1:0));let Z=y9(W[0]);for(let X=1;X<W.length;++X)Z=J(Z,y9(W[X]));if(W.length>1&&k)return rW.create(Z);return Z}function o$(W){return W==="is"||W==="is not"}function g9(W){return h0(W)||Y0(W)}function r4(W){if(_W(W)&&C9.includes(W))return dW.create(W);if(LW(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function y9(W){return LW(W)?W.toOperationNode():W}var Q1=H({is(W){return W.kind==="OrderByNode"},create(W){return H({kind:"OrderByNode",items:H([...W])})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var W6=H({is(W){return W.kind==="PartitionByNode"},create(W){return H({kind:"PartitionByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var H8=H({is(W){return W.kind==="OverNode"},create(){return H({kind:"OverNode"})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithPartitionByItems(W,$){return H({...W,partitionBy:W.partitionBy?W6.cloneWithItems(W.partitionBy,$):W6.create($)})}});var H0=H({is(W){return W.kind==="FromNode"},create(W){return H({kind:"FromNode",froms:H(W)})},cloneWithFroms(W,$){return H({...W,froms:H([...W.froms,...$])})}});var $6=H({is(W){return W.kind==="GroupByNode"},create(W){return H({kind:"GroupByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var k6=H({is(W){return W.kind==="HavingNode"},create(W){return H({kind:"HavingNode",having:W})},cloneWithOperation(W,$,k){return H({...W,having:$==="And"?cW.create(W.having,k):Y1.create(W.having,k)})}});var fW=H({is(W){return W.kind==="InsertQueryNode"},create(W,$,k){return H({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:k})},createWithoutInto(){return H({kind:"InsertQueryNode"})},cloneWith(W,$){return H({...W,...$})}});var a8=H({is(W){return W.kind==="ListNode"},create(W){return H({kind:"ListNode",items:H(W)})}});var D1=H({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return H({kind:"UpdateQueryNode",table:W.length===1?W[0]:a8.create(W),...$&&{with:$}})},createWithoutTable(){return H({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return H({...W,from:W.from?H0.cloneWithFroms(W.from,$):H0.create($)})},cloneWithUpdates(W,$){return H({...W,updates:W.updates?H([...W.updates,...$]):$})},cloneWithLimit(W,$){return H({...W,limit:$})}});var z8=H({is(W){return W.kind==="UsingNode"},create(W){return H({kind:"UsingNode",tables:H(W)})},cloneWithTables(W,$){return H({...W,tables:H([...W.tables,...$])})}});var a1=H({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return H({kind:"DeleteQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithUsing(W,$){return H({...W,using:W.using!==void 0?z8.cloneWithTables(W.using,$):z8.create($)})}});var qW=H({is(W){return W.kind==="WhereNode"},create(W){return H({kind:"WhereNode",where:W})},cloneWithOperation(W,$,k){return H({...W,where:$==="And"?cW.create(W.where,k):Y1.create(W.where,k)})}});var J6=H({is(W){return W.kind==="ReturningNode"},create(W){return H({kind:"ReturningNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var m9=H({is(W){return W.kind==="ExplainNode"},create(W,$){return H({kind:"ExplainNode",format:W,options:$})}});var k1=H({is(W){return W.kind==="WhenNode"},create(W){return H({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return H({...W,result:$})}});var eW=H({is(W){return W.kind==="MergeQueryNode"},create(W,$){return H({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return H({...W,using:$})},cloneWithWhen(W,$){return H({...W,whens:W.whens?H([...W.whens,$]):H([$])})},cloneWithThen(W,$){return H({...W,whens:W.whens?H([...W.whens.slice(0,-1),k1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var Z6=H({is(W){return W.kind==="OutputNode"},create(W){return H({kind:"OutputNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var g=H({is(W){return HW.is(W)||fW.is(W)||D1.is(W)||a1.is(W)||eW.is(W)},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWithWhere(W,$){return H({...W,where:W.where?qW.cloneWithOperation(W.where,"And",$):qW.create($)})},cloneWithJoin(W,$){return H({...W,joins:W.joins?H([...W.joins,$]):H([$])})},cloneWithReturning(W,$){return H({...W,returning:W.returning?J6.cloneWithSelections(W.returning,$):J6.create($)})},cloneWithoutReturning(W){return H({...W,returning:void 0})},cloneWithoutWhere(W){return H({...W,where:void 0})},cloneWithExplain(W,$,k){return H({...W,explain:m9.create($,k?.toOperationNode())})},cloneWithTop(W,$){return H({...W,top:$})},cloneWithOutput(W,$){return H({...W,output:W.output?Z6.cloneWithSelections(W.output,$):Z6.create($)})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithoutOrderBy(W){return H({...W,orderBy:void 0})}});var HW=H({is(W){return W.kind==="SelectQueryNode"},create(W){return H({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return H({kind:"SelectQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})},cloneWithDistinctOn(W,$){return H({...W,distinctOn:W.distinctOn?H([...W.distinctOn,...$]):H($)})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return H({...W,groupBy:W.groupBy?$6.cloneWithItems(W.groupBy,$):$6.create($)})},cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithOffset(W,$){return H({...W,offset:$})},cloneWithFetch(W,$){return H({...W,fetch:$})},cloneWithHaving(W,$){return H({...W,having:W.having?k6.cloneWithOperation(W.having,"And",$):k6.create($)})},cloneWithSetOperations(W,$){return H({...W,setOperations:W.setOperations?H([...W.setOperations,...$]):H([...$])})},cloneWithoutSelections(W){return H({...W,selections:[]})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithoutOffset(W){return H({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return H({...W,groupBy:void 0})}});class S0{#W;constructor(W){this.#W=H(W)}on(...W){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,MW(W))})}onRef(W,$,k){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,jW(W,$,k))})}onTrue(){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,YW.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var c9=H({is(W){return W.kind==="PartitionByItemNode"},create(W){return H({kind:"PartitionByItemNode",partitionBy:W})}});function u9(W){return C1(W).map(c9.create)}class N0{#W;constructor(W){this.#W=H(W)}orderBy(...W){return new N0({overNode:H8.cloneWithOrderByItems(this.#W.overNode,oW(W))})}clearOrderBy(){return new N0({overNode:g.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new N0({overNode:H8.cloneWithPartitionByItems(this.#W.overNode,u9(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var O0=H({is(W){return W.kind==="SelectionNode"},create(W){return H({kind:"SelectionNode",selection:W})},createSelectAll(){return H({kind:"SelectionNode",selection:D0.create()})},createSelectAllFromTable(W){return H({kind:"SelectionNode",selection:f0.createSelectAll(W)})}});function NW(W){if(hW(W))return NW(W(G1()));else if(bW(W))return W.map(($)=>l9($));else return[l9(W)]}function l9(W){if(_W(W))return O0.create(B9(W));else if(l8(W))return O0.create(W.toOperationNode());else return O0.create(d8(W))}function CW(W){if(!W)return[O0.createSelectAll()];else if(Array.isArray(W))return W.map(i9);else return[i9(W)]}function i9(W){if(_W(W))return O0.createSelectAllFromTable(kW(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var p9=H({is(W){return W.kind==="ValuesNode"},create(W){return H({kind:"ValuesNode",values:H(W)})}});var t9=H({is(W){return W.kind==="DefaultInsertValueNode"},create(){return H({kind:"DefaultInsertValueNode"})}});function n8(W){let $=hW(W)?W(G1()):W,k=bW($)?$:H([$]);return r$(k)}function r$(W){let $=e$(W);return[H([...$.keys()].map(WW.create)),p9.create(W.map((k)=>Wk(k,$)))]}function e$(W){let $=new Map;for(let k of W){let J=Object.keys(k);for(let Z of J)if(!$.has(Z)&&k[Z]!==void 0)$.set(Z,$.size)}return $}function Wk(W,$){let k=Object.keys(W),J=Array.from({length:$.size}),Z=!1,X=k.length;for(let z of k){let V=$.get(z);if(aW(V)){X--;continue}let w=W[z];if(aW(w)||j1(w))Z=!0;J[V]=w}if(X<$.size||Z){let z=t9.create();return s1.create(J.map((V)=>aW(V)?z:zW(V)))}return p8.create(J)}var X6=H({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return H({kind:"ColumnUpdateNode",column:W,value:$})}});function s9(...W){if(W.length===2)return[X6.create(xW(W[0]),zW(W[1]))];return G8(W[0])}function G8(W){let $=hW(W)?W(G1()):W;return Object.entries($).filter(([k,J])=>J!==void 0).map(([k,J])=>{return X6.create(WW.create(k),zW(J))})}var a9=H({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return H({kind:"OnDuplicateKeyNode",updates:W})}});class Y6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class M1 extends Error{node;constructor(W){super("no result");this.node=W}}function f1(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var gW=H({is(W){return W.kind==="OnConflictNode"},create(){return H({kind:"OnConflictNode"})},cloneWith(W,$){return H({...W,...$})},cloneWithIndexWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"And",$):qW.create($)})},cloneWithIndexOrWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"Or",$):qW.create($)})},cloneWithUpdateWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"And",$):qW.create($)})},cloneWithUpdateOrWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"Or",$):qW.create($)})},cloneWithoutIndexWhere(W){return H({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return H({...W,updateWhere:void 0})}});class T1{#W;constructor(W){this.#W=H(W)}column(W){let $=WW.create(W);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,$]):H([$])})})}columns(W){let $=W.map(WW.create);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,...$]):H($)})})}constraint(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{constraint:i.create(W)})})}expression(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new T1({...this.#W,onConflictNode:gW.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new d9({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new M8({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{updates:G8(W)})})}$call(W){return W(this)}}class d9{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.onConflictNode}}class M8{#W;constructor(W){this.#W=H(W)}where(...W){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new M8({...this.#W,onConflictNode:gW.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var n9=H({is(W){return W.kind==="TopNode"},create(W,$){return H({kind:"TopNode",expression:W,modifiers:$})}});function L1(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid top expression: ${W}`);if(!aW($)&&!$k($))throw Error(`Invalid top modifiers: ${$}`);return n9.create(W,$)}function $k(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var z0=H({is(W){return W.kind==="OrActionNode"},create(W){return H({kind:"OrActionNode",action:W})}});class GW{#W;constructor(W){this.#W=H(W)}values(W){let[$,k]=n8(W);return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:$,values:k})})}columns(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:H(W.map(WW.create))})})}expression(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{values:uW(W)})})}defaultValues(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new GW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orIgnore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orAbort(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("abort")})})}orFail(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("fail")})})}orReplace(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("replace")})})}orRollback(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("rollback")})})}top(W,$){return new GW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}onConflict(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onConflict:W(new T1({onConflictNode:gW.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onDuplicateKey:a9.create(G8(W))})})}returning(W){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW())})}output(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new GW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new GW({...this.#W})}$castTo(){return new GW(this.#W)}$narrowType(){return new GW(this.#W)}$assertType(){return new GW(this.#W)}withPlugin(W){return new GW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new Y6($.insertId,$.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new GW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class H6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var A0=H({is(W){return W.kind==="LimitNode"},create(W){return H({kind:"LimitNode",limit:W})}});class PW{#W;constructor(W){this.#W=H(W)}where(...W){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new PW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new PW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(W){return new PW({...this.#W,queryNode:a1.cloneWithUsing(this.#W.queryNode,K1(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 PW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}returning(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new PW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new PW({...this.#W,queryNode:a1.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new PW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new PW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new PW({...this.#W,queryNode:a1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}modifyEnd(W){return new PW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new PW({...this.#W})}$castTo(){return new PW(this.#W)}$narrowType(){return new PW(this.#W)}$assertType(){return new PW(this.#W)}withPlugin(W){return new PW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new H6($.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new PW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class z6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}class KW{#W;constructor(W){this.#W=H(W)}where(...W){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new KW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new KW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}from(W){return new KW({...this.#W,queryNode:D1.cloneWithFromItems(this.#W.queryNode,K1(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 KW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new KW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new KW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new KW({...this.#W,queryNode:D1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}set(...W){return new KW({...this.#W,queryNode:D1.cloneWithUpdates(this.#W.queryNode,s9(...W))})}returning(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}modifyEnd(W){return new KW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new KW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new KW({...this.#W})}$castTo(){return new KW(this.#W)}$narrowType(){return new KW(this.#W)}$assertType(){return new KW(this.#W)}withPlugin(W){return new KW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new z6($.numAffectedRows??BigInt(0),$.numChangedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new KW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}var G6=H({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return H({kind:"CommonTableExpressionNameNode",table:mW.create(W),columns:$?H($.map(WW.create)):void 0})}});var j0=H({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return H({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return H({...W,...$})}});class L8{#W;constructor(W){this.#W=H(W)}materialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function M6(W,$){let k=$(r9()).toOperationNode();if(hW(W))return W(kk(k)).toOperationNode();return j0.create(o9(W),k)}function kk(W){return($)=>{return new L8({node:j0.create(o9($),W)})}}function o9(W){if(W.includes("(")){let $=W.split(/[\(\)]/),k=$[0],J=$[1].split(",").map((Z)=>Z.trim());return G6.create(k,J)}else return G6.create(W)}var K8=H({is(W){return W.kind==="WithNode"},create(W,$){return H({kind:"WithNode",expressions:H([W]),...$})},cloneWithExpression(W,$){return H({...W,expressions:H([...W.expressions,$])})}});var e9=["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 W5(W){let $="";for(let k=0;k<W;++k)$+=Jk();return $}function Jk(){return e9[~~(Math.random()*e9.length)]}function e(){return new $5}class $5{#W;get queryId(){if(this.#W===void 0)this.#W=W5(8);return this.#W}}function I(W){return W}class U8{nodeStack=[];#W=H({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)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let k=this.transformNodeImpl(W,$);return this.nodeStack.pop(),H(k)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return H(W.map((k)=>this.transformNode(k,$)))}transformSelectQuery(W,$){return I({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 I({kind:"SelectionNode",selection:this.transformNode(W.selection,$)})}transformColumn(W,$){return I({kind:"ColumnNode",column:this.transformNode(W.column,$)})}transformAlias(W,$){return I({kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)})}transformTable(W,$){return I({kind:"TableNode",table:this.transformNode(W.table,$)})}transformFrom(W,$){return I({kind:"FromNode",froms:this.transformNodeList(W.froms,$)})}transformReference(W,$){return I({kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)})}transformAnd(W,$){return I({kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformOr(W,$){return I({kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformValueList(W,$){return I({kind:"ValueListNode",values:this.transformNodeList(W.values,$)})}transformParens(W,$){return I({kind:"ParensNode",node:this.transformNode(W.node,$)})}transformJoin(W,$){return I({kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)})}transformRaw(W,$){return I({kind:"RawNode",sqlFragments:H([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)})}transformWhere(W,$){return I({kind:"WhereNode",where:this.transformNode(W.where,$)})}transformInsertQuery(W,$){return I({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,$),ignore:W.ignore,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 I({kind:"ValuesNode",values:this.transformNodeList(W.values,$)})}transformDeleteQuery(W,$){return I({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 I({kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)})}transformCreateTable(W,$){return I({kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),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 I({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 I({kind:"AddColumnNode",column:this.transformNode(W.column,$)})}transformDropTable(W,$){return I({kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformOrderBy(W,$){return I({kind:"OrderByNode",items:this.transformNodeList(W.items,$)})}transformOrderByItem(W,$){return I({kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls})}transformGroupBy(W,$){return I({kind:"GroupByNode",items:this.transformNodeList(W.items,$)})}transformGroupByItem(W,$){return I({kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)})}transformUpdateQuery(W,$){return I({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 I({kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)})}transformLimit(W,$){return I({kind:"LimitNode",limit:this.transformNode(W.limit,$)})}transformOffset(W,$){return I({kind:"OffsetNode",offset:this.transformNode(W.offset,$)})}transformOnConflict(W,$){return I({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 I({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)})}transformCreateIndex(W,$){return I({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 I({kind:"ListNode",items:this.transformNodeList(W.items,$)})}transformDropIndex(W,$){return I({kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformPrimaryKeyConstraint(W,$){return I({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformUniqueConstraint(W,$){return I({kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformForeignKeyConstraint(W,$){return I({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 I({kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all})}transformReferences(W,$){return I({kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate})}transformCheckConstraint(W,$){return I({kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)})}transformWith(W,$){return I({kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive})}transformCommonTableExpression(W,$){return I({kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)})}transformCommonTableExpressionName(W,$){return I({kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)})}transformHaving(W,$){return I({kind:"HavingNode",having:this.transformNode(W.having,$)})}transformCreateSchema(W,$){return I({kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists})}transformDropSchema(W,$){return I({kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade})}transformAlterTable(W,$){return I({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 I({kind:"DropColumnNode",column:this.transformNode(W.column,$)})}transformRenameColumn(W,$){return I({kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)})}transformAlterColumn(W,$){return I({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 I({kind:"ModifyColumnNode",column:this.transformNode(W.column,$)})}transformAddConstraint(W,$){return I({kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)})}transformDropConstraint(W,$){return I({kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier})}transformRenameConstraint(W,$){return I({kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)})}transformCreateView(W,$){return I({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 I({kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData})}transformDropView(W,$){return I({kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade})}transformGenerated(W,$){return I({kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)})}transformDefaultValue(W,$){return I({kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)})}transformOn(W,$){return I({kind:"OnNode",on:this.transformNode(W.on,$)})}transformSelectModifier(W,$){return I({kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)})}transformCreateType(W,$){return I({kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)})}transformDropType(W,$){return I({kind:"DropTypeNode",name:this.transformNode(W.name,$),ifExists:W.ifExists})}transformExplain(W,$){return I({kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)})}transformSchemableIdentifier(W,$){return I({kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)})}transformAggregateFunction(W,$){return I({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 I({kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)})}transformPartitionBy(W,$){return I({kind:"PartitionByNode",items:this.transformNodeList(W.items,$)})}transformPartitionByItem(W,$){return I({kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)})}transformBinaryOperation(W,$){return I({kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)})}transformUnaryOperation(W,$){return I({kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)})}transformUsing(W,$){return I({kind:"UsingNode",tables:this.transformNodeList(W.tables,$)})}transformFunction(W,$){return I({kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)})}transformCase(W,$){return I({kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement})}transformWhen(W,$){return I({kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)})}transformJSONReference(W,$){return I({kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)})}transformJSONPath(W,$){return I({kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)})}transformJSONPathLeg(W,$){return I({kind:"JSONPathLegNode",type:W.type,value:W.value})}transformJSONOperatorChain(W,$){return I({kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)})}transformTuple(W,$){return I({kind:"TupleNode",values:this.transformNodeList(W.values,$)})}transformMergeQuery(W,$){return I({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 I({kind:"MatchedNode",not:W.not,bySource:W.bySource})}transformAddIndex(W,$){return I({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 I({kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)})}transformFetch(W,$){return I({kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier})}transformTop(W,$){return I({kind:"TopNode",expression:W.expression,modifiers:W.modifiers})}transformOutput(W,$){return I({kind:"OutputNode",selections:this.transformNodeList(W.selections,$)})}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}}var Zk=H({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),Xk={json_agg:!0,to_json:!0};class L6 extends U8{#W;#$=new Set;#k=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!this.#Z(W))return super.transformNodeImpl(W,$);let k=this.#X(W);for(let X of k)this.#k.add(X);let J=this.#z(W);for(let X of J)this.#$.add(X);let Z=super.transformNodeImpl(W,$);for(let X of J)this.#$.delete(X);for(let X of k)this.#k.delete(X);return Z}transformSchemableIdentifier(W,$){let k=super.transformSchemableIdentifier(W,$);if(k.schema||!this.#$.has(W.identifier.name))return k;return{...k,schema:i.create(this.#W)}}transformReferences(W,$){let k=super.transformReferences(W,$);if(k.table.table.schema)return k;return{...k,table:mW.createWithSchema(this.#W,k.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#J(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#J(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((k)=>mW.is(k)&&!k.table.schema?{...k,table:this.transformIdentifier(k.table.identifier,$)}:this.transformNode(k,$))}}#J(W,$,k){return Xk[W.func]?W[k].map((J)=>!mW.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[k],$)}#Z(W){return W.kind in Zk}#z(W){let $=new Set;if("name"in W&&W.name&&IW.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let k of W.from.froms)this.#Y(k,$);if("into"in W&&W.into)this.#Y(W.into,$);if("table"in W&&W.table)this.#Y(W.table,$);if("joins"in W&&W.joins)for(let k of W.joins)this.#Y(k.table,$);if("using"in W&&W.using)if(H1.is(W.using))this.#Y(W.using.table,$);else this.#Y(W.using,$);return $}#X(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#Y(W,$){if(mW.is(W))return this.#H(W.table,$);if(AW.is(W)&&mW.is(W.node))return this.#H(W.node.table,$);if(a8.is(W)){for(let k of W.items)this.#Y(k,$);return}if(z8.is(W)){for(let k of W.tables)this.#Y(k,$);return}}#H(W,$){let k=W.identifier.name;if(!this.#$.has(k)&&!this.#k.has(k))$.add(k)}#G(W,$){for(let k of W.expressions){let J=k.name.table.table.identifier.name;if(!this.#k.has(J))$.add(J)}}}class W1{#W;constructor(W){this.#W=new L6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var k5=H({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return H({kind:"MatchedNode",not:W,bySource:$})}});function K6(W,$,k){return k1.create(E0([k5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&k?jW($[0],$[1],$[2]):MW($)]:[]],"and",!1))}function C0(W){if(_W(W))return YW.create([W],[]);if(LW(W))return W.toOperationNode();return W}class o8{#W;#$;#k;constructor(){this.#W=new Promise((W,$)=>{this.#k=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{if(this.#$)this.#$(W)};reject=(W)=>{if(this.#k)this.#k(W)}}async function r8(W){let $=new o8,k=new o8;return W.provideConnection(async(J)=>{return $.resolve(J),await k.promise}).catch((J)=>$.reject(J)),H({connection:await $.promise,release:k.resolve})}var Yk=H([]);class V8{#W;constructor(W=Yk){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let k of this.#W){let J=k.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){return await this.provideConnection(async($)=>{let k=await $.executeQuery(W);if("numUpdatedOrDeletedRows"in k)P1("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#$(k,W.queryId)})}async*stream(W,$){let{connection:k,release:J}=await r8(this);try{for await(let Z of k.streamQuery(W,$))yield await this.#$(Z,W.queryId)}finally{J()}}async#$(W,$){for(let k of this.#W)W=await k.transformResult({result:W,queryId:$});return W}}class Q0 extends V8{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 Q0([...this.plugins,W])}withPlugins(W){return new Q0([...this.plugins,...W])}withPluginAtFront(W){return new Q0([W,...this.plugins])}withoutPlugins(){return new Q0([])}}var n1=new Q0;class U6{numChangedRows;constructor(W){this.numChangedRows=W}}class x1{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new x1({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new x1({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(...W){return new lW({...this.#W,queryNode:eW.cloneWithUsing(this.#W.queryNode,d1("Using",W))})}returning(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}}class lW{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new lW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new lW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,k){return this.#$([W,$,k],!0)}#$(W,$){return new V6({...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!0},W,$))})}whenNotMatched(){return this.#k([])}whenNotMatchedAnd(...W){return this.#k(W)}whenNotMatchedAndRef(W,$,k){return this.#k([W,$,k],!0)}whenNotMatchedBySource(){return this.#k([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#k(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,k){return this.#k([W,$,k],!0,!0)}returning(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}#k(W,$=!1,k=!1){let J={...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!1,bySource:k},W,$))};return new(k?V6:J5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new lW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new U6($.numAffectedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}}class V6{#W;constructor(W){this.#W=H(W)}thenDelete(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("delete"))})}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenUpdate(W){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(W(new KW({queryId:this.#W.queryId,executor:n1,queryNode:D1.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class J5{#W;constructor(W){this.#W=H(W)}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenInsertValues(W){let[$,k]=n8(W);return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(fW.cloneWith(fW.createWithoutInto(),{columns:$,values:k})))})}}class v1{#W;constructor(W){this.#W=H(W)}selectFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.createFrom(K1(W),this.#W.withNode)})}selectNoFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.cloneWithSelections(HW.create(this.#W.withNode),NW(W))})}insertInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode)})}replaceInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode,!0)})}deleteFrom(W){return new PW({queryId:e(),executor:this.#W.executor,queryNode:a1.create(K1(W),this.#W.withNode)})}updateTable(W){return new KW({queryId:e(),executor:this.#W.executor,queryNode:D1.create(K1(W),this.#W.withNode)})}mergeInto(W){return new x1({queryId:e(),executor:this.#W.executor,queryNode:eW.create(R6(W),this.#W.withNode)})}with(W,$){let k=M6(W,$);return new v1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k)})}withRecursive(W,$){let k=M6(W,$);return new v1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k,{recursive:!0})})}withPlugin(W){return new v1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new v1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new v1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}}function r9(){return new v1({executor:n1})}function Z5(W,$){return new S0({joinNode:H1.create(W,G0($))})}function X5(){return new N0({overNode:H8.create()})}function d1(W,$){if($.length===3)return zk(W,$[0],$[1],$[2]);else if($.length===2)return Hk(W,$[0],$[1]);else if($.length===1)return Gk(W,$[0]);else throw Error("not implemented")}function Hk(W,$,k){return k(Z5(W,$)).toOperationNode()}function zk(W,$,k,J){return H1.createWithOn(W,G0($),jW(k,"=",J))}function Gk(W,$){return H1.create(W,G0($))}var Y5=H({is(W){return W.kind==="OffsetNode"},create(W){return H({kind:"OffsetNode",offset:W})}});var H5=H({is(W){return W.kind==="GroupByItemNode"},create(W){return H({kind:"GroupByItemNode",groupBy:W})}});function z5(W){return W=hW(W)?W(G1()):W,C1(W).map(H5.create)}var e8=H({is(W){return W.kind==="SetOperationNode"},create(W,$,k){return H({kind:"SetOperationNode",operator:W,expression:$,all:k})}});function M0(W,$,k){if(hW($))$=$(W4());if(!bW($))$=[$];return $.map((J)=>e8.create(W,uW(J),k))}class ZW{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new ZW(this.#W)}$notNull(){return new ZW(this.#W)}toOperationNode(){return this.#W}}class J4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}class $4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}$castTo(){return new $4(this.#W)}toOperationNode(){return rW.create(this.#W)}}class k4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new k4(this.#W)}toOperationNode(){return rW.create(this.#W)}}var G5=H({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:EW.create(W),modifier:$}}});function M5(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid fetch row count: ${W}`);if(!Mk($))throw Error(`Invalid fetch modifier: ${$}`);return G5.create(W,$)}function Mk(W){return W==="only"||W==="with ties"}class d{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}having(...W){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,MW(W))})}havingRef(W,$,k){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,jW(W,$,k))})}select(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,NW(W))})}distinctOn(W){return new d({...this.#W,queryNode:HW.cloneWithDistinctOn(this.#W.queryNode,C1(W))})}modifyFront(W){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}distinct(){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.create("Distinct"))})}forUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForUpdate",W?J8(W).map(kW):void 0))})}forShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForShare",W?J8(W).map(kW):void 0))})}forKeyShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForKeyShare",W?J8(W).map(kW):void 0))})}forNoKeyUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForNoKeyUpdate",W?J8(W).map(kW):void 0))})}skipLocked(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("SkipLocked"))})}noWait(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("NoWait"))})}selectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,CW(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 d({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new d({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}groupBy(W){return new d({...this.#W,queryNode:HW.cloneWithGroupByItems(this.#W.queryNode,z5(W))})}limit(W){return new d({...this.#W,queryNode:HW.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}offset(W){return new d({...this.#W,queryNode:HW.cloneWithOffset(this.#W.queryNode,Y5.create(zW(W)))})}fetch(W,$="only"){return new d({...this.#W,queryNode:HW.cloneWithFetch(this.#W.queryNode,M5(W,$))})}top(W,$){return new d({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}union(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!1))})}unionAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!0))})}intersect(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!1))})}intersectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!0))})}except(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!1))})}exceptAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!0))})}as(W){return new L5(this,W)}clearSelect(){return new d({...this.#W,queryNode:HW.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new d({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new d({...this.#W,queryNode:HW.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new d({...this.#W,queryNode:HW.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new d({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new d({...this.#W,queryNode:HW.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new d({...this.#W})}$castTo(){return new d(this.#W)}$narrowType(){return new d(this.#W)}$assertType(){return new d(this.#W)}$asTuple(){return new ZW(this.toOperationNode())}$asScalar(){return new ZW(this.toOperationNode())}withPlugin(W){return new d({...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(){let W=this.compile();return(await this.#W.executor.executeQuery(W)).rows}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new d({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}function x0(W){return new d(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 AW.create(this.#W.toOperationNode(),i.create(this.#$))}}var E1=H({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return H({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return H({...W,distinct:!0})},cloneWithOrderBy(W,$,k=!1){let J=k?"withinGroup":"orderBy";return H({...W,[J]:W[J]?Q1.cloneWithItems(W[J],$):Q1.create($)})},cloneWithFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"And",$):qW.create($)})},cloneWithOrFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"Or",$):qW.create($)})},cloneWithOver(W,$){return H({...W,over:$})}});var F6=H({is(W){return W.kind==="FunctionNode"},create(W,$){return H({kind:"FunctionNode",func:W,arguments:$})}});class iW{#W;constructor(W){this.#W=H(W)}get expressionType(){return}as(W){return new K5(this,W)}distinct(){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithOrderByItems(this.#W.aggregateFunctionNode,oW(W))})}clearOrderBy(){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithOrderBy(this.#W.aggregateFunctionNode,oW(W),!0)})}filterWhere(...W){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithFilter(this.#W.aggregateFunctionNode,MW(W))})}filterWhereRef(W,$,k){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithFilter(this.#W.aggregateFunctionNode,jW(W,$,k))})}over(W){let $=X5();return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new iW(this.#W)}$notNull(){return new iW(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class K5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),i.create(this.#$))}}function Z4(){let W=(k,J)=>{return new ZW(F6.create(k,C1(J??[])))},$=(k,J)=>{return new iW({aggregateFunctionNode:E1.create(k,J?C1(J):void 0)})};return Object.assign(W,{agg:$,avg(k){return $("avg",[k])},coalesce(...k){return W("coalesce",k)},count(k){return $("count",[k])},countAll(k){return new iW({aggregateFunctionNode:E1.create("count",CW(k))})},max(k){return $("max",[k])},min(k){return $("min",[k])},sum(k){return $("sum",[k])},any(k){return W("any",[k])},jsonAgg(k){return new iW({aggregateFunctionNode:E1.create("json_agg",[_W(k)?kW(k):k.toOperationNode()])})},toJson(k){return new ZW(F6.create("to_json",[_W(k)?kW(k):k.toOperationNode()]))}})}var U5=H({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return H({kind:"UnaryOperationNode",operator:W,operand:$})}});function V5(W,$){return U5.create(dW.create(W),xW($))}var $1=H({is(W){return W.kind==="CaseNode"},create(W){return H({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return H({...W,when:H(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return H({...W,when:W.when?H([...W.when.slice(0,-1),k1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return H({...W,...$})}});class R8{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}}class w6{#W;constructor(W){this.#W=H(W)}then(W){return new R5({...this.#W,node:$1.cloneWithThen(this.#W.node,t8(W)?Y8(W):zW(W))})}}class R5{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}else(W){return new F5({...this.#W,node:$1.cloneWith(this.#W.node,{else:t8(W)?Y8(W):zW(W)})})}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}class F5{#W;constructor(W){this.#W=H(W)}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}var _6=H({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return H({kind:"JSONPathLegNode",type:W,value:$})}});class w8{#W;constructor(W){this.#W=W}at(W){return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(T0.is(this.#W))return new F8(T0.cloneWithTraversal(this.#W,t1.is(this.#W.traversal)?t1.cloneWithLeg(this.#W.traversal,_6.create(W,$)):i8.cloneWithValue(this.#W.traversal,EW.createImmediate($))));return new F8(t1.cloneWithLeg(this.#W,_6.create(W,$)))}}class F8 extends w8{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new w5(this,W)}$castTo(){return new F8(this.#W)}$notNull(){return new F8(this.#W)}toOperationNode(){return this.#W}}class w5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var h6=H({is(W){return W.kind==="TupleNode"},create(W){return H({kind:"TupleNode",values:H(W)})}});var Lk=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],Kk=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],_5=H({is(W){return W.kind==="DataTypeNode"},create(W){return H({kind:"DataTypeNode",dataType:W})}});function h5(W){if(Lk.includes(W))return!0;if(Kk.some(($)=>$.test(W)))return!0;return!1}function U1(W){if(LW(W))return W.toOperationNode();if(h5(W))return _5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var P5=H({is(W){return W.kind==="CastNode"},create(W,$){return H({kind:"CastNode",expression:W,dataType:$})}});function W4(W=n1){function $(Z,X,G){return new ZW(s8(Z,X,G))}function k(Z,X){return new ZW(V5(Z,X))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(Z){return x0({queryId:e(),executor:W,queryNode:HW.createFrom(K1(Z))})},case(Z){return new R8({node:$1.create(aW(Z)?void 0:xW(Z))})},ref(Z,X){if(aW(X))return new ZW(nW(Z));return new w8(b9(Z,X))},jsonPath(){return new w8(t1.create())},table(Z){return new ZW(kW(Z))},val(Z){return new ZW(zW(Z))},refTuple(...Z){return new ZW(h6.create(Z.map(xW)))},tuple(...Z){return new ZW(h6.create(Z.map(zW)))},lit(Z){return new ZW(Y8(Z))},unary:k,not(Z){return k("not",Z)},exists(Z){return k("exists",Z)},neg(Z){return k("-",Z)},between(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between"),cW.create(zW(X),zW(G))))},betweenSymmetric(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between symmetric"),cW.create(zW(X),zW(G))))},and(Z){if(bW(Z))return new ZW(E0(Z,"and"));return new ZW(e4(Z,"and"))},or(Z){if(bW(Z))return new ZW(E0(Z,"or"));return new ZW(e4(Z,"or"))},parens(...Z){let X=MW(Z);if(rW.is(X))return new ZW(X);else return new ZW(rW.create(X))},cast(Z,X){return new ZW(P5.create(xW(Z),U1(X)))},withSchema(Z){return W4(W.withPluginAtFront(new W1(Z)))}});return J.fn=Z4(),J.eb=J,J}function G1(W){return W4()}function uW(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function d8(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function j1(W){return c8(W)||A9(W)||hW(W)}class P6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new D5(this.#W,W)}}class D5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return AW.create(kW(this.#W),i.create(this.#$))}}function f5(W){return TW(W)&&LW(W)&&_W(W.table)&&_W(W.alias)}function K1(W){if(bW(W))return W.map(($)=>G0($));else return[G0(W)]}function G0(W){if(_W(W))return R6(W);else if(f5(W))return W.toOperationNode();else return d8(W)}function R6(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(T5);return AW.create(kW(k),i.create(J))}else return kW(W)}function kW(W){if(W.includes(".")){let[k,J]=W.split(".").map(T5);return mW.createWithSchema(k,J)}else return mW.create(W)}function T5(W){return W.trim()}var D6=H({is(W){return W.kind==="AddColumnNode"},create(W){return H({kind:"AddColumnNode",column:W})}});var UW=H({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return H({kind:"ColumnDefinitionNode",column:WW.create(W),dataType:$})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):[$]})},cloneWith(W,$){return H({...W,...$})}});var f6=H({is(W){return W.kind==="DropColumnNode"},create(W){return H({kind:"DropColumnNode",column:WW.create(W)})}});var T6=H({is(W){return W.kind==="RenameColumnNode"},create(W,$){return H({kind:"RenameColumnNode",column:WW.create(W),renameTo:WW.create($)})}});var q0=H({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return H({kind:"CheckConstraintNode",expression:W,name:$?i.create($):void 0})}});var v5=["no action","restrict","cascade","set null","set default"],b0=H({is(W){return W.kind==="ReferencesNode"},create(W,$){return H({kind:"ReferencesNode",table:W,columns:H([...$])})},cloneWithOnDelete(W,$){return H({...W,onDelete:$})},cloneWithOnUpdate(W,$){return H({...W,onUpdate:$})}});function X4(W){return LW(W)?W.toOperationNode():EW.createImmediate(W)}var _8=H({is(W){return W.kind==="GeneratedNode"},create(W){return H({kind:"GeneratedNode",...W})},createWithExpression(W){return H({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return H({...W,...$})}});var E5=H({is(W){return W.kind==="DefaultValueNode"},create(W){return H({kind:"DefaultValueNode",defaultValue:W})}});function B0(W){if(v5.includes(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class VW{#W;constructor(W){this.#W=W}autoIncrement(){return new VW(UW.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new VW(UW.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new VW(UW.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=nW(W);if(!$.table||D0.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new VW(UW.cloneWith(this.#W,{references:b0.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnDelete(this.#W.references,B0(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnUpdate(this.#W.references,B0(W))}))}unique(){return new VW(UW.cloneWith(this.#W,{unique:!0}))}notNull(){return new VW(UW.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new VW(UW.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new VW(UW.cloneWith(this.#W,{defaultTo:E5.create(X4(W))}))}check(W){return new VW(UW.cloneWith(this.#W,{check:q0.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new VW(UW.cloneWith(this.#W,{generated:_8.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new VW(UW.cloneWith(this.#W,{generated:_8.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new VW(UW.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new VW(UW.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new VW(UW.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new VW(UW.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var v6=H({is(W){return W.kind==="ModifyColumnNode"},create(W){return H({kind:"ModifyColumnNode",column:W})}});var V1=H({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,k,J){return H({kind:"ForeignKeyConstraintNode",columns:W,references:b0.create($,k),name:J?i.create(J):void 0})},cloneWith(W,$){return H({...W,...$})}});class R1{#W;constructor(W){this.#W=W}onDelete(W){return new R1(V1.cloneWith(this.#W,{onDelete:B0(W)}))}onUpdate(W){return new R1(V1.cloneWith(this.#W,{onUpdate:B0(W)}))}deferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var I0=H({is(W){return W.kind==="AddConstraintNode"},create(W){return H({kind:"AddConstraintNode",constraint:W})}});var S1=H({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,k){return H({kind:"UniqueConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0,nullsNotDistinct:k})},cloneWith(W,$){return H({...W,...$})}});var y0=H({is(W){return W.kind==="DropConstraintNode"},create(W){return H({kind:"DropConstraintNode",constraintName:i.create(W)})},cloneWith(W,$){return H({...W,...$})}});var g0=H({is(W){return W.kind==="AlterColumnNode"},create(W,$,k){return H({kind:"AlterColumnNode",column:WW.create(W),[$]:k})}});class Y4{#W;constructor(W){this.#W=W}setDataType(W){return new m0(g0.create(this.#W,"dataType",U1(W)))}setDefault(W){return new m0(g0.create(this.#W,"setDefault",X4(W)))}dropDefault(){return new m0(g0.create(this.#W,"dropDefault",!0))}setNotNull(){return new m0(g0.create(this.#W,"setNotNull",!0))}dropNotNull(){return new m0(g0.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class m0{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class o1{#W;constructor(W){this.#W=H(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(){await this.#W.executor.executeQuery(this.compile())}}class q1{#W;constructor(W){this.#W=H(W)}onDelete(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class L0{#W;constructor(W){this.#W=H(W)}ifExists(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.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(){await this.#W.executor.executeQuery(this.compile())}}var b1=H({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return H({kind:"PrimaryKeyConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0})},cloneWith(W,$){return H({...W,...$})}});var r1=H({is(W){return W.kind==="AddIndexNode"},create(W){return H({kind:"AddIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});class e1{#W;constructor(W){this.#W=H(W)}unique(){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[v0(W)])})})}columns(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,W.map(v0))})})}expression(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{using:YW.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(){await this.#W.executor.executeQuery(this.compile())}}class N1{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N1(S1.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class B1{#W;constructor(W){this.#W=W}deferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class h8{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var S5=H({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return H({kind:"RenameConstraintNode",oldName:i.create(W),newName:i.create($)})}});class E6{#W;constructor(W){this.#W=H(W)}renameTo(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameTo:kW(W)})})}setSchema(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{setSchema:i.create(W)})})}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,v6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new q1({...this.#W,constraintBuilder:X})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}dropConstraint(W){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.create(W)})})}renameConstraint(W,$){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameConstraint:S5.create(W,$)})})}addIndex(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.create(W)})})}dropIndex(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropIndex:l1.create(W)})})}$call(W){return W(this)}}class F1{#W;constructor(W){this.#W=H(W)}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,v6.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(){await this.#W.executor.executeQuery(this.compile())}}class P8 extends U8{transformPrimitiveValueList(W){return s1.create(W.values.map(EW.createImmediate))}transformValue(W){return EW.createImmediate(W.value)}}class J1{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{table:kW(W)})})}column(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[v0(W)])})}columns(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,W.map(v0))})}expression(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{using:YW.createWithSql(W)})})}where(...W){let $=new P8;return new J1({...this.#W,node:g.cloneWithWhere(this.#W.node,$.transformNode(MW(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(){await this.#W.executor.executeQuery(this.compile())}}class H4{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new H4({...this.#W,node:m8.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(){await this.#W.executor.executeQuery(this.compile())}}function N5(W){if(O9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class pW{#W;constructor(W){this.#W=H(W)}temporary(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{onCommit:N5(W)})})}ifNotExists(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new pW({...this.#W,node:BW.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,X.toOperationNode())})}modifyFront(W){return new pW({...this.#W,node:BW.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new pW({...this.#W,node:BW.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{selectQuery:uW(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(){await this.#W.executor.executeQuery(this.compile())}}class c0{#W;constructor(W){this.#W=H(W)}on(W){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{table:kW(W)})})}ifExists(){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new c0({...this.#W,node:l1.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(){await this.#W.executor.executeQuery(this.compile())}}class D8{#W;constructor(W){this.#W=H(W)}ifExists(){return new D8({...this.#W,node:Z8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new D8({...this.#W,node:Z8.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(){await this.#W.executor.executeQuery(this.compile())}}class f8{#W;constructor(W){this.#W=H(W)}ifExists(){return new f8({...this.#W,node:X8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new f8({...this.#W,node:X8.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(){await this.#W.executor.executeQuery(this.compile())}}var w1=H({is(W){return W.kind==="CreateViewNode"},create(W){return H({kind:"CreateViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class S6{#W=new P8;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class I1{#W;constructor(W){this.#W=H(W)}temporary(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{columns:W.map(n4)})})}as(W){let $=W.withPlugin(new S6).toOperationNode();return new I1({...this.#W,node:w1.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(){await this.#W.executor.executeQuery(this.compile())}}var u0=H({is(W){return W.kind==="DropViewNode"},create(W){return H({kind:"DropViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class l0{#W;constructor(W){this.#W=H(W)}materialized(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new l0({...this.#W,node:u0.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(){await this.#W.executor.executeQuery(this.compile())}}var z4=H({is(W){return W.kind==="CreateTypeNode"},create(W){return H({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return H({...W,enum:s1.create($.map(EW.createImmediate))})}});class G4{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new G4({...this.#W,node:z4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var M4=H({is(W){return W.kind==="DropTypeNode"},create(W){return H({kind:"DropTypeNode",name:W})},cloneWith(W,$){return H({...W,...$})}});class L4{#W;constructor(W){this.#W=H(W)}ifExists(){return new L4({...this.#W,node:M4.cloneWith(this.#W.node,{ifExists:!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(){await this.#W.executor.executeQuery(this.compile())}}function N6(W){if(W.includes(".")){let k=W.split(".").map(Uk);if(k.length===2)return IW.createWithSchema(k[0],k[1]);else throw Error(`invalid schemable identifier ${W}`)}else return IW.create(W)}function Uk(W){return W.trim()}var i0=H({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return H({kind:"RefreshMaterializedViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class p0{#W;constructor(W){this.#W=H(W)}concurrently(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new p0({...this.#W,node:i0.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(){await this.#W.executor.executeQuery(this.compile())}}class t0{#W;constructor(W){this.#W=W}createTable(W){return new pW({queryId:e(),executor:this.#W,node:BW.create(kW(W))})}dropTable(W){return new f8({queryId:e(),executor:this.#W,node:X8.create(kW(W))})}createIndex(W){return new J1({queryId:e(),executor:this.#W,node:X1.create(W)})}dropIndex(W){return new c0({queryId:e(),executor:this.#W,node:l1.create(W)})}createSchema(W){return new H4({queryId:e(),executor:this.#W,node:m8.create(W)})}dropSchema(W){return new D8({queryId:e(),executor:this.#W,node:Z8.create(W)})}alterTable(W){return new E6({queryId:e(),executor:this.#W,node:$W.create(kW(W))})}createView(W){return new I1({queryId:e(),executor:this.#W,node:w1.create(W)})}refreshMaterializedView(W){return new p0({queryId:e(),executor:this.#W,node:i0.create(W)})}dropView(W){return new l0({queryId:e(),executor:this.#W,node:u0.create(W)})}createType(W){return new G4({queryId:e(),executor:this.#W,node:z4.create(N6(W))})}dropType(W){return new L4({queryId:e(),executor:this.#W,node:M4.create(N6(W))})}withPlugin(W){return new t0(this.#W.withPlugin(W))}withoutPlugins(){return new t0(this.#W.withoutPlugins())}withSchema(W){return new t0(this.#W.withPluginAtFront(new W1(W)))}}class O6{ref(W){return new t4(W)}table(W){return new P6(W)}}class A6{#W;constructor(W){this.#W=W}async provideConnection(W){let $=await this.#W.acquireConnection();try{return await W($)}finally{await this.#W.releaseConnection($)}}}class W0 extends V8{#W;#$;#k;constructor(W,$,k,J=[]){super(J);this.#W=W,this.#$=$,this.#k=k}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W){return this.#k.provideConnection(W)}withPlugins(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,...W])}withPlugin(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,W])}withPluginAtFront(W){return new W0(this.#W,this.#$,this.#k,[W,...this.plugins])}withConnectionProvider(W){return new W0(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new W0(this.#W,this.#$,this.#k,[])}}function K4(){if(typeof performance<"u"&&hW(performance.now))return performance.now();else return Date.now()}class j6{#W;#$;#k;#J;#Z;#z=new WeakSet;constructor(W,$){this.#J=!1,this.#W=W,this.#$=$}async init(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#k)this.#k=this.#W.init().then(()=>{this.#J=!0}).catch((W)=>{return this.#k=void 0,Promise.reject(W)});await this.#k}async acquireConnection(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#J)await this.init();let W=await this.#W.acquireConnection();if(!this.#z.has(W)){if(this.#X())this.#Y(W);this.#z.add(W)}return W}async releaseConnection(W){await this.#W.releaseConnection(W)}beginTransaction(W,$){return this.#W.beginTransaction(W,$)}commitTransaction(W){return this.#W.commitTransaction(W)}rollbackTransaction(W){return this.#W.rollbackTransaction(W)}savepoint(W,$,k){if(this.#W.savepoint)return this.#W.savepoint(W,$,k);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(W,$,k){if(this.#W.rollbackToSavepoint)return this.#W.rollbackToSavepoint(W,$,k);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(W,$,k){if(this.#W.releaseSavepoint)return this.#W.releaseSavepoint(W,$,k);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#k)return;if(await this.#k,!this.#Z)this.#Z=this.#W.destroy().catch((W)=>{return this.#Z=void 0,Promise.reject(W)});await this.#Z}#X(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#Y(W){let{executeQuery:$,streamQuery:k}=W,J=this;W.executeQuery=async(Z)=>{let X,G=K4();try{return await $.call(W,Z)}catch(z){throw X=z,await J.#H(z,Z,G),z}finally{if(!X)await J.#G(Z,G)}},W.streamQuery=async function*(Z,X){let G,z=K4();try{for await(let V of k.call(W,Z,X))yield V}catch(V){throw G=V,await J.#H(V,Z,z),V}finally{if(!G)await J.#G(Z,z,!0)}}}async#H(W,$,k){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#L(k)}))}async#G(W,$,k=!1){await this.#$.query(()=>({level:"query",isStream:k,query:W,queryDurationMillis:this.#L($)}))}#L(W){return K4()-W}}var Vk=()=>{};class T8{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch(Vk);return this.#$=this.#k(W).finally(()=>{this.#$=void 0}),this.#$}async#k(W){return await W(this.#W)}}var Rk=["read only","read write"],Fk=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function C6(W){if(W.accessMode&&!Rk.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!Fk.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var wk=["query","error"],fw=H(wk);class Q6{#W;#$;constructor(W){if(hW(W))this.#$=W,this.#W=H({query:!0,error:!0});else this.#$=_k,this.#W=H({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 _k(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 O5(W){return TW(W)&&hW(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class g1 extends v1{#W;constructor(W){let $,k;if(hk(W))$={executor:W.executor},k={...W};else{let J=W.dialect,Z=J.createDriver(),X=J.createQueryCompiler(),G=J.createAdapter(),z=new Q6(W.log??[]),V=new j6(Z,z),w=new A6(V),R=new W0(X,G,w,W.plugins??[]);$={executor:R},k={config:W,executor:R,dialect:J,driver:V}}super($);this.#W=H(k)}get schema(){return new t0(this.#W.executor)}get dynamic(){return new O6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new R8({node:$1.create(aW(W)?void 0:uW(W))})}get fn(){return Z4()}transaction(){return new U4({...this.#W})}startTransaction(){return new V4({...this.#W})}connection(){return new A5({...this.#W})}withPlugin(W){return new g1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new g1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new g1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new g1({...this.#W})}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}executeQuery(W,$){if($!==void 0)P1("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let k=O5(W)?W.compile():W;return this.getExecutor().executeQuery(k)}async[Symbol.asyncDispose](){await this.destroy()}}class U0 extends g1{#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")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new U0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new U0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new U0({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new U0({...this.#W})}}function hk(W){return TW(W)&&TW(W.config)&&TW(W.driver)&&TW(W.executor)&&TW(W.dialect)}class A5{#W;constructor(W){this.#W=H(W)}async execute(W){return this.#W.executor.provideConnection(async($)=>{let k=this.#W.executor.withConnectionProvider(new T8($)),J=new g1({...this.#W,executor:k});return await W(J)})}}class U4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new U4({...this.#W,accessMode:W})}setIsolationLevel(W){return new U4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:k,...J}=this.#W,Z={isolationLevel:$,accessMode:k};return C6(Z),this.#W.executor.provideConnection(async(X)=>{let G=this.#W.executor.withConnectionProvider(new T8(X)),z=new U0({...J,executor:G}),V=!1;try{await this.#W.driver.beginTransaction(X,Z),V=!0;let w=await W(z);return await this.#W.driver.commitTransaction(X),w}catch(w){if(V)await this.#W.driver.rollbackTransaction(X);throw w}})}}class V4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new V4({...this.#W,accessMode:W})}setIsolationLevel(W){return new V4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...k}=this.#W,J={isolationLevel:W,accessMode:$};C6(J);let Z=await r8(this.#W.executor);return await this.#W.driver.beginTransaction(Z.connection,J),new y1({...k,connection:Z,executor:this.#W.executor.withConnectionProvider(new T8(Z.connection))})}}class y1 extends U0{#W;#$;#k;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new $0(W.executor,$)};let{connection:k,...J}=W;super(J);this.#W=H(W),this.#k=$;let Z=e();this.#$=(X)=>W.executor.compileQuery(X,Z)}get isCommitted(){return this.#k.isCommitted}get isRolledBack(){return this.#k.isRolledBack}commit(){return K0(this.#k),new s0(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#k.isCommitted=!0,this.#W.connection.release()})}rollback(){return K0(this.#k),new s0(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#k.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}rollbackToSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}releaseSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}withPlugin(W){return new y1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new y1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new y1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new y1({...this.#W})}}class s0{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function K0(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class $0{#W;#$;constructor(W,$){if(W instanceof $0)this.#W=W.#W;else this.#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 K0(this.#$),this.#W.executeQuery(W)}stream(W,$){return K0(this.#$),this.#W.stream(W,$)}withConnectionProvider(W){return new $0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new $0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new $0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new $0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new $0(this.#W.withoutPlugins(),this.#$)}}class v8{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new j5(this,W)}$castTo(){return new v8({...this.#W})}$notNull(){return new v8(this.#W)}withPlugin(W){return new v8({...this.#W,plugins:this.#W.plugins!==void 0?H([...this.#W.plugins,W]):H([W])})}toOperationNode(){return this.#k(this.#$())}compile(W){return this.#J(this.#$(W))}async execute(W){let $=this.#$(W);return $.executeQuery(this.#J($))}#$(W){let $=W!==void 0?W.getExecutor():n1;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#k(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#J(W){return W.compileQuery(this.#k(W),this.#W.queryId)}}function m1(W){return new v8(W)}class j5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var k0=Object.assign((W,...$)=>{return m1({queryId:e(),rawNode:YW.create(W,$?.map(C5)??[])})},{ref(W){return m1({queryId:e(),rawNode:YW.createWithChild(nW(W))})},val(W){return m1({queryId:e(),rawNode:YW.createWithChild(zW(W))})},value(W){return this.val(W)},table(W){return m1({queryId:e(),rawNode:YW.createWithChild(kW(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",m1({queryId:e(),rawNode:YW.create($,W.map(i.create))})},lit(W){return m1({queryId:e(),rawNode:YW.createWithChild(EW.createImmediate(W))})},literal(W){return this.lit(W)},raw(W){return m1({queryId:e(),rawNode:YW.createWithSql(W)})},join(W,$=k0`, `){let k=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let Z=0;Z<W.length;++Z)if(k[2*Z]=C5(W[Z]),Z!==W.length-1)k[2*Z+1]=J;return m1({queryId:e(),rawNode:YW.createWithChildren(k)})}});function C5(W){if(LW(W))return W.toOperationNode();return zW(W)}class x6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=H({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)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var Pk=/'/g;class q6 extends x6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),H({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!fW.is(this.parentNode)&&!BW.is(this.parentNode)&&!w1.is(this.parentNode)&&!e8.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 k=W.length-1;for(let J=0;J<=k;J++)if(this.visitNode(W[J]),J<k)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&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.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.ignore)P1("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(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&&!rW.is(this.parentNode)&&!YW.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(!_W(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 k=0;k<$.length;++k)if(this.appendValue($[k]),k!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(fk[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:k}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),k.length>J)this.visitNode(k[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&&W.frontModifiers.length>0)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(" as "),this.visitNode(W.selectQuery);else{if(this.append(" ("),this.compileList([...W.columns,...W.constraints??[]]),this.append(")"),W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}}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 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&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.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.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," ")}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 "),Y0(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){this.append("drop column "),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(Dk[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 ");this.visitNode(W.name)}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 dW.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";if(this.append($?"[":"."),this.append(String(W.value)),$)this.append("]")}visitJSONOperatorChain(W){for(let $=0,k=W.values.length;$<k;$++){if($===k-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.append("add "),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(),k=this.getRightIdentifierWrapper(),J="";for(let Z of W)if(J+=Z,Z===$)J+=$;else if(Z===k)J+=k;return J}sanitizeStringLiteral(W){return W.replace(Pk,"''")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(_W(W))this.appendStringLiteral(W);else if(u1(W)||Y0(W)||P0(W))this.append(W.toString());else if(h0(W))this.append("null");else if(S9(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 W.sort(($,k)=>$.modifier&&k.modifier?Q5[$.modifier]-Q5[k.modifier]:1),H(W)}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var Dk=H({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Q5=H({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),fk=H({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 E8=H({raw(W,$=[]){return H({sql:W,query:YW.createWithSql(W),parameters:H($),queryId:e()})}});class b6{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class B6{transformQuery(W){return W.node}async transformResult(W){return W.result}}var y6="kysely_migration",F4="kysely_migration_lock",Tk=!1,I6="migration_lock",C_=H({__noMigrations__:!0});class g6{#W;constructor(W){this.#W=H(W)}async getMigrations(){let $=await this.#M(this.#J)?await this.#W.db.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#R()).map(({name:J,...Z})=>{let X=$.find((G)=>G.name===J);return{name:J,migration:Z,executedAt:X?new Date(X.timestamp):void 0}})}async migrateToLatest(){return this.#$(()=>({direction:"Up",step:1/0}))}async migrateTo(W){return this.#$(({migrations:$,executedMigrations:k,pendingMigrations:J})=>{if(TW(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!$.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Z=k.indexOf(W),X=J.findIndex((G)=>G.name===W);if(Z!==-1)return{direction:"Down",step:k.length-Z-1};else if(X!==-1)return{direction:"Up",step:X+1};else throw Error(`migration "${W}" isn't executed or pending`)})}async migrateUp(){return this.#$(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#$(()=>({direction:"Down",step:1}))}async#$(W){try{return await this.#Y(),await this.#H(),await this.#G(),await this.#L(),await this.#F(W)}catch($){if($ instanceof R4)return $.resultSet;return{error:$}}}get#k(){return this.#W.migrationTableSchema}get#J(){return this.#W.migrationTableName??y6}get#Z(){return this.#W.migrationLockTableName??F4}get#z(){return this.#W.allowUnorderedMigrations??Tk}get#X(){if(this.#k)return new W1(this.#k);return new B6}async#Y(){if(!this.#k)return;if(await this.#U())return;try{await this.#K(this.#W.db.schema.createSchema(this.#k))}catch($){if(!await this.#U())throw $}}async#H(){if(await this.#M(this.#J))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#J).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#M(this.#J))throw $}}async#G(){if(await this.#M(this.#Z))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#Z).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#M(this.#Z))throw $}}async#L(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#X).insertInto(this.#Z).values({id:I6,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#U(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#k)}async#M(W){let $=this.#k;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.#X).selectFrom(this.#Z).where("id","=",I6).select("id").executeTakeFirst()}async#F(W){let $=this.#W.db.getExecutor().adapter,k=H({lockTable:this.#W.migrationLockTableName??F4,lockRowId:I6,lockTableSchema:this.#W.migrationTableSchema}),J=async(Z)=>{try{await $.acquireMigrationLock(Z,k);let X=await this.#w(Z);if(X.migrations.length===0)return{results:[]};let{direction:G,step:z}=W(X);if(z<=0)return{results:[]};if(G==="Down")return await this.#f(Z,X,z);else if(G==="Up")return await this.#T(Z,X,z);return{results:[]}}finally{await $.releaseMigrationLock(Z,k)}};if($.supportsTransactionalDdl&&!this.#W.disableTransactions)return this.#W.db.transaction().execute(J);else return this.#W.db.connection().execute(J)}async#w(W){let $=await this.#R(),k=await this.#h(W);if(this.#P($,k),!this.#z)this.#D($,k);let J=this.#_($,k);return H({migrations:$,executedMigrations:k,lastMigration:N9(k),pendingMigrations:J})}#_(W,$){return W.filter((k)=>{return!$.includes(k.name)})}async#R(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#h(W){let $=await W.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute(),k=this.#W.nameComparator||((J,Z)=>J.localeCompare(Z));return $.sort((J,Z)=>{if(J.timestamp===Z.timestamp)return k(J.name,Z.name);return new Date(J.timestamp).getTime()-new Date(Z.timestamp).getTime()}).map((J)=>J.name)}#P(W,$){for(let k of $)if(!W.some((J)=>J.name===k))throw Error(`corrupted migrations: previously executed migration ${k} is missing`)}#D(W,$){for(let k=0;k<$.length;++k)if(W[k].name!==$[k])throw Error(`corrupted migrations: expected previously executed migration ${$[k]} to be at index ${k} but ${W[k].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#f(W,$,k){let J=$.executedMigrations.slice().reverse().slice(0,k).map((X)=>{return $.migrations.find((G)=>G.name===X)}),Z=J.map((X)=>{return{migrationName:X.name,direction:"Down",status:"NotExecuted"}});for(let X=0;X<Z.length;++X){let G=J[X];try{if(G.down)await G.down(W),await W.withPlugin(this.#X).deleteFrom(this.#J).where("name","=",G.name).execute(),Z[X]={migrationName:G.name,direction:"Down",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Down",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#T(W,$,k){let Z=$.pendingMigrations.slice(0,k).map((X)=>{return{migrationName:X.name,direction:"Up",status:"NotExecuted"}});for(let X=0;X<Z.length;X++){let G=$.pendingMigrations[X];try{await G.up(W),await W.withPlugin(this.#X).insertInto(this.#J).values({name:G.name,timestamp:new Date().toISOString()}).execute(),Z[X]={migrationName:G.name,direction:"Up",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Up",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#K(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class R4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}var vk=/"/g;class S8 extends q6{sanitizeIdentifier(W){return W.replace(vk,'""')}}class N8{#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",k0`col_description(a.attrelid, a.attnum)`.as("column_description"),k0`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k0`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","!=",y6).where("c.relname","!=",F4);let k=await $.execute();return this.#$(k)}async getMetadata(W){return{tables:await this.getTables(W)}}#$(W){return W.reduce(($,k)=>{let J=$.find((Z)=>Z.name===k.table&&Z.schema===k.schema);if(!J)J=H({name:k.table,isView:k.table_type==="v",schema:k.schema,columns:[]}),$.push(J);return J.columns.push(H({name:k.column,dataType:k.type,dataTypeSchema:k.type_schema,isNullable:!k.not_null,isAutoIncrementing:k.auto_incrementing!==null,hasDefaultValue:k.has_default,comment:k.column_description??void 0})),$},[])}}var Ek=BigInt("3853314791062309107");class O8 extends b6{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k0`select pg_advisory_xact_lock(${k0.lit(Ek)})`.execute(W)}async releaseMigrationLock(W,$){}}class m6{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let k of $)if(k.endsWith(".js")||k.endsWith(".ts")&&!k.endsWith(".d.ts")||k.endsWith(".mjs")||k.endsWith(".mts")&&!k.endsWith(".d.mts")){let J=await import(this.#W.path.join(this.#W.migrationFolder,k)),Z=k.substring(0,k.lastIndexOf("."));if(x5(J?.default))W[Z]=J.default;else if(x5(J))W[Z]=J}return W}}function x5(W){return TW(W)&&hW(W.up)}var{create:Sk,defineProperty:d0,getOwnPropertyDescriptor:Nk,getOwnPropertyNames:Ok,getPrototypeOf:Ak}=Object,jk=Object.prototype.hasOwnProperty,Ck=(W,$,k)=>($ in W)?d0(W,$,{enumerable:!0,configurable:!0,writable:!0,value:k}):W[$]=k,U=(W,$)=>d0(W,"name",{value:$,configurable:!0}),tW=(W,$)=>()=>(W&&($=W(W=0)),$),r=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),_1=(W,$)=>{for(var k in $)d0(W,k,{get:$[k],enumerable:!0})},m5=(W,$,k,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let Z of Ok($))!jk.call(W,Z)&&Z!==k&&d0(W,Z,{get:()=>$[Z],enumerable:!(J=Nk($,Z))||J.enumerable});return W},R0=(W,$,k)=>(k=W!=null?Sk(Ak(W)):{},m5($||!W||!W.__esModule?d0(k,"default",{value:W,enumerable:!0}):k,W)),QW=(W)=>m5(d0({},"__esModule",{value:!0}),W),s=(W,$,k)=>Ck(W,typeof $!="symbol"?$+"":$,k),Qk=r((W)=>{l(),W.byteLength=V,W.toByteArray=R,W.fromByteArray=D;var $=[],k=[],J=typeof Uint8Array<"u"?Uint8Array:Array,Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(X=0,G=Z.length;X<G;++X)$[X]=Z[X],k[Z.charCodeAt(X)]=X;var X,G;k[45]=62,k[95]=63;function z(F){var M=F.length;if(M%4>0)throw Error("Invalid string. Length must be a multiple of 4");var P=F.indexOf("=");P===-1&&(P=M);var f=P===M?0:4-P%4;return[P,f]}U(z,"getLens");function V(F){var M=z(F),P=M[0],f=M[1];return(P+f)*3/4-f}U(V,"byteLength");function w(F,M,P){return(M+P)*3/4-P}U(w,"_byteLength");function R(F){var M,P=z(F),f=P[0],T=P[1],S=new J(w(F,f,T)),q=0,Q=T>0?f-4:f,v;for(v=0;v<Q;v+=4)M=k[F.charCodeAt(v)]<<18|k[F.charCodeAt(v+1)]<<12|k[F.charCodeAt(v+2)]<<6|k[F.charCodeAt(v+3)],S[q++]=M>>16&255,S[q++]=M>>8&255,S[q++]=M&255;return T===2&&(M=k[F.charCodeAt(v)]<<2|k[F.charCodeAt(v+1)]>>4,S[q++]=M&255),T===1&&(M=k[F.charCodeAt(v)]<<10|k[F.charCodeAt(v+1)]<<4|k[F.charCodeAt(v+2)]>>2,S[q++]=M>>8&255,S[q++]=M&255),S}U(R,"toByteArray");function h(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}U(h,"tripletToBase64");function _(F,M,P){for(var f,T=[],S=M;S<P;S+=3)f=(F[S]<<16&16711680)+(F[S+1]<<8&65280)+(F[S+2]&255),T.push(h(f));return T.join("")}U(_,"encodeChunk");function D(F){for(var M,P=F.length,f=P%3,T=[],S=16383,q=0,Q=P-f;q<Q;q+=S)T.push(_(F,q,q+S>Q?Q:q+S));return f===1?(M=F[P-1],T.push($[M>>2]+$[M<<4&63]+"==")):f===2&&(M=(F[P-2]<<8)+F[P-1],T.push($[M>>10]+$[M>>4&63]+$[M<<2&63]+"=")),T.join("")}U(D,"fromByteArray")}),xk=r((W)=>{l(),W.read=function($,k,J,Z,X){var G,z,V=X*8-Z-1,w=(1<<V)-1,R=w>>1,h=-7,_=J?X-1:0,D=J?-1:1,F=$[k+_];for(_+=D,G=F&(1<<-h)-1,F>>=-h,h+=V;h>0;G=G*256+$[k+_],_+=D,h-=8);for(z=G&(1<<-h)-1,G>>=-h,h+=Z;h>0;z=z*256+$[k+_],_+=D,h-=8);if(G===0)G=1-R;else{if(G===w)return z?NaN:(F?-1:1)*(1/0);z=z+Math.pow(2,Z),G=G-R}return(F?-1:1)*z*Math.pow(2,G-Z)},W.write=function($,k,J,Z,X,G){var z,V,w,R=G*8-X-1,h=(1<<R)-1,_=h>>1,D=X===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=Z?0:G-1,M=Z?1:-1,P=k<0||k===0&&1/k<0?1:0;for(k=Math.abs(k),isNaN(k)||k===1/0?(V=isNaN(k)?1:0,z=h):(z=Math.floor(Math.log(k)/Math.LN2),k*(w=Math.pow(2,-z))<1&&(z--,w*=2),z+_>=1?k+=D/w:k+=D*Math.pow(2,1-_),k*w>=2&&(z++,w/=2),z+_>=h?(V=0,z=h):z+_>=1?(V=(k*w-1)*Math.pow(2,X),z=z+_):(V=k*Math.pow(2,_-1)*Math.pow(2,X),z=0));X>=8;$[J+F]=V&255,F+=M,V/=256,X-=8);for(z=z<<X|V,R+=X;R>0;$[J+F]=z&255,F+=M,z/=256,R-=8);$[J+F-M]|=P*128}}),qk=r((W)=>{l();var $=Qk(),k=xk(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=z,W.SlowBuffer=T,W.INSPECT_MAX_BYTES=50;var Z=2147483647;W.kMaxLength=Z,z.TYPED_ARRAY_SUPPORT=X(),!z.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 X(){try{let Y=new Uint8Array(1),L={foo:U(function(){return 42},"foo")};return Object.setPrototypeOf(L,Uint8Array.prototype),Object.setPrototypeOf(Y,L),Y.foo()===42}catch{return!1}}U(X,"typedArraySupport"),Object.defineProperty(z.prototype,"parent",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(z.prototype,"offset",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.byteOffset},"get")});function G(Y){if(Y>Z)throw RangeError('The value "'+Y+'" is invalid for option "size"');let L=new Uint8Array(Y);return Object.setPrototypeOf(L,z.prototype),L}U(G,"createBuffer");function z(Y,L,K){if(typeof Y=="number"){if(typeof L=="string")throw TypeError('The "string" argument must be of type string. Received type number');return h(Y)}return V(Y,L,K)}U(z,"Buffer"),z.poolSize=8192;function V(Y,L,K){if(typeof Y=="string")return _(Y,L);if(ArrayBuffer.isView(Y))return F(Y);if(Y==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y);if(Z1(Y,ArrayBuffer)||Y&&Z1(Y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z1(Y,SharedArrayBuffer)||Y&&Z1(Y.buffer,SharedArrayBuffer)))return M(Y,L,K);if(typeof Y=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let E=Y.valueOf&&Y.valueOf();if(E!=null&&E!==Y)return z.from(E,L,K);let O=P(Y);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Y[Symbol.toPrimitive]=="function")return z.from(Y[Symbol.toPrimitive]("string"),L,K);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y)}U(V,"from"),z.from=function(Y,L,K){return V(Y,L,K)},Object.setPrototypeOf(z.prototype,Uint8Array.prototype),Object.setPrototypeOf(z,Uint8Array);function w(Y){if(typeof Y!="number")throw TypeError('"size" argument must be of type number');if(Y<0)throw RangeError('The value "'+Y+'" is invalid for option "size"')}U(w,"assertSize");function R(Y,L,K){return w(Y),Y<=0?G(Y):L!==void 0?typeof K=="string"?G(Y).fill(L,K):G(Y).fill(L):G(Y)}U(R,"alloc"),z.alloc=function(Y,L,K){return R(Y,L,K)};function h(Y){return w(Y),G(Y<0?0:f(Y)|0)}U(h,"allocUnsafe"),z.allocUnsafe=function(Y){return h(Y)},z.allocUnsafeSlow=function(Y){return h(Y)};function _(Y,L){if((typeof L!="string"||L==="")&&(L="utf8"),!z.isEncoding(L))throw TypeError("Unknown encoding: "+L);let K=S(Y,L)|0,E=G(K),O=E.write(Y,L);return O!==K&&(E=E.slice(0,O)),E}U(_,"fromString");function D(Y){let L=Y.length<0?0:f(Y.length)|0,K=G(L);for(let E=0;E<L;E+=1)K[E]=Y[E]&255;return K}U(D,"fromArrayLike");function F(Y){if(Z1(Y,Uint8Array)){let L=new Uint8Array(Y);return M(L.buffer,L.byteOffset,L.byteLength)}return D(Y)}U(F,"fromArrayView");function M(Y,L,K){if(L<0||Y.byteLength<L)throw RangeError('"offset" is outside of buffer bounds');if(Y.byteLength<L+(K||0))throw RangeError('"length" is outside of buffer bounds');let E;return L===void 0&&K===void 0?E=new Uint8Array(Y):K===void 0?E=new Uint8Array(Y,L):E=new Uint8Array(Y,L,K),Object.setPrototypeOf(E,z.prototype),E}U(M,"fromArrayBuffer");function P(Y){if(z.isBuffer(Y)){let L=f(Y.length)|0,K=G(L);return K.length===0||Y.copy(K,0,0,L),K}if(Y.length!==void 0)return typeof Y.length!="number"||I8(Y.length)?G(0):D(Y);if(Y.type==="Buffer"&&Array.isArray(Y.data))return D(Y.data)}U(P,"fromObject");function f(Y){if(Y>=Z)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Z.toString(16)+" bytes");return Y|0}U(f,"checked");function T(Y){return+Y!=Y&&(Y=0),z.alloc(+Y)}U(T,"SlowBuffer"),z.isBuffer=U(function(Y){return Y!=null&&Y._isBuffer===!0&&Y!==z.prototype},"isBuffer"),z.compare=U(function(Y,L){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),Z1(L,Uint8Array)&&(L=z.from(L,L.offset,L.byteLength)),!z.isBuffer(Y)||!z.isBuffer(L))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(Y===L)return 0;let K=Y.length,E=L.length;for(let O=0,x=Math.min(K,E);O<x;++O)if(Y[O]!==L[O]){K=Y[O],E=L[O];break}return K<E?-1:E<K?1:0},"compare"),z.isEncoding=U(function(Y){switch(String(Y).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"),z.concat=U(function(Y,L){if(!Array.isArray(Y))throw TypeError('"list" argument must be an Array of Buffers');if(Y.length===0)return z.alloc(0);let K;if(L===void 0)for(L=0,K=0;K<Y.length;++K)L+=Y[K].length;let E=z.allocUnsafe(L),O=0;for(K=0;K<Y.length;++K){let x=Y[K];if(Z1(x,Uint8Array))O+x.length>E.length?(z.isBuffer(x)||(x=z.from(x)),x.copy(E,O)):Uint8Array.prototype.set.call(E,x,O);else if(z.isBuffer(x))x.copy(E,O);else throw TypeError('"list" argument must be an Array of Buffers');O+=x.length}return E},"concat");function S(Y,L){if(z.isBuffer(Y))return Y.length;if(ArrayBuffer.isView(Y)||Z1(Y,ArrayBuffer))return Y.byteLength;if(typeof Y!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Y);let K=Y.length,E=arguments.length>2&&arguments[2]===!0;if(!E&&K===0)return 0;let O=!1;for(;;)switch(L){case"ascii":case"latin1":case"binary":return K;case"utf8":case"utf-8":return B8(Y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K*2;case"hex":return K>>>1;case"base64":return B4(Y).length;default:if(O)return E?-1:B8(Y).length;L=(""+L).toLowerCase(),O=!0}}U(S,"byteLength"),z.byteLength=S;function q(Y,L,K){let E=!1;if((L===void 0||L<0)&&(L=0),L>this.length||((K===void 0||K>this.length)&&(K=this.length),K<=0)||(K>>>=0,L>>>=0,K<=L))return"";for(Y||(Y="utf8");;)switch(Y){case"hex":return n(this,L,K);case"utf8":case"utf-8":return B(this,L,K);case"ascii":return a(this,L,K);case"latin1":case"binary":return JW(this,L,K);case"base64":return c(this,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sW(this,L,K);default:if(E)throw TypeError("Unknown encoding: "+Y);Y=(Y+"").toLowerCase(),E=!0}}U(q,"slowToString"),z.prototype._isBuffer=!0;function Q(Y,L,K){let E=Y[L];Y[L]=Y[K],Y[K]=E}U(Q,"swap"),z.prototype.swap16=U(function(){let Y=this.length;if(Y%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let L=0;L<Y;L+=2)Q(this,L,L+1);return this},"swap16"),z.prototype.swap32=U(function(){let Y=this.length;if(Y%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let L=0;L<Y;L+=4)Q(this,L,L+3),Q(this,L+1,L+2);return this},"swap32"),z.prototype.swap64=U(function(){let Y=this.length;if(Y%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let L=0;L<Y;L+=8)Q(this,L,L+7),Q(this,L+1,L+6),Q(this,L+2,L+5),Q(this,L+3,L+4);return this},"swap64"),z.prototype.toString=U(function(){let Y=this.length;return Y===0?"":arguments.length===0?B(this,0,Y):q.apply(this,arguments)},"toString"),z.prototype.toLocaleString=z.prototype.toString,z.prototype.equals=U(function(Y){if(!z.isBuffer(Y))throw TypeError("Argument must be a Buffer");return this===Y?!0:z.compare(this,Y)===0},"equals"),z.prototype.inspect=U(function(){let Y="",L=W.INSPECT_MAX_BYTES;return Y=this.toString("hex",0,L).replace(/(.{2})/g,"$1 ").trim(),this.length>L&&(Y+=" ... "),"<Buffer "+Y+">"},"inspect"),J&&(z.prototype[J]=z.prototype.inspect),z.prototype.compare=U(function(Y,L,K,E,O){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),!z.isBuffer(Y))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof Y);if(L===void 0&&(L=0),K===void 0&&(K=Y?Y.length:0),E===void 0&&(E=0),O===void 0&&(O=this.length),L<0||K>Y.length||E<0||O>this.length)throw RangeError("out of range index");if(E>=O&&L>=K)return 0;if(E>=O)return-1;if(L>=K)return 1;if(L>>>=0,K>>>=0,E>>>=0,O>>>=0,this===Y)return 0;let x=O-E,y=K-L,FW=Math.min(x,y),OW=this.slice(E,O),DW=Y.slice(L,K);for(let wW=0;wW<FW;++wW)if(OW[wW]!==DW[wW]){x=OW[wW],y=DW[wW];break}return x<y?-1:y<x?1:0},"compare");function v(Y,L,K,E,O){if(Y.length===0)return-1;if(typeof K=="string"?(E=K,K=0):K>2147483647?K=2147483647:K<-2147483648&&(K=-2147483648),K=+K,I8(K)&&(K=O?0:Y.length-1),K<0&&(K=Y.length+K),K>=Y.length){if(O)return-1;K=Y.length-1}else if(K<0)if(O)K=0;else return-1;if(typeof L=="string"&&(L=z.from(L,E)),z.isBuffer(L))return L.length===0?-1:j(Y,L,K,E,O);if(typeof L=="number")return L=L&255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(Y,L,K):Uint8Array.prototype.lastIndexOf.call(Y,L,K):j(Y,[L],K,E,O);throw TypeError("val must be string, number or Buffer")}U(v,"bidirectionalIndexOf");function j(Y,L,K,E,O){let x=1,y=Y.length,FW=L.length;if(E!==void 0&&(E=String(E).toLowerCase(),E==="ucs2"||E==="ucs-2"||E==="utf16le"||E==="utf-16le")){if(Y.length<2||L.length<2)return-1;x=2,y/=2,FW/=2,K/=2}function OW(wW,vW){return x===1?wW[vW]:wW.readUInt16BE(vW*x)}U(OW,"read");let DW;if(O){let wW=-1;for(DW=K;DW<y;DW++)if(OW(Y,DW)===OW(L,wW===-1?0:DW-wW)){if(wW===-1&&(wW=DW),DW-wW+1===FW)return wW*x}else wW!==-1&&(DW-=DW-wW),wW=-1}else for(K+FW>y&&(K=y-FW),DW=K;DW>=0;DW--){let wW=!0;for(let vW=0;vW<FW;vW++)if(OW(Y,DW+vW)!==OW(L,vW)){wW=!1;break}if(wW)return DW}return-1}U(j,"arrayIndexOf"),z.prototype.includes=U(function(Y,L,K){return this.indexOf(Y,L,K)!==-1},"includes"),z.prototype.indexOf=U(function(Y,L,K){return v(this,Y,L,K,!0)},"indexOf"),z.prototype.lastIndexOf=U(function(Y,L,K){return v(this,Y,L,K,!1)},"lastIndexOf");function A(Y,L,K,E){K=Number(K)||0;let O=Y.length-K;E?(E=Number(E),E>O&&(E=O)):E=O;let x=L.length;E>x/2&&(E=x/2);let y;for(y=0;y<E;++y){let FW=parseInt(L.substr(y*2,2),16);if(I8(FW))return y;Y[K+y]=FW}return y}U(A,"hexWrite");function N(Y,L,K,E){return W8(B8(L,Y.length-K),Y,K,E)}U(N,"utf8Write");function b(Y,L,K,E){return W8(Z9(L),Y,K,E)}U(b,"asciiWrite");function C(Y,L,K,E){return W8(B4(L),Y,K,E)}U(C,"base64Write");function u(Y,L,K,E){return W8(X9(L,Y.length-K),Y,K,E)}U(u,"ucs2Write"),z.prototype.write=U(function(Y,L,K,E){if(L===void 0)E="utf8",K=this.length,L=0;else if(K===void 0&&typeof L=="string")E=L,K=this.length,L=0;else if(isFinite(L))L=L>>>0,isFinite(K)?(K=K>>>0,E===void 0&&(E="utf8")):(E=K,K=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let O=this.length-L;if((K===void 0||K>O)&&(K=O),Y.length>0&&(K<0||L<0)||L>this.length)throw RangeError("Attempt to write outside buffer bounds");E||(E="utf8");let x=!1;for(;;)switch(E){case"hex":return A(this,Y,L,K);case"utf8":case"utf-8":return N(this,Y,L,K);case"ascii":case"latin1":case"binary":return b(this,Y,L,K);case"base64":return C(this,Y,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u(this,Y,L,K);default:if(x)throw TypeError("Unknown encoding: "+E);E=(""+E).toLowerCase(),x=!0}},"write"),z.prototype.toJSON=U(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function c(Y,L,K){return L===0&&K===Y.length?$.fromByteArray(Y):$.fromByteArray(Y.slice(L,K))}U(c,"base64Slice");function B(Y,L,K){K=Math.min(Y.length,K);let E=[],O=L;for(;O<K;){let x=Y[O],y=null,FW=x>239?4:x>223?3:x>191?2:1;if(O+FW<=K){let OW,DW,wW,vW;switch(FW){case 1:x<128&&(y=x);break;case 2:OW=Y[O+1],(OW&192)===128&&(vW=(x&31)<<6|OW&63,vW>127&&(y=vW));break;case 3:OW=Y[O+1],DW=Y[O+2],(OW&192)===128&&(DW&192)===128&&(vW=(x&15)<<12|(OW&63)<<6|DW&63,vW>2047&&(vW<55296||vW>57343)&&(y=vW));break;case 4:OW=Y[O+1],DW=Y[O+2],wW=Y[O+3],(OW&192)===128&&(DW&192)===128&&(wW&192)===128&&(vW=(x&15)<<18|(OW&63)<<12|(DW&63)<<6|wW&63,vW>65535&&vW<1114112&&(y=vW))}}y===null?(y=65533,FW=1):y>65535&&(y-=65536,E.push(y>>>10&1023|55296),y=56320|y&1023),E.push(y),O+=FW}return p(E)}U(B,"utf8Slice");var m=4096;function p(Y){let L=Y.length;if(L<=m)return String.fromCharCode.apply(String,Y);let K="",E=0;for(;E<L;)K+=String.fromCharCode.apply(String,Y.slice(E,E+=m));return K}U(p,"decodeCodePointsArray");function a(Y,L,K){let E="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)E+=String.fromCharCode(Y[O]&127);return E}U(a,"asciiSlice");function JW(Y,L,K){let E="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)E+=String.fromCharCode(Y[O]);return E}U(JW,"latin1Slice");function n(Y,L,K){let E=Y.length;(!L||L<0)&&(L=0),(!K||K<0||K>E)&&(K=E);let O="";for(let x=L;x<K;++x)O+=p7[Y[x]];return O}U(n,"hexSlice");function sW(Y,L,K){let E=Y.slice(L,K),O="";for(let x=0;x<E.length-1;x+=2)O+=String.fromCharCode(E[x]+E[x+1]*256);return O}U(sW,"utf16leSlice"),z.prototype.slice=U(function(Y,L){let K=this.length;Y=~~Y,L=L===void 0?K:~~L,Y<0?(Y+=K,Y<0&&(Y=0)):Y>K&&(Y=K),L<0?(L+=K,L<0&&(L=0)):L>K&&(L=K),L<Y&&(L=Y);let E=this.subarray(Y,L);return Object.setPrototypeOf(E,z.prototype),E},"slice");function RW(Y,L,K){if(Y%1!==0||Y<0)throw RangeError("offset is not uint");if(Y+L>K)throw RangeError("Trying to access beyond buffer length")}U(RW,"checkOffset"),z.prototype.readUintLE=z.prototype.readUIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)E+=this[Y+x]*O;return E},"readUIntLE"),z.prototype.readUintBE=z.prototype.readUIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y+--L],O=1;for(;L>0&&(O*=256);)E+=this[Y+--L]*O;return E},"readUIntBE"),z.prototype.readUint8=z.prototype.readUInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]},"readUInt8"),z.prototype.readUint16LE=z.prototype.readUInt16LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]|this[Y+1]<<8},"readUInt16LE"),z.prototype.readUint16BE=z.prototype.readUInt16BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]<<8|this[Y+1]},"readUInt16BE"),z.prototype.readUint32LE=z.prototype.readUInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),(this[Y]|this[Y+1]<<8|this[Y+2]<<16)+this[Y+3]*16777216},"readUInt32LE"),z.prototype.readUint32BE=z.prototype.readUInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]*16777216+(this[Y+1]<<16|this[Y+2]<<8|this[Y+3])},"readUInt32BE"),z.prototype.readBigUInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216,O=this[++Y]+this[++Y]*256+this[++Y]*65536+K*16777216;return BigInt(E)+(BigInt(O)<<BigInt(32))},"readBigUInt64LE")),z.prototype.readBigUInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=L*16777216+this[++Y]*65536+this[++Y]*256+this[++Y],O=this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K;return(BigInt(E)<<BigInt(32))+BigInt(O)},"readBigUInt64BE")),z.prototype.readIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)E+=this[Y+x]*O;return O*=128,E>=O&&(E-=Math.pow(2,8*L)),E},"readIntLE"),z.prototype.readIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=L,O=1,x=this[Y+--E];for(;E>0&&(O*=256);)x+=this[Y+--E]*O;return O*=128,x>=O&&(x-=Math.pow(2,8*L)),x},"readIntBE"),z.prototype.readInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]&128?(255-this[Y]+1)*-1:this[Y]},"readInt8"),z.prototype.readInt16LE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y]|this[Y+1]<<8;return K&32768?K|4294901760:K},"readInt16LE"),z.prototype.readInt16BE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y+1]|this[Y]<<8;return K&32768?K|4294901760:K},"readInt16BE"),z.prototype.readInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]|this[Y+1]<<8|this[Y+2]<<16|this[Y+3]<<24},"readInt32LE"),z.prototype.readInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]<<24|this[Y+1]<<16|this[Y+2]<<8|this[Y+3]},"readInt32BE"),z.prototype.readBigInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=this[Y+4]+this[Y+5]*256+this[Y+6]*65536+(K<<24);return(BigInt(E)<<BigInt(32))+BigInt(L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216)},"readBigInt64LE")),z.prototype.readBigInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=(L<<24)+this[++Y]*65536+this[++Y]*256+this[++Y];return(BigInt(E)<<BigInt(32))+BigInt(this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K)},"readBigInt64BE")),z.prototype.readFloatLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!0,23,4)},"readFloatLE"),z.prototype.readFloatBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!1,23,4)},"readFloatBE"),z.prototype.readDoubleLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!0,52,8)},"readDoubleLE"),z.prototype.readDoubleBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!1,52,8)},"readDoubleBE");function SW(Y,L,K,E,O,x){if(!z.isBuffer(Y))throw TypeError('"buffer" argument must be a Buffer instance');if(L>O||L<x)throw RangeError('"value" argument is out of bounds');if(K+E>Y.length)throw RangeError("Index out of range")}U(SW,"checkInt"),z.prototype.writeUintLE=z.prototype.writeUIntLE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,K=K>>>0,!E){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=1,x=0;for(this[L]=Y&255;++x<K&&(O*=256);)this[L+x]=Y/O&255;return L+K},"writeUIntLE"),z.prototype.writeUintBE=z.prototype.writeUIntBE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,K=K>>>0,!E){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=K-1,x=1;for(this[L+O]=Y&255;--O>=0&&(x*=256);)this[L+O]=Y/x&255;return L+K},"writeUIntBE"),z.prototype.writeUint8=z.prototype.writeUInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,255,0),this[L]=Y&255,L+1},"writeUInt8"),z.prototype.writeUint16LE=z.prototype.writeUInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeUInt16LE"),z.prototype.writeUint16BE=z.prototype.writeUInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeUInt16BE"),z.prototype.writeUint32LE=z.prototype.writeUInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L+3]=Y>>>24,this[L+2]=Y>>>16,this[L+1]=Y>>>8,this[L]=Y&255,L+4},"writeUInt32LE"),z.prototype.writeUint32BE=z.prototype.writeUInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeUInt32BE");function r0(Y,L,K,E,O){b4(L,E,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,K}U(r0,"wrtBigUInt64LE");function e0(Y,L,K,E,O){b4(L,E,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K+7]=x,x=x>>8,Y[K+6]=x,x=x>>8,Y[K+5]=x,x=x>>8,Y[K+4]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K+3]=y,y=y>>8,Y[K+2]=y,y=y>>8,Y[K+1]=y,y=y>>8,Y[K]=y,K+8}U(e0,"wrtBigUInt64BE"),z.prototype.writeBigUInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),z.prototype.writeBigUInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),z.prototype.writeIntLE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,!E){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=0,x=1,y=0;for(this[L]=Y&255;++O<K&&(x*=256);)Y<0&&y===0&&this[L+O-1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntLE"),z.prototype.writeIntBE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,!E){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=K-1,x=1,y=0;for(this[L+O]=Y&255;--O>=0&&(x*=256);)Y<0&&y===0&&this[L+O+1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntBE"),z.prototype.writeInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,127,-128),Y<0&&(Y=255+Y+1),this[L]=Y&255,L+1},"writeInt8"),z.prototype.writeInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeInt16LE"),z.prototype.writeInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeInt16BE"),z.prototype.writeInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),this[L]=Y&255,this[L+1]=Y>>>8,this[L+2]=Y>>>16,this[L+3]=Y>>>24,L+4},"writeInt32LE"),z.prototype.writeInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),Y<0&&(Y=4294967295+Y+1),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeInt32BE"),z.prototype.writeBigInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),z.prototype.writeBigInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function C4(Y,L,K,E,O,x){if(K+E>Y.length)throw RangeError("Index out of range");if(K<0)throw RangeError("Index out of range")}U(C4,"checkIEEE754");function Q4(Y,L,K,E,O){return L=+L,K=K>>>0,O||C4(Y,L,K,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),k.write(Y,L,K,E,23,4),K+4}U(Q4,"writeFloat"),z.prototype.writeFloatLE=U(function(Y,L,K){return Q4(this,Y,L,!0,K)},"writeFloatLE"),z.prototype.writeFloatBE=U(function(Y,L,K){return Q4(this,Y,L,!1,K)},"writeFloatBE");function x4(Y,L,K,E,O){return L=+L,K=K>>>0,O||C4(Y,L,K,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),k.write(Y,L,K,E,52,8),K+8}U(x4,"writeDouble"),z.prototype.writeDoubleLE=U(function(Y,L,K){return x4(this,Y,L,!0,K)},"writeDoubleLE"),z.prototype.writeDoubleBE=U(function(Y,L,K){return x4(this,Y,L,!1,K)},"writeDoubleBE"),z.prototype.copy=U(function(Y,L,K,E){if(!z.isBuffer(Y))throw TypeError("argument should be a Buffer");if(K||(K=0),!E&&E!==0&&(E=this.length),L>=Y.length&&(L=Y.length),L||(L=0),E>0&&E<K&&(E=K),E===K||Y.length===0||this.length===0)return 0;if(L<0)throw RangeError("targetStart out of bounds");if(K<0||K>=this.length)throw RangeError("Index out of range");if(E<0)throw RangeError("sourceEnd out of bounds");E>this.length&&(E=this.length),Y.length-L<E-K&&(E=Y.length-L+K);let O=E-K;return this===Y&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(L,K,E):Uint8Array.prototype.set.call(Y,this.subarray(K,E),L),O},"copy"),z.prototype.fill=U(function(Y,L,K,E){if(typeof Y=="string"){if(typeof L=="string"?(E=L,L=0,K=this.length):typeof K=="string"&&(E=K,K=this.length),E!==void 0&&typeof E!="string")throw TypeError("encoding must be a string");if(typeof E=="string"&&!z.isEncoding(E))throw TypeError("Unknown encoding: "+E);if(Y.length===1){let x=Y.charCodeAt(0);(E==="utf8"&&x<128||E==="latin1")&&(Y=x)}}else typeof Y=="number"?Y=Y&255:typeof Y=="boolean"&&(Y=Number(Y));if(L<0||this.length<L||this.length<K)throw RangeError("Out of range index");if(K<=L)return this;L=L>>>0,K=K===void 0?this.length:K>>>0,Y||(Y=0);let O;if(typeof Y=="number")for(O=L;O<K;++O)this[O]=Y;else{let x=z.isBuffer(Y)?Y:z.from(Y,E),y=x.length;if(y===0)throw TypeError('The value "'+Y+'" is invalid for argument "value"');for(O=0;O<K-L;++O)this[O+L]=x[O%y]}return this},"fill");var w0={};function b8(Y,L,K){var E;w0[Y]=(E=class extends K{constructor(){super(),Object.defineProperty(this,"message",{value:L.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Y}]`,this.stack,delete this.name}get code(){return Y}set code(O){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:O,writable:!0})}toString(){return`${this.name} [${Y}]: ${this.message}`}},U(E,"NodeError"),E)}U(b8,"E"),b8("ERR_BUFFER_OUT_OF_BOUNDS",function(Y){return Y?`${Y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),b8("ERR_INVALID_ARG_TYPE",function(Y,L){return`The "${Y}" argument must be of type number. Received type ${typeof L}`},TypeError),b8("ERR_OUT_OF_RANGE",function(Y,L,K){let E=`The value of "${Y}" is out of range.`,O=K;return Number.isInteger(K)&&Math.abs(K)>4294967296?O=q4(String(K)):typeof K=="bigint"&&(O=String(K),(K>BigInt(2)**BigInt(32)||K<-(BigInt(2)**BigInt(32)))&&(O=q4(O)),O+="n"),E+=` It must be ${L}. Received ${O}`,E},RangeError);function q4(Y){let L="",K=Y.length,E=Y[0]==="-"?1:0;for(;K>=E+4;K-=3)L=`_${Y.slice(K-3,K)}${L}`;return`${Y.slice(0,K)}${L}`}U(q4,"addNumericalSeparator");function k9(Y,L,K){Z0(L,"offset"),(Y[L]===void 0||Y[L+K]===void 0)&&_0(L,Y.length-(K+1))}U(k9,"checkBounds");function b4(Y,L,K,E,O,x){if(Y>K||Y<L){let y=typeof L=="bigint"?"n":"",FW;throw x>3?L===0||L===BigInt(0)?FW=`>= 0${y} and < 2${y} ** ${(x+1)*8}${y}`:FW=`>= -(2${y} ** ${(x+1)*8-1}${y}) and < 2 ** ${(x+1)*8-1}${y}`:FW=`>= ${L}${y} and <= ${K}${y}`,new w0.ERR_OUT_OF_RANGE("value",FW,Y)}k9(E,O,x)}U(b4,"checkIntBI");function Z0(Y,L){if(typeof Y!="number")throw new w0.ERR_INVALID_ARG_TYPE(L,"number",Y)}U(Z0,"validateNumber");function _0(Y,L,K){throw Math.floor(Y)!==Y?(Z0(Y,K),new w0.ERR_OUT_OF_RANGE(K||"offset","an integer",Y)):L<0?new w0.ERR_BUFFER_OUT_OF_BOUNDS:new w0.ERR_OUT_OF_RANGE(K||"offset",`>= ${K?1:0} and <= ${L}`,Y)}U(_0,"boundsError");var i7=/[^+/0-9A-Za-z-_]/g;function J9(Y){if(Y=Y.split("=")[0],Y=Y.trim().replace(i7,""),Y.length<2)return"";for(;Y.length%4!==0;)Y=Y+"=";return Y}U(J9,"base64clean");function B8(Y,L){L=L||1/0;let K,E=Y.length,O=null,x=[];for(let y=0;y<E;++y){if(K=Y.charCodeAt(y),K>55295&&K<57344){if(!O){if(K>56319){(L-=3)>-1&&x.push(239,191,189);continue}else if(y+1===E){(L-=3)>-1&&x.push(239,191,189);continue}O=K;continue}if(K<56320){(L-=3)>-1&&x.push(239,191,189),O=K;continue}K=(O-55296<<10|K-56320)+65536}else O&&(L-=3)>-1&&x.push(239,191,189);if(O=null,K<128){if((L-=1)<0)break;x.push(K)}else if(K<2048){if((L-=2)<0)break;x.push(K>>6|192,K&63|128)}else if(K<65536){if((L-=3)<0)break;x.push(K>>12|224,K>>6&63|128,K&63|128)}else if(K<1114112){if((L-=4)<0)break;x.push(K>>18|240,K>>12&63|128,K>>6&63|128,K&63|128)}else throw Error("Invalid code point")}return x}U(B8,"utf8ToBytes");function Z9(Y){let L=[];for(let K=0;K<Y.length;++K)L.push(Y.charCodeAt(K)&255);return L}U(Z9,"asciiToBytes");function X9(Y,L){let K,E,O,x=[];for(let y=0;y<Y.length&&!((L-=2)<0);++y)K=Y.charCodeAt(y),E=K>>8,O=K%256,x.push(O),x.push(E);return x}U(X9,"utf16leToBytes");function B4(Y){return $.toByteArray(J9(Y))}U(B4,"base64ToBytes");function W8(Y,L,K,E){let O;for(O=0;O<E&&!(O+K>=L.length||O>=Y.length);++O)L[O+K]=Y[O];return O}U(W8,"blitBuffer");function Z1(Y,L){return Y instanceof L||Y!=null&&Y.constructor!=null&&Y.constructor.name!=null&&Y.constructor.name===L.name}U(Z1,"isInstance");function I8(Y){return Y!==Y}U(I8,"numberIsNaN");var p7=function(){let Y="0123456789abcdef",L=Array(256);for(let K=0;K<16;++K){let E=K*16;for(let O=0;O<16;++O)L[E+O]=Y[K]+Y[O]}return L}();function O1(Y){return typeof BigInt>"u"?Y9:Y}U(O1,"defineBigIntMethod");function Y9(){throw Error("BigInt not supported")}U(Y9,"BufferBigIntNotDefined")}),D4,t6,bk,t,o,l=tW(()=>{D4=globalThis,t6=globalThis.setImmediate??((W)=>setTimeout(W,0)),bk=globalThis.clearImmediate??((W)=>clearTimeout(W)),t=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:qk().Buffer,o=globalThis.process??{},o.env??(o.env={});try{o.nextTick(()=>{})}catch{let W=Promise.resolve();o.nextTick=W.then.bind(W)}}),F0=r((W,$)=>{l();var k=typeof Reflect=="object"?Reflect:null,J=k&&typeof k.apply=="function"?k.apply:U(function(v,j,A){return Function.prototype.apply.call(v,j,A)},"ReflectApply"),Z;k&&typeof k.ownKeys=="function"?Z=k.ownKeys:Object.getOwnPropertySymbols?Z=U(function(v){return Object.getOwnPropertyNames(v).concat(Object.getOwnPropertySymbols(v))},"ReflectOwnKeys"):Z=U(function(v){return Object.getOwnPropertyNames(v)},"ReflectOwnKeys");function X(v){console&&console.warn&&console.warn(v)}U(X,"ProcessEmitWarning");var G=Number.isNaN||U(function(v){return v!==v},"NumberIsNaN");function z(){z.init.call(this)}U(z,"EventEmitter"),$.exports=z,$.exports.once=S,z.EventEmitter=z,z.prototype._events=void 0,z.prototype._eventsCount=0,z.prototype._maxListeners=void 0;var V=10;function w(v){if(typeof v!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}U(w,"checkListener"),Object.defineProperty(z,"defaultMaxListeners",{enumerable:!0,get:U(function(){return V},"get"),set:U(function(v){if(typeof v!="number"||v<0||G(v))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");V=v},"set")}),z.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},z.prototype.setMaxListeners=U(function(v){if(typeof v!="number"||v<0||G(v))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this},"setMaxListeners");function R(v){return v._maxListeners===void 0?z.defaultMaxListeners:v._maxListeners}U(R,"_getMaxListeners"),z.prototype.getMaxListeners=U(function(){return R(this)},"getMaxListeners"),z.prototype.emit=U(function(v){for(var j=[],A=1;A<arguments.length;A++)j.push(arguments[A]);var N=v==="error",b=this._events;if(b!==void 0)N=N&&b.error===void 0;else if(!N)return!1;if(N){var C;if(j.length>0&&(C=j[0]),C instanceof Error)throw C;var u=Error("Unhandled error."+(C?" ("+C.message+")":""));throw u.context=C,u}var c=b[v];if(c===void 0)return!1;if(typeof c=="function")J(c,this,j);else for(var B=c.length,m=P(c,B),A=0;A<B;++A)J(m[A],this,j);return!0},"emit");function h(v,j,A,N){var b,C,u;if(w(A),C=v._events,C===void 0?(C=v._events=Object.create(null),v._eventsCount=0):(C.newListener!==void 0&&(v.emit("newListener",j,A.listener?A.listener:A),C=v._events),u=C[j]),u===void 0)u=C[j]=A,++v._eventsCount;else if(typeof u=="function"?u=C[j]=N?[A,u]:[u,A]:N?u.unshift(A):u.push(A),b=R(v),b>0&&u.length>b&&!u.warned){u.warned=!0;var c=Error("Possible EventEmitter memory leak detected. "+u.length+" "+String(j)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=v,c.type=j,c.count=u.length,X(c)}return v}U(h,"_addListener"),z.prototype.addListener=U(function(v,j){return h(this,v,j,!1)},"addListener"),z.prototype.on=z.prototype.addListener,z.prototype.prependListener=U(function(v,j){return h(this,v,j,!0)},"prependListener");function _(){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(_,"onceWrapper");function D(v,j,A){var N={fired:!1,wrapFn:void 0,target:v,type:j,listener:A},b=_.bind(N);return b.listener=A,N.wrapFn=b,b}U(D,"_onceWrap"),z.prototype.once=U(function(v,j){return w(j),this.on(v,D(this,v,j)),this},"once"),z.prototype.prependOnceListener=U(function(v,j){return w(j),this.prependListener(v,D(this,v,j)),this},"prependOnceListener"),z.prototype.removeListener=U(function(v,j){var A,N,b,C,u;if(w(j),N=this._events,N===void 0)return this;if(A=N[v],A===void 0)return this;if(A===j||A.listener===j)--this._eventsCount===0?this._events=Object.create(null):(delete N[v],N.removeListener&&this.emit("removeListener",v,A.listener||j));else if(typeof A!="function"){for(b=-1,C=A.length-1;C>=0;C--)if(A[C]===j||A[C].listener===j){u=A[C].listener,b=C;break}if(b<0)return this;b===0?A.shift():f(A,b),A.length===1&&(N[v]=A[0]),N.removeListener!==void 0&&this.emit("removeListener",v,u||j)}return this},"removeListener"),z.prototype.off=z.prototype.removeListener,z.prototype.removeAllListeners=U(function(v){var j,A,N;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[v]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[v]),this;if(arguments.length===0){var b=Object.keys(A),C;for(N=0;N<b.length;++N)C=b[N],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(j=A[v],typeof j=="function")this.removeListener(v,j);else if(j!==void 0)for(N=j.length-1;N>=0;N--)this.removeListener(v,j[N]);return this},"removeAllListeners");function F(v,j,A){var N=v._events;if(N===void 0)return[];var b=N[j];return b===void 0?[]:typeof b=="function"?A?[b.listener||b]:[b]:A?T(b):P(b,b.length)}U(F,"_listeners"),z.prototype.listeners=U(function(v){return F(this,v,!0)},"listeners"),z.prototype.rawListeners=U(function(v){return F(this,v,!1)},"rawListeners"),z.listenerCount=function(v,j){return typeof v.listenerCount=="function"?v.listenerCount(j):M.call(v,j)},z.prototype.listenerCount=M;function M(v){var j=this._events;if(j!==void 0){var A=j[v];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}U(M,"listenerCount"),z.prototype.eventNames=U(function(){return this._eventsCount>0?Z(this._events):[]},"eventNames");function P(v,j){for(var A=Array(j),N=0;N<j;++N)A[N]=v[N];return A}U(P,"arrayClone");function f(v,j){for(;j+1<v.length;j++)v[j]=v[j+1];v.pop()}U(f,"spliceOne");function T(v){for(var j=Array(v.length),A=0;A<j.length;++A)j[A]=v[A].listener||v[A];return j}U(T,"unwrapListeners");function S(v,j){return new Promise(function(A,N){function b(u){v.removeListener(j,C),N(u)}U(b,"errorListener");function C(){typeof v.removeListener=="function"&&v.removeListener("error",b),A([].slice.call(arguments))}U(C,"resolver"),Q(v,j,C,{once:!0}),j!=="error"&&q(v,b,{once:!0})})}U(S,"once");function q(v,j,A){typeof v.on=="function"&&Q(v,"error",j,A)}U(q,"addErrorHandlerIfEventEmitter");function Q(v,j,A,N){if(typeof v.on=="function")N.once?v.once(j,A):v.on(j,A);else if(typeof v.addEventListener=="function")v.addEventListener(j,U(function b(C){N.once&&v.removeEventListener(j,b),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}U(Q,"eventTargetAgnosticAddListener")}),c5={};_1(c5,{Socket:()=>V0,isIP:()=>u5});function u5(W){return 0}var q5,c6,A8,V0,Q8=tW(()=>{l(),q5=R0(F0(),1),U(u5,"isIP"),c6=/^[^.]+\./,A8=class W extends q5.EventEmitter{constructor(){super(...arguments);s(this,"opts",{}),s(this,"connecting",!1),s(this,"pending",!0),s(this,"writable",!0),s(this,"encrypted",!1),s(this,"authorized",!1),s(this,"destroyed",!1),s(this,"ws",null),s(this,"writeBuffer"),s(this,"tlsState",0),s(this,"tlsRead"),s(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($,k){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($,k):`${J}?address=${$}:${k}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,k,J){this.connecting=!0,J&&this.once("connect",J);let Z=U(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),X=U((z,V=!1)=>{z.binaryType="arraybuffer",z.addEventListener("error",(w)=>{this.emit("error",w),this.emit("close")}),z.addEventListener("message",(w)=>{if(this.tlsState===0){let R=t.from(w.data);this.emit("data",R)}}),z.addEventListener("close",()=>{this.emit("close")}),V?Z():z.addEventListener("open",Z)},"configureWebSocket"),G;try{G=this.wsProxyAddrForHost(k,typeof $=="string"?parseInt($,10):$)}catch(z){this.emit("error",z),this.emit("close");return}try{let z=(this.useSecureWebSocket?"wss:":"ws:")+"//"+G;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(z),X(this.ws);else try{this.ws=new WebSocket(z),X(this.ws)}catch{this.ws=new __unstable_WebSocket(z),X(this.ws)}}catch(z){let V=(this.useSecureWebSocket?"https:":"http:")+"//"+G;fetch(V,{headers:{Upgrade:"websocket"}}).then((w)=>{if(this.ws=w.webSocket,this.ws==null)throw z;this.ws.accept(),X(this.ws,!0)}).catch((w)=>{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: ${w}`)),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 k=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),Z=J.read.bind(J),X=this.rawWrite.bind(this),{read:G,write:z}=await this.subtls.startTls($,k,Z,X,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=G,this.tlsWrite=z,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 k=t.from($);this.emit("data",k)}}}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 k=new Uint8Array(this.writeBuffer.length+$.length);k.set(this.writeBuffer),k.set($,this.writeBuffer.length),this.writeBuffer=k}}write($,k="utf8",J=(Z)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=t.from($,k)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,k,J)}):(this.tlsWrite($),J()),!0)}end($=t.alloc(0),k="utf8",J=()=>{}){return this.write($,k,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},U(A8,"Socket"),s(A8,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:U((W,$,k)=>{let J;return k?.jwtAuth?J=W.replace(c6,"apiauth."):J=W.replace(c6,"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}),s(A8,"opts",{}),V0=A8}),l5={};_1(l5,{parse:()=>s6});function s6(W,$=!1){let{protocol:k}=new URL(W),J="http:"+W.substring(k.length),{username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,searchParams:h,hash:_}=new URL(J);X=decodeURIComponent(X),Z=decodeURIComponent(Z),w=decodeURIComponent(w);let D=Z+":"+X,F=$?Object.fromEntries(h.entries()):R;return{href:W,protocol:k,auth:D,username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,query:F,hash:_}}var i5=tW(()=>{l(),U(s6,"parse")}),p5=r((W)=>{l(),W.parse=function(Z,X){return new k(Z,X).parse()};var $=class Z{constructor(X,G){this.source=X,this.transform=G||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var X=this.source[this.position++];return X==="\\"?{value:this.source[this.position++],escaped:!0}:{value:X,escaped:!1}}record(X){this.recorded.push(X)}newEntry(X){var G;(this.recorded.length>0||X)&&(G=this.recorded.join(""),G==="NULL"&&!X&&(G=null),G!==null&&(G=this.transform(G)),this.entries.push(G),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var X=this.nextCharacter();if(X.value==="=")break}}parse(X){var G,z,V;for(this.consumeDimensions();!this.isEof();)if(G=this.nextCharacter(),G.value==="{"&&!V)this.dimension++,this.dimension>1&&(z=new Z(this.source.substr(this.position-1),this.transform),this.entries.push(z.parse(!0)),this.position+=z.position-2);else if(G.value==="}"&&!V){if(this.dimension--,!this.dimension&&(this.newEntry(),X))return this.entries}else G.value==='"'&&!G.escaped?(V&&this.newEntry(!0),V=!V):G.value===","&&!V?this.newEntry():this.record(G.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};U($,"ArrayParser");var k=$;function J(Z){return Z}U(J,"identity")}),t5=r((W,$)=>{l();var k=p5();$.exports={create:U(function(J,Z){return{parse:U(function(){return k.parse(J,Z)},"parse")}},"create")}}),Bk=r((W,$)=>{l();var k=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Z=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,X=/^-?infinity$/;$.exports=U(function(R){if(X.test(R))return Number(R.replace("i","I"));var h=k.exec(R);if(!h)return G(R)||null;var _=!!h[8],D=parseInt(h[1],10);_&&(D=V(D));var F=parseInt(h[2],10)-1,M=h[3],P=parseInt(h[4],10),f=parseInt(h[5],10),T=parseInt(h[6],10),S=h[7];S=S?1000*parseFloat(S):0;var q,Q=z(R);return Q!=null?(q=new Date(Date.UTC(D,F,M,P,f,T,S)),w(D)&&q.setUTCFullYear(D),Q!==0&&q.setTime(q.getTime()-Q)):(q=new Date(D,F,M,P,f,T,S),w(D)&&q.setFullYear(D)),q},"parseDate");function G(R){var h=J.exec(R);if(h){var _=parseInt(h[1],10),D=!!h[4];D&&(_=V(_));var F=parseInt(h[2],10)-1,M=h[3],P=new Date(_,F,M);return w(_)&&P.setFullYear(_),P}}U(G,"getDate");function z(R){if(R.endsWith("+00"))return 0;var h=Z.exec(R.split(" ")[1]);if(h){var _=h[1];if(_==="Z")return 0;var D=_==="-"?-1:1,F=parseInt(h[2],10)*3600+parseInt(h[3]||0,10)*60+parseInt(h[4]||0,10);return F*D*1000}}U(z,"timeZoneOffset");function V(R){return-(R-1)}U(V,"bcYearToNegativeYear");function w(R){return R>=0&&R<100}U(w,"is0To99")}),Ik=r((W,$)=>{l(),$.exports=J;var k=Object.prototype.hasOwnProperty;function J(Z){for(var X=1;X<arguments.length;X++){var G=arguments[X];for(var z in G)k.call(G,z)&&(Z[z]=G[z])}return Z}U(J,"extend")}),yk=r((W,$)=>{l();var k=Ik();$.exports=J;function J(T){if(!(this instanceof J))return new J(T);k(this,f(T))}U(J,"PostgresInterval");var Z=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var T=Z.filter(this.hasOwnProperty,this);return this.milliseconds&&T.indexOf("seconds")<0&&T.push("seconds"),T.length===0?"0":T.map(function(S){var q=this[S]||0;return S==="seconds"&&this.milliseconds&&(q=(q+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),q+" "+S},this).join(" ")};var X={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},G=["years","months","days"],z=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var T=G.map(q,this).join(""),S=z.map(q,this).join("");return"P"+T+"T"+S;function q(Q){var v=this[Q]||0;return Q==="seconds"&&this.milliseconds&&(v=(v+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),v+X[Q]}};var V="([+-]?\\d+)",w=V+"\\s+years?",R=V+"\\s+mons?",h=V+"\\s+days?",_="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",D=new RegExp([w,R,h,_].map(function(T){return"("+T+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},M=["hours","minutes","seconds","milliseconds"];function P(T){var S=T+"000000".slice(T.length);return parseInt(S,10)/1000}U(P,"parseMilliseconds");function f(T){if(!T)return{};var S=D.exec(T),q=S[8]==="-";return Object.keys(F).reduce(function(Q,v){var j=F[v],A=S[j];return!A||(A=v==="milliseconds"?P(A):parseInt(A,10),!A)||(q&&~M.indexOf(v)&&(A*=-1),Q[v]=A),Q},{})}U(f,"parse")}),gk=r((W,$)=>{l(),$.exports=U(function(k){if(/^\\x/.test(k))return new t(k.substr(2),"hex");for(var J="",Z=0;Z<k.length;)if(k[Z]!=="\\")J+=k[Z],++Z;else if(/[0-7]{3}/.test(k.substr(Z+1,3)))J+=String.fromCharCode(parseInt(k.substr(Z+1,3),8)),Z+=4;else{for(var X=1;Z+X<k.length&&k[Z+X]==="\\";)X++;for(var G=0;G<Math.floor(X/2);++G)J+="\\";Z+=Math.floor(X/2)*2}return new t(J,"binary")},"parseBytea")}),mk=r((W,$)=>{l();var k=p5(),J=t5(),Z=Bk(),X=yk(),G=gk();function z(N){return U(function(b){return b===null?b:N(b)},"nullAllowed")}U(z,"allowNull");function V(N){return N===null?N:N==="TRUE"||N==="t"||N==="true"||N==="y"||N==="yes"||N==="on"||N==="1"}U(V,"parseBool");function w(N){return N?k.parse(N,V):null}U(w,"parseBoolArray");function R(N){return parseInt(N,10)}U(R,"parseBaseTenInt");function h(N){return N?k.parse(N,z(R)):null}U(h,"parseIntegerArray");function _(N){return N?k.parse(N,z(function(b){return q(b).trim()})):null}U(_,"parseBigIntegerArray");var D=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=v(C)),C});return b.parse()},"parsePointArray"),F=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=parseFloat(C)),C});return b.parse()},"parseFloatArray"),M=U(function(N){if(!N)return null;var b=J.create(N);return b.parse()},"parseStringArray"),P=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=Z(C)),C});return b.parse()},"parseDateArray"),f=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=X(C)),C});return b.parse()},"parseIntervalArray"),T=U(function(N){return N?k.parse(N,z(G)):null},"parseByteAArray"),S=U(function(N){return parseInt(N,10)},"parseInteger"),q=U(function(N){var b=String(N);return/^\d+$/.test(b)?b:N},"parseBigInteger"),Q=U(function(N){return N?k.parse(N,z(JSON.parse)):null},"parseJsonArray"),v=U(function(N){return N[0]!=="("?null:(N=N.substring(1,N.length-1).split(","),{x:parseFloat(N[0]),y:parseFloat(N[1])})},"parsePoint"),j=U(function(N){if(N[0]!=="<"&&N[1]!=="(")return null;for(var b="(",C="",u=!1,c=2;c<N.length-1;c++){if(u||(b+=N[c]),N[c]===")"){u=!0;continue}else if(!u)continue;N[c]!==","&&(C+=N[c])}var B=v(b);return B.radius=parseFloat(C),B},"parseCircle"),A=U(function(N){N(20,q),N(21,S),N(23,S),N(26,S),N(700,parseFloat),N(701,parseFloat),N(16,V),N(1082,Z),N(1114,Z),N(1184,Z),N(600,v),N(651,M),N(718,j),N(1000,w),N(1001,T),N(1005,h),N(1007,h),N(1028,h),N(1016,_),N(1017,D),N(1021,F),N(1022,F),N(1231,F),N(1014,M),N(1015,M),N(1008,M),N(1009,M),N(1040,M),N(1041,M),N(1115,P),N(1182,P),N(1185,P),N(1186,X),N(1187,f),N(17,G),N(114,JSON.parse.bind(JSON)),N(3802,JSON.parse.bind(JSON)),N(199,Q),N(3807,Q),N(3907,M),N(2951,M),N(791,M),N(1183,M),N(1270,M)},"init");$.exports={init:A}}),ck=r((W,$)=>{l();var k=1e6;function J(Z){var X=Z.readInt32BE(0),G=Z.readUInt32BE(4),z="";X<0&&(X=~X+(G===0),G=~G+1>>>0,z="-");var V="",w,R,h,_,D,F;{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}return w=X%k,R=4294967296*w+G,h=""+R%k,z+h+V}U(J,"readInt8"),$.exports=J}),uk=r((W,$)=>{l();var k=ck(),J=U(function(M,P,f,T,S){f=f||0,T=T||!1,S=S||function(u,c,B){return u*Math.pow(2,B)+c};var q=f>>3,Q=U(function(u){return T?~u&255:u},"inv"),v=255,j=8-f%8;P<j&&(v=255<<8-P&255,j=P),f&&(v=v>>f%8);var A=0;f%8+P>=8&&(A=S(0,Q(M[q])&v,j));for(var N=P+f>>3,b=q+1;b<N;b++)A=S(A,Q(M[b]),8);var C=(P+f)%8;return C>0&&(A=S(A,Q(M[N])>>8-C,C)),A},"parseBits"),Z=U(function(M,P,f){var T=Math.pow(2,f-1)-1,S=J(M,1),q=J(M,f,1);if(q===0)return 0;var Q=1,v=U(function(A,N,b){A===0&&(A=1);for(var C=1;C<=b;C++)Q/=2,(N&1<<b-C)>0&&(A+=Q);return A},"parsePrecisionBits"),j=J(M,P,f+1,!1,v);return q==Math.pow(2,f+1)-1?j===0?S===0?1/0:-1/0:NaN:(S===0?1:-1)*Math.pow(2,q-T)*j},"parseFloatFromBits"),X=U(function(M){return J(M,1)==1?-1*(J(M,15,1,!0)+1):J(M,15,1)},"parseInt16"),G=U(function(M){return J(M,1)==1?-1*(J(M,31,1,!0)+1):J(M,31,1)},"parseInt32"),z=U(function(M){return Z(M,23,8)},"parseFloat32"),V=U(function(M){return Z(M,52,11)},"parseFloat64"),w=U(function(M){var P=J(M,16,32);if(P==49152)return NaN;for(var f=Math.pow(1e4,J(M,16,16)),T=0,S=[],q=J(M,16),Q=0;Q<q;Q++)T+=J(M,16,64+16*Q)*f,f/=1e4;var v=Math.pow(10,J(M,16,48));return(P===0?1:-1)*Math.round(T*v)/v},"parseNumeric"),R=U(function(M,P){var f=J(P,1),T=J(P,63,1),S=new Date((f===0?1:-1)*T/1000+946684800000);return M||S.setTime(S.getTime()+S.getTimezoneOffset()*60000),S.usec=T%1000,S.getMicroSeconds=function(){return this.usec},S.setMicroSeconds=function(q){this.usec=q},S.getUTCMicroSeconds=function(){return this.usec},S},"parseDate"),h=U(function(M){for(var P=J(M,32),f=J(M,32,32),T=J(M,32,64),S=96,q=[],Q=0;Q<P;Q++)q[Q]=J(M,32,S),S+=32,S+=32;var v=U(function(A){var N=J(M,32,S);if(S+=32,N==4294967295)return null;var b;if(A==23||A==20)return b=J(M,N*8,S),S+=N*8,b;if(A==25)return b=M.toString(this.encoding,S>>3,(S+=N<<3)>>3),b;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),j=U(function(A,N){var b=[],C;if(A.length>1){var u=A.shift();for(C=0;C<u;C++)b[C]=j(A,N);A.unshift(u)}else for(C=0;C<A[0];C++)b[C]=v(N);return b},"parse");return j(q,T)},"parseArray"),_=U(function(M){return M.toString("utf8")},"parseText"),D=U(function(M){return M===null?null:J(M,8)>0},"parseBool"),F=U(function(M){M(20,k),M(21,X),M(23,G),M(26,G),M(1700,w),M(700,z),M(701,V),M(16,D),M(1114,R.bind(null,!1)),M(1184,R.bind(null,!0)),M(1000,h),M(1007,h),M(1016,h),M(1008,h),M(1009,h),M(25,_)},"init");$.exports={init:F}}),lk=r((W,$)=>{l(),$.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}}),f4=r((W)=>{l();var $=mk(),k=uk(),J=t5(),Z=lk();W.getTypeParser=z,W.setTypeParser=V,W.arrayParser=J,W.builtins=Z;var X={text:{},binary:{}};function G(w){return String(w)}U(G,"noParse");function z(w,R){return R=R||"text",X[R]&&X[R][w]||G}U(z,"getTypeParser");function V(w,R,h){typeof R=="function"&&(h=R,R="text"),X[R][w]=h}U(V,"setTypeParser"),$.init(function(w,R){X.text[w]=R}),k.init(function(w,R){X.binary[w]=R})}),a6=r((W,$)=>{l();var k=f4();function J(Z){this._types=Z||k,this.text={},this.binary={}}U(J,"TypeOverrides"),J.prototype.getOverrides=function(Z){switch(Z){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(Z,X,G){typeof X=="function"&&(G=X,X="text"),this.getOverrides(X)[Z]=G},J.prototype.getTypeParser=function(Z,X){return X=X||"text",this.getOverrides(X)[Z]||this._types.getTypeParser(Z,X)},$.exports=J});function C8(W){let $=1779033703,k=3144134277,J=1013904242,Z=2773480762,X=1359893119,G=2600822924,z=528734635,V=1541459225,w=0,R=0,h=[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],_=U((T,S)=>T>>>S|T<<32-S,"rrot"),D=new Uint32Array(64),F=new Uint8Array(64),M=U(()=>{for(let b=0,C=0;b<16;b++,C+=4)D[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[b-15],7)^_(D[b-15],18)^D[b-15]>>>3,u=_(D[b-2],17)^_(D[b-2],19)^D[b-2]>>>10;D[b]=D[b-16]+C+D[b-7]+u|0}let T=$,S=k,q=J,Q=Z,v=X,j=G,A=z,N=V;for(let b=0;b<64;b++){let C=_(v,6)^_(v,11)^_(v,25),u=v&j^~v&A,c=N+C+u+h[b]+D[b]|0,B=_(T,2)^_(T,13)^_(T,22),m=T&S^T&q^S&q,p=B+m|0;N=A,A=j,j=v,v=Q+c|0,Q=q,q=S,S=T,T=c+p|0}$=$+T|0,k=k+S|0,J=J+q|0,Z=Z+Q|0,X=X+v|0,G=G+j|0,z=z+A|0,V=V+N|0,R=0},"process"),P=U((T)=>{typeof T=="string"&&(T=new TextEncoder().encode(T));for(let S=0;S<T.length;S++)F[R++]=T[S],R===64&&M();w+=T.length},"add"),f=U(()=>{if(F[R++]=128,R==64&&M(),R+8>64){for(;R<64;)F[R++]=0;M()}for(;R<58;)F[R++]=0;let T=w*8;F[R++]=T/1099511627776&255,F[R++]=T/4294967296&255,F[R++]=T>>>24,F[R++]=T>>>16&255,F[R++]=T>>>8&255,F[R++]=T&255,M();let S=new Uint8Array(32);return S[0]=$>>>24,S[1]=$>>>16&255,S[2]=$>>>8&255,S[3]=$&255,S[4]=k>>>24,S[5]=k>>>16&255,S[6]=k>>>8&255,S[7]=k&255,S[8]=J>>>24,S[9]=J>>>16&255,S[10]=J>>>8&255,S[11]=J&255,S[12]=Z>>>24,S[13]=Z>>>16&255,S[14]=Z>>>8&255,S[15]=Z&255,S[16]=X>>>24,S[17]=X>>>16&255,S[18]=X>>>8&255,S[19]=X&255,S[20]=G>>>24,S[21]=G>>>16&255,S[22]=G>>>8&255,S[23]=G&255,S[24]=z>>>24,S[25]=z>>>16&255,S[26]=z>>>8&255,S[27]=z&255,S[28]=V>>>24,S[29]=V>>>16&255,S[30]=V>>>8&255,S[31]=V&255,S},"digest");return W===void 0?{add:P,digest:f}:(P(W),f())}var ik=tW(()=>{l(),U(C8,"sha256")}),c1,l6,pk=tW(()=>{l(),c1=class W{constructor(){s(this,"_dataLength",0),s(this,"_bufferLength",0),s(this,"_state",new Int32Array(4)),s(this,"_buffer",new ArrayBuffer(68)),s(this,"_buffer8"),s(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,k=!1){return this.onePassHasher.start().appendByteArray($).end(k)}static hashStr($,k=!1){return this.onePassHasher.start().appendStr($).end(k)}static hashAsciiStr($,k=!1){return this.onePassHasher.start().appendAsciiStr($).end(k)}static _hex($){let{hexChars:k,hexOut:J}=W,Z,X,G,z;for(z=0;z<4;z+=1)for(X=z*8,Z=$[z],G=0;G<8;G+=2)J[X+1+G]=k.charAt(Z&15),Z>>>=4,J[X+0+G]=k.charAt(Z&15),Z>>>=4;return J.join("")}static _md5cycle($,k){let J=$[0],Z=$[1],X=$[2],G=$[3];J+=(Z&X|~Z&G)+k[0]-680876936|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[1]-389564586|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[2]+606105819|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[3]-1044525330|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[4]-176418897|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[5]+1200080426|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[6]-1473231341|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[7]-45705983|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[8]+1770035416|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[9]-1958414417|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[10]-42063|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[11]-1990404162|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[12]+1804603682|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[13]-40341101|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[14]-1502002290|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[15]+1236535329|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&G|X&~G)+k[1]-165796510|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[6]-1069501632|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[11]+643717713|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[0]-373897302|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[5]-701558691|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[10]+38016083|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[15]-660478335|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[4]-405537848|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[9]+568446438|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[14]-1019803690|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[3]-187363961|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[8]+1163531501|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[13]-1444681467|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[2]-51403784|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[7]+1735328473|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[12]-1926607734|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z^X^G)+k[5]-378558|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[8]-2022574463|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[11]+1839030562|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[14]-35309556|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[1]-1530992060|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[4]+1272893353|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[7]-155497632|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[10]-1094730640|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[13]+681279174|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[0]-358537222|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[3]-722521979|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[6]+76029189|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[9]-640364487|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[12]-421815835|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[15]+530742520|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[2]-995338651|0,Z=(Z<<23|Z>>>9)+X|0,J+=(X^(Z|~G))+k[0]-198630844|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[7]+1126891415|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[14]-1416354905|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[5]-57434055|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[12]+1700485571|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[3]-1894986606|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[10]-1051523|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[1]-2054922799|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[8]+1873313359|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[15]-30611744|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[6]-1560198380|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[13]+1309151649|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[4]-145523070|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[11]-1120210379|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[2]+718787259|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[9]-343485551|0,Z=(Z<<21|Z>>>11)+X|0,$[0]=J+$[0]|0,$[1]=Z+$[1]|0,$[2]=X+$[2]|0,$[3]=G+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G;for(G=0;G<$.length;G+=1){if(X=$.charCodeAt(G),X<128)k[Z++]=X;else if(X<2048)k[Z++]=(X>>>6)+192,k[Z++]=X&63|128;else if(X<55296||X>56319)k[Z++]=(X>>>12)+224,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128;else{if(X=(X-55296)*1024+($.charCodeAt(++G)-56320)+65536,X>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");k[Z++]=(X>>>18)+240,k[Z++]=X>>>12&63|128,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128}Z>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),Z-=64,J[0]=J[16])}return this._bufferLength=Z,this}appendAsciiStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$.charCodeAt(G++);if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,this}appendByteArray($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$[G++];if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,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:k,state:J}=$,Z=this._state,X;for(this._dataLength=$.length,this._bufferLength=$.buflen,Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[3],X=0;X<k.length;X+=1)this._buffer8[X]=k.charCodeAt(X)}end($=!1){let k=this._bufferLength,J=this._buffer8,Z=this._buffer32,X=(k>>2)+1;this._dataLength+=k;let G=this._dataLength*8;if(J[k]=128,J[k+1]=J[k+2]=J[k+3]=0,Z.set(W.buffer32Identity.subarray(X),X),k>55&&(W._md5cycle(this._state,Z),Z.set(W.buffer32Identity)),G<=4294967295)Z[14]=G;else{let z=G.toString(16).match(/(.*?)(.{0,8})$/);if(z===null)return;let V=parseInt(z[2],16),w=parseInt(z[1],16)||0;Z[14]=V,Z[15]=w}return W._md5cycle(this._state,Z),$?this._state:W._hex(this._state)}},U(c1,"Md5"),s(c1,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),s(c1,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),s(c1,"hexChars","0123456789abcdef"),s(c1,"hexOut",[]),s(c1,"onePassHasher",new c1),l6=c1}),d6={};_1(d6,{createHash:()=>a5,createHmac:()=>d5,randomBytes:()=>s5});function s5(W){return crypto.getRandomValues(t.alloc(W))}function a5(W){if(W==="sha256")return{update:U(function($){return{digest:U(function(){return t.from(C8($))},"digest")}},"update")};if(W==="md5")return{update:U(function($){return{digest:U(function(){return typeof $=="string"?l6.hashStr($):l6.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function d5(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:U(function(k){return{digest:U(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof k=="string"&&(k=new TextEncoder().encode(k));let J=$.length;if(J>64)$=C8($);else if(J<64){let V=new Uint8Array(64);V.set($),$=V}let Z=new Uint8Array(64),X=new Uint8Array(64);for(let V=0;V<64;V++)Z[V]=54^$[V],X[V]=92^$[V];let G=new Uint8Array(k.length+64);G.set(Z,0),G.set(k,64);let z=new Uint8Array(96);return z.set(X,0),z.set(C8(G),64),t.from(C8(z))},"digest")}},"update")}}var n5=tW(()=>{l(),ik(),pk(),U(s5,"randomBytes"),U(a5,"createHash"),U(d5,"createHmac")}),T4=r((W,$)=>{l(),$.exports={host:"localhost",user:o.platform==="win32"?o.env.USERNAME:o.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 k=f4(),J=k.getTypeParser(20,"text"),Z=k.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(X){k.setTypeParser(20,"text",X?k.getTypeParser(23,"text"):J),k.setTypeParser(1016,"text",X?k.getTypeParser(1007,"text"):Z)})}),v4=r((W,$)=>{l();var k=(n5(),QW(d6)),J=T4();function Z(F){var M=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+M+'"'}U(Z,"escapeElement");function X(F){for(var M="{",P=0;P<F.length;P++)P>0&&(M=M+","),F[P]===null||typeof F[P]>"u"?M=M+"NULL":Array.isArray(F[P])?M=M+X(F[P]):F[P]instanceof t?M+="\\\\x"+F[P].toString("hex"):M+=Z(G(F[P]));return M=M+"}",M}U(X,"arrayString");var G=U(function(F,M){if(F==null)return null;if(F instanceof t)return F;if(ArrayBuffer.isView(F)){var P=t.from(F.buffer,F.byteOffset,F.byteLength);return P.length===F.byteLength?P:P.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?R(F):w(F):Array.isArray(F)?X(F):typeof F=="object"?z(F,M):F.toString()},"prepareValue");function z(F,M){if(F&&typeof F.toPostgres=="function"){if(M=M||[],M.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return M.push(F),G(F.toPostgres(G),M)}return JSON.stringify(F)}U(z,"prepareObject");function V(F,M){for(F=""+F;F.length<M;)F="0"+F;return F}U(V,"pad");function w(F){var M=-F.getTimezoneOffset(),P=F.getFullYear(),f=P<1;f&&(P=Math.abs(P)+1);var T=V(P,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 M<0?(T+="-",M*=-1):T+="+",T+=V(Math.floor(M/60),2)+":"+V(M%60,2),f&&(T+=" BC"),T}U(w,"dateToString");function R(F){var M=F.getUTCFullYear(),P=M<1;P&&(M=Math.abs(M)+1);var f=V(M,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 f+="+00:00",P&&(f+=" BC"),f}U(R,"dateToStringUTC");function h(F,M,P){return F=typeof F=="string"?{text:F}:F,M&&(typeof M=="function"?F.callback=M:F.values=M),P&&(F.callback=P),F}U(h,"normalizeQueryConfig");var _=U(function(F){return k.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),D=U(function(F,M,P){var f=_(M+F),T=_(t.concat([t.from(f),P]));return"md5"+T},"postgresMd5PasswordHash");$.exports={prepareValue:U(function(F){return G(F)},"prepareValueWrapper"),normalizeQueryConfig:h,postgresMd5PasswordHash:D,md5:_}}),x8={};_1(x8,{default:()=>o5});var o5,E4=tW(()=>{l(),o5={}}),tk=r((W,$)=>{l();var k=(n5(),QW(d6));function J(M){if(M.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let P=k.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:P,response:"n,,n=*,r="+P,message:"SASLInitialResponse"}}U(J,"startSession");function Z(M,P,f){if(M.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof f!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let T=w(f);if(T.nonce.startsWith(M.clientNonce)){if(T.nonce.length===M.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 S=t.from(T.salt,"base64"),q=F(P,S,T.iteration),Q=D(q,"Client Key"),v=_(Q),j="n=*,r="+M.clientNonce,A="r="+T.nonce+",s="+T.salt+",i="+T.iteration,N="c=biws,r="+T.nonce,b=j+","+A+","+N,C=D(v,b),u=h(Q,C),c=u.toString("base64"),B=D(q,"Server Key"),m=D(B,b);M.message="SASLResponse",M.serverSignature=m.toString("base64"),M.response=N+",p="+c}U(Z,"continueSession");function X(M,P){if(M.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:f}=R(P);if(f!==M.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}U(X,"finalizeSession");function G(M){if(typeof M!="string")throw TypeError("SASL: text must be a string");return M.split("").map((P,f)=>M.charCodeAt(f)).every((P)=>P>=33&&P<=43||P>=45&&P<=126)}U(G,"isPrintableChars");function z(M){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(M)}U(z,"isBase64");function V(M){if(typeof M!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(M.split(",").map((P)=>{if(!/^.=/.test(P))throw Error("SASL: Invalid attribute pair entry");let f=P[0],T=P.substring(2);return[f,T]}))}U(V,"parseAttributePairs");function w(M){let P=V(M),f=P.get("r");if(f){if(!G(f))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let T=P.get("s");if(T){if(!z(T))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let S=P.get("i");if(S){if(!/^[1-9][0-9]*$/.test(S))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let q=parseInt(S,10);return{nonce:f,salt:T,iteration:q}}U(w,"parseServerFirstMessage");function R(M){let P=V(M).get("v");if(P){if(!z(P))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:P}}U(R,"parseServerFinalMessage");function h(M,P){if(!t.isBuffer(M))throw TypeError("first argument must be a Buffer");if(!t.isBuffer(P))throw TypeError("second argument must be a Buffer");if(M.length!==P.length)throw Error("Buffer lengths must match");if(M.length===0)throw Error("Buffers cannot be empty");return t.from(M.map((f,T)=>M[T]^P[T]))}U(h,"xorBuffers");function _(M){return k.createHash("sha256").update(M).digest()}U(_,"sha256");function D(M,P){return k.createHmac("sha256",M).update(P).digest()}U(D,"hmacSha256");function F(M,P,f){for(var T=D(M,t.concat([P,t.from([0,0,0,1])])),S=T,q=0;q<f-1;q++)T=D(M,T),S=h(S,T);return S}U(F,"Hi"),$.exports={startSession:J,continueSession:Z,finalizeSession:X}}),n6={};_1(n6,{join:()=>r5});function r5(...W){return W.join("/")}var e5=tW(()=>{l(),U(r5,"join")}),o6={};_1(o6,{stat:()=>W7});function W7(W,$){$(Error("No filesystem"))}var $7=tW(()=>{l(),U(W7,"stat")}),r6={};_1(r6,{default:()=>k7});var k7,J7=tW(()=>{l(),k7={}}),Z7={};_1(Z7,{StringDecoder:()=>X7});var u6,X7,sk=tW(()=>{l(),u6=class{constructor($){s(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},U(u6,"StringDecoder"),X7=u6}),ak=r((W,$)=>{l();var{Transform:k}=(J7(),QW(r6)),{StringDecoder:J}=(sk(),QW(Z7)),Z=Symbol("last"),X=Symbol("decoder");function G(h,_,D){let F;if(this.overflow){if(F=this[X].write(h).split(this.matcher),F.length===1)return D();F.shift(),this.overflow=!1}else this[Z]+=this[X].write(h),F=this[Z].split(this.matcher);this[Z]=F.pop();for(let M=0;M<F.length;M++)try{V(this,this.mapper(F[M]))}catch(P){return D(P)}if(this.overflow=this[Z].length>this.maxLength,this.overflow&&!this.skipOverflow){D(Error("maximum buffer reached"));return}D()}U(G,"transform");function z(h){if(this[Z]+=this[X].end(),this[Z])try{V(this,this.mapper(this[Z]))}catch(_){return h(_)}h()}U(z,"flush");function V(h,_){_!==void 0&&h.push(_)}U(V,"push");function w(h){return h}U(w,"noop");function R(h,_,D){switch(h=h||/\r?\n/,_=_||w,D=D||{},arguments.length){case 1:typeof h=="function"?(_=h,h=/\r?\n/):typeof h=="object"&&!(h instanceof RegExp)&&!h[Symbol.split]&&(D=h,h=/\r?\n/);break;case 2:typeof h=="function"?(D=_,_=h,h=/\r?\n/):typeof _=="object"&&(D=_,_=w)}D=Object.assign({},D),D.autoDestroy=!0,D.transform=G,D.flush=z,D.readableObjectMode=!0;let F=new k(D);return F[Z]="",F[X]=new J("utf8"),F.matcher=h,F.mapper=_,F.maxLength=D.maxLength,F.skipOverflow=D.skipOverflow||!1,F.overflow=!1,F._destroy=function(M,P){this._writableState.errorEmitted=!1,P(M)},F}U(R,"split"),$.exports=R}),dk=r((W,$)=>{l();var k=(e5(),QW(n6)),J=(J7(),QW(r6)).Stream,Z=ak(),X=(E4(),QW(x8)),G=5432,z=o.platform==="win32",V=o.stderr,w=56,R=7,h=61440,_=32768;function D(Q){return(Q&h)==_}U(D,"isRegFile");var F=["host","port","database","user","password"],M=F.length,P=F[M-1];function f(){var Q=V instanceof J&&V.writable===!0;if(Q){var v=Array.prototype.slice.call(arguments).concat(`
27
+ `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function _9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let k,J="127.0.0.1",Z="9229",X;if((X=$.match(/^(--inspect(-brk)?)$/))!==null)k=X[1];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(k=X[1],/^\d+$/.test(X[3]))Z=X[3];else J=X[3];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)k=X[1],J=X[3],Z=X[4];if(k&&Z!=="0")return`${k}=${J}:${parseInt(Z)+1}`;return $})}function u4(){if(XW.env.NO_COLOR||XW.env.FORCE_COLOR==="0"||XW.env.FORCE_COLOR==="false")return!1;if(XW.env.FORCE_COLOR||XW.env.CLICOLOR_FORCE!==void 0)return!0;return}E$.Command=l4;E$.useColor=u4});var T9=X0((j$)=>{var{Argument:P9}=y8(),{Command:i4}=h9(),{CommanderError:O$,InvalidArgumentError:D9}=k8(),{Help:A$}=y4(),{Option:f9}=g4();j$.program=new i4;j$.createCommand=(W)=>new i4(W);j$.createOption=(W,$)=>new f9(W,$);j$.createArgument=(W,$)=>new P9(W,$);j$.Command=i4;j$.Option=f9;j$.Argument=P9;j$.Help=A$;j$.CommanderError=O$;j$.InvalidArgumentError=D9;j$.InvalidOptionArgumentError=D9});var v9=n7(T9(),1),{program:WJ,createCommand:$J,createArgument:kJ,createOption:JJ,CommanderError:ZJ,InvalidArgumentError:XJ,InvalidOptionArgumentError:YJ,Command:E9,Argument:HJ,Option:zJ,Help:GJ}=v9.default;import j4 from"path";import{fileURLToPath as m2}from"url";import{createRequire as c2}from"module";import{execSync as u2,spawn as l2}from"child_process";function aW(W){return typeof W>"u"||W===void 0}function _W(W){return typeof W==="string"}function u1(W){return typeof W==="number"}function Y0(W){return typeof W==="boolean"}function h0(W){return W===null}function S9(W){return W instanceof Date}function P0(W){return typeof W==="bigint"}function hW(W){return typeof W==="function"}function TW(W){return typeof W==="object"&&W!==null}function N9(W){return W[W.length-1]}function H(W){return Object.freeze(W)}function J8(W){if(bW(W))return W;else return[W]}function bW(W){return Array.isArray(W)}function yW(W){return W}var $W=H({is(W){return W.kind==="AlterTableNode"},create(W){return H({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return H({...W,...$})},cloneWithColumnAlteration(W,$){return H({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var i=H({is(W){return W.kind==="IdentifierNode"},create(W){return H({kind:"IdentifierNode",name:W})}});var X1=H({is(W){return W.kind==="CreateIndexNode"},create(W){return H({kind:"CreateIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});var m8=H({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return H({kind:"CreateSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var O9=["preserve rows","delete rows","drop"],BW=H({is(W){return W.kind==="CreateTableNode"},create(W){return H({kind:"CreateTableNode",table:W,columns:H([])})},cloneWithColumn(W,$){return H({...W,columns:H([...W.columns,$])})},cloneWithConstraint(W,$){return H({...W,constraints:W.constraints?H([...W.constraints,$]):H([$])})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWith(W,$){return H({...W,...$})}});var IW=H({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return H({kind:"SchemableIdentifierNode",identifier:i.create(W)})},createWithSchema(W,$){return H({kind:"SchemableIdentifierNode",schema:i.create(W),identifier:i.create($)})}});var l1=H({is(W){return W.kind==="DropIndexNode"},create(W,$){return H({kind:"DropIndexNode",name:IW.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var Z8=H({is(W){return W.kind==="DropSchemaNode"},create(W,$){return H({kind:"DropSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var X8=H({is(W){return W.kind==="DropTableNode"},create(W,$){return H({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return H({...W,...$})}});var AW=H({is(W){return W.kind==="AliasNode"},create(W,$){return H({kind:"AliasNode",node:W,alias:$})}});var mW=H({is(W){return W.kind==="TableNode"},create(W){return H({kind:"TableNode",table:IW.create(W)})},createWithSchema(W,$){return H({kind:"TableNode",table:IW.createWithSchema(W,$)})}});function LW(W){return TW(W)&&hW(W.toOperationNode)}function c8(W){return TW(W)&&"expressionType"in W&&LW(W)}function A9(W){return TW(W)&&"expression"in W&&_W(W.alias)&&LW(W)}var h1=H({is(W){return W.kind==="SelectModifierNode"},create(W,$){return H({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return H({kind:"SelectModifierNode",rawModifier:W})}});var cW=H({is(W){return W.kind==="AndNode"},create(W,$){return H({kind:"AndNode",left:W,right:$})}});var Y1=H({is(W){return W.kind==="OrNode"},create(W,$){return H({kind:"OrNode",left:W,right:$})}});var u8=H({is(W){return W.kind==="OnNode"},create(W){return H({kind:"OnNode",on:W})},cloneWithOperation(W,$,k){return H({...W,on:$==="And"?cW.create(W.on,k):Y1.create(W.on,k)})}});var H1=H({is(W){return W.kind==="JoinNode"},create(W,$){return H({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,k){return H({kind:"JoinNode",joinType:W,table:$,on:u8.create(k)})},cloneWithOn(W,$){return H({...W,on:W.on?u8.cloneWithOperation(W.on,"And",$):u8.create($)})}});var i1=H({is(W){return W.kind==="BinaryOperationNode"},create(W,$,k){return H({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:k})}});var u$=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],l$=["+","-","*","/","%","^","&","|","#","<<",">>"],j9=["->","->>"],i$=[...u$,...l$,"&&","||"],p$=["exists","not exists"],t$=["not","-",...p$],C9=[...i$,...j9,...t$,"between","between symmetric"],dW=H({is(W){return W.kind==="OperatorNode"},create(W){return H({kind:"OperatorNode",operator:W})}});function p4(W){return _W(W)&&j9.includes(W)}var WW=H({is(W){return W.kind==="ColumnNode"},create(W){return H({kind:"ColumnNode",column:i.create(W)})}});var D0=H({is(W){return W.kind==="SelectAllNode"},create(){return H({kind:"SelectAllNode"})}});var f0=H({is(W){return W.kind==="ReferenceNode"},create(W,$){return H({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return H({kind:"ReferenceNode",table:W,column:D0.create()})}});class t4{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return s4(this.#W)}}function l8(W){return TW(W)&&LW(W)&&_W(W.dynamicReference)}var z1=H({is(W){return W.kind==="OrderByItemNode"},create(W,$){return H({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return H({...W,...$})}});var YW=H({is(W){return W.kind==="RawNode"},create(W,$){return H({kind:"RawNode",sqlFragments:H(W),parameters:H($)})},createWithSql(W){return YW.create([W],[])},createWithChild(W){return YW.create(["",""],[W])},createWithChildren(W){return YW.create(Array(W.length+1).fill(""),W)}});var Q9=H({is(W){return W.kind==="CollateNode"},create(W){return H({kind:"CollateNode",collation:i.create(W)})}});class p1{#W;constructor(W){this.#W=H(W)}desc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("desc")})})}asc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("asc")})})}nullsLast(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new p1({node:z1.cloneWith(this.#W.node,{collation:Q9.create(W)})})}toOperationNode(){return this.#W.node}}var x9=new Set;function P1(W){if(x9.has(W))return;x9.add(W),console.log(W)}function d4(W){return W==="asc"||W==="desc"}function oW(W){if(W.length===2)return[a4(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return P1("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((k)=>a4(k));return[a4($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function a4(W,$){let k=s$(W);if(z1.is(k)){if($)throw Error("Cannot specify direction twice!");return k}return q9(k,$)}function s$(W){if(j1(W))return uW(W);if(l8(W))return W.toOperationNode();let[$,k]=W.split(" ");if(k)return P1("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),q9(nW($),k);return nW(W)}function q9(W,$){if(typeof $==="string"){if(!d4($))throw Error(`Invalid order by direction: ${$}`);return z1.create(W,YW.createWithSql($))}if(c8($))return P1("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),z1.create(W,$.toOperationNode());let k=z1.create(W);if(!$)return k;return $(new p1({node:k})).toOperationNode()}var T0=H({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return H({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return H({...W,traversal:$})}});var i8=H({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return H({kind:"JSONOperatorChainNode",operator:W,values:H([])})},cloneWithValue(W,$){return H({...W,values:H([...W.values,$])})}});var t1=H({is(W){return W.kind==="JSONPathNode"},create(W){return H({kind:"JSONPathNode",inOperator:W,pathLegs:H([])})},cloneWithLeg(W,$){return H({...W,pathLegs:H([...W.pathLegs,$])})}});function s4(W){if(_W(W))return nW(W);return W.toOperationNode()}function C1(W){if(bW(W))return W.map(($)=>xW($));else return[xW(W)]}function xW(W){if(j1(W))return uW(W);return s4(W)}function b9(W,$){let k=nW(W);if(p4($))return T0.create(k,i8.create(dW.create($)));let J=$.slice(0,-1);if(p4(J))return T0.create(k,t1.create(dW.create(J)));throw Error(`Invalid JSON operator: ${$}`)}function nW(W){if(!W.includes("."))return f0.create(WW.create(W));let k=W.split(".").map(o4);if(k.length===3)return a$(k);if(k.length===2)return d$(k);throw Error(`invalid column reference ${W}`)}function B9(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(o4);return AW.create(nW(k),i.create(J))}else return nW(W)}function n4(W){return WW.create(W)}function v0(W){if(W.includes(" ")){let[k,J]=W.split(" ").map(o4);if(!d4(J))throw Error(`invalid order direction "${J}" next to "${k}"`);return oW([k,J])[0]}else return n4(W)}function a$(W){let[$,k,J]=W;return f0.create(WW.create(J),mW.createWithSchema($,k))}function d$(W){let[$,k]=W;return f0.create(WW.create(k),mW.create($))}function o4(W){return W.trim()}var p8=H({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return H({kind:"PrimitiveValueListNode",values:H([...W])})}});var s1=H({is(W){return W.kind==="ValueListNode"},create(W){return H({kind:"ValueListNode",values:H(W)})}});var EW=H({is(W){return W.kind==="ValueNode"},create(W){return H({kind:"ValueNode",value:W})},createImmediate(W){return H({kind:"ValueNode",value:W,immediate:!0})}});function I9(W){if(bW(W))return n$(W);return zW(W)}function zW(W){if(j1(W))return uW(W);return EW.create(W)}function t8(W){return u1(W)||Y0(W)||h0(W)}function Y8(W){if(!t8(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return EW.createImmediate(W)}function n$(W){if(W.some(j1))return s1.create(W.map(($)=>zW($)));return p8.create(W)}var rW=H({is(W){return W.kind==="ParensNode"},create(W){return H({kind:"ParensNode",node:W})}});function MW(W){if(W.length===3)return s8(W[0],W[1],W[2]);else if(W.length===1)return zW(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function s8(W,$,k){if(o$($)&&g9(k))return i1.create(xW(W),r4($),EW.createImmediate(k));return i1.create(xW(W),r4($),I9(k))}function jW(W,$,k){return i1.create(xW(W),r4($),xW(k))}function e4(W,$){return E0(Object.entries(W).filter(([,k])=>!aW(k)).map(([k,J])=>s8(k,g9(J)?"is":"=",J)),$)}function E0(W,$,k=!0){let J=$==="and"?cW.create:Y1.create;if(W.length===0)return i1.create(EW.createImmediate(1),dW.create("="),EW.createImmediate($==="and"?1:0));let Z=y9(W[0]);for(let X=1;X<W.length;++X)Z=J(Z,y9(W[X]));if(W.length>1&&k)return rW.create(Z);return Z}function o$(W){return W==="is"||W==="is not"}function g9(W){return h0(W)||Y0(W)}function r4(W){if(_W(W)&&C9.includes(W))return dW.create(W);if(LW(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function y9(W){return LW(W)?W.toOperationNode():W}var Q1=H({is(W){return W.kind==="OrderByNode"},create(W){return H({kind:"OrderByNode",items:H([...W])})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var W6=H({is(W){return W.kind==="PartitionByNode"},create(W){return H({kind:"PartitionByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var H8=H({is(W){return W.kind==="OverNode"},create(){return H({kind:"OverNode"})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithPartitionByItems(W,$){return H({...W,partitionBy:W.partitionBy?W6.cloneWithItems(W.partitionBy,$):W6.create($)})}});var H0=H({is(W){return W.kind==="FromNode"},create(W){return H({kind:"FromNode",froms:H(W)})},cloneWithFroms(W,$){return H({...W,froms:H([...W.froms,...$])})}});var $6=H({is(W){return W.kind==="GroupByNode"},create(W){return H({kind:"GroupByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var k6=H({is(W){return W.kind==="HavingNode"},create(W){return H({kind:"HavingNode",having:W})},cloneWithOperation(W,$,k){return H({...W,having:$==="And"?cW.create(W.having,k):Y1.create(W.having,k)})}});var fW=H({is(W){return W.kind==="InsertQueryNode"},create(W,$,k){return H({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:k})},createWithoutInto(){return H({kind:"InsertQueryNode"})},cloneWith(W,$){return H({...W,...$})}});var a8=H({is(W){return W.kind==="ListNode"},create(W){return H({kind:"ListNode",items:H(W)})}});var D1=H({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return H({kind:"UpdateQueryNode",table:W.length===1?W[0]:a8.create(W),...$&&{with:$}})},createWithoutTable(){return H({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return H({...W,from:W.from?H0.cloneWithFroms(W.from,$):H0.create($)})},cloneWithUpdates(W,$){return H({...W,updates:W.updates?H([...W.updates,...$]):$})},cloneWithLimit(W,$){return H({...W,limit:$})}});var z8=H({is(W){return W.kind==="UsingNode"},create(W){return H({kind:"UsingNode",tables:H(W)})},cloneWithTables(W,$){return H({...W,tables:H([...W.tables,...$])})}});var a1=H({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return H({kind:"DeleteQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithUsing(W,$){return H({...W,using:W.using!==void 0?z8.cloneWithTables(W.using,$):z8.create($)})}});var qW=H({is(W){return W.kind==="WhereNode"},create(W){return H({kind:"WhereNode",where:W})},cloneWithOperation(W,$,k){return H({...W,where:$==="And"?cW.create(W.where,k):Y1.create(W.where,k)})}});var J6=H({is(W){return W.kind==="ReturningNode"},create(W){return H({kind:"ReturningNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var m9=H({is(W){return W.kind==="ExplainNode"},create(W,$){return H({kind:"ExplainNode",format:W,options:$})}});var k1=H({is(W){return W.kind==="WhenNode"},create(W){return H({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return H({...W,result:$})}});var eW=H({is(W){return W.kind==="MergeQueryNode"},create(W,$){return H({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return H({...W,using:$})},cloneWithWhen(W,$){return H({...W,whens:W.whens?H([...W.whens,$]):H([$])})},cloneWithThen(W,$){return H({...W,whens:W.whens?H([...W.whens.slice(0,-1),k1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var Z6=H({is(W){return W.kind==="OutputNode"},create(W){return H({kind:"OutputNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var g=H({is(W){return HW.is(W)||fW.is(W)||D1.is(W)||a1.is(W)||eW.is(W)},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWithWhere(W,$){return H({...W,where:W.where?qW.cloneWithOperation(W.where,"And",$):qW.create($)})},cloneWithJoin(W,$){return H({...W,joins:W.joins?H([...W.joins,$]):H([$])})},cloneWithReturning(W,$){return H({...W,returning:W.returning?J6.cloneWithSelections(W.returning,$):J6.create($)})},cloneWithoutReturning(W){return H({...W,returning:void 0})},cloneWithoutWhere(W){return H({...W,where:void 0})},cloneWithExplain(W,$,k){return H({...W,explain:m9.create($,k?.toOperationNode())})},cloneWithTop(W,$){return H({...W,top:$})},cloneWithOutput(W,$){return H({...W,output:W.output?Z6.cloneWithSelections(W.output,$):Z6.create($)})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithoutOrderBy(W){return H({...W,orderBy:void 0})}});var HW=H({is(W){return W.kind==="SelectQueryNode"},create(W){return H({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return H({kind:"SelectQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})},cloneWithDistinctOn(W,$){return H({...W,distinctOn:W.distinctOn?H([...W.distinctOn,...$]):H($)})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return H({...W,groupBy:W.groupBy?$6.cloneWithItems(W.groupBy,$):$6.create($)})},cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithOffset(W,$){return H({...W,offset:$})},cloneWithFetch(W,$){return H({...W,fetch:$})},cloneWithHaving(W,$){return H({...W,having:W.having?k6.cloneWithOperation(W.having,"And",$):k6.create($)})},cloneWithSetOperations(W,$){return H({...W,setOperations:W.setOperations?H([...W.setOperations,...$]):H([...$])})},cloneWithoutSelections(W){return H({...W,selections:[]})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithoutOffset(W){return H({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return H({...W,groupBy:void 0})}});class S0{#W;constructor(W){this.#W=H(W)}on(...W){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,MW(W))})}onRef(W,$,k){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,jW(W,$,k))})}onTrue(){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,YW.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var c9=H({is(W){return W.kind==="PartitionByItemNode"},create(W){return H({kind:"PartitionByItemNode",partitionBy:W})}});function u9(W){return C1(W).map(c9.create)}class N0{#W;constructor(W){this.#W=H(W)}orderBy(...W){return new N0({overNode:H8.cloneWithOrderByItems(this.#W.overNode,oW(W))})}clearOrderBy(){return new N0({overNode:g.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new N0({overNode:H8.cloneWithPartitionByItems(this.#W.overNode,u9(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var O0=H({is(W){return W.kind==="SelectionNode"},create(W){return H({kind:"SelectionNode",selection:W})},createSelectAll(){return H({kind:"SelectionNode",selection:D0.create()})},createSelectAllFromTable(W){return H({kind:"SelectionNode",selection:f0.createSelectAll(W)})}});function NW(W){if(hW(W))return NW(W(G1()));else if(bW(W))return W.map(($)=>l9($));else return[l9(W)]}function l9(W){if(_W(W))return O0.create(B9(W));else if(l8(W))return O0.create(W.toOperationNode());else return O0.create(d8(W))}function CW(W){if(!W)return[O0.createSelectAll()];else if(Array.isArray(W))return W.map(i9);else return[i9(W)]}function i9(W){if(_W(W))return O0.createSelectAllFromTable(kW(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var p9=H({is(W){return W.kind==="ValuesNode"},create(W){return H({kind:"ValuesNode",values:H(W)})}});var t9=H({is(W){return W.kind==="DefaultInsertValueNode"},create(){return H({kind:"DefaultInsertValueNode"})}});function n8(W){let $=hW(W)?W(G1()):W,k=bW($)?$:H([$]);return r$(k)}function r$(W){let $=e$(W);return[H([...$.keys()].map(WW.create)),p9.create(W.map((k)=>Wk(k,$)))]}function e$(W){let $=new Map;for(let k of W){let J=Object.keys(k);for(let Z of J)if(!$.has(Z)&&k[Z]!==void 0)$.set(Z,$.size)}return $}function Wk(W,$){let k=Object.keys(W),J=Array.from({length:$.size}),Z=!1,X=k.length;for(let z of k){let V=$.get(z);if(aW(V)){X--;continue}let w=W[z];if(aW(w)||j1(w))Z=!0;J[V]=w}if(X<$.size||Z){let z=t9.create();return s1.create(J.map((V)=>aW(V)?z:zW(V)))}return p8.create(J)}var X6=H({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return H({kind:"ColumnUpdateNode",column:W,value:$})}});function s9(...W){if(W.length===2)return[X6.create(xW(W[0]),zW(W[1]))];return G8(W[0])}function G8(W){let $=hW(W)?W(G1()):W;return Object.entries($).filter(([k,J])=>J!==void 0).map(([k,J])=>{return X6.create(WW.create(k),zW(J))})}var a9=H({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return H({kind:"OnDuplicateKeyNode",updates:W})}});class Y6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class M1 extends Error{node;constructor(W){super("no result");this.node=W}}function f1(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var gW=H({is(W){return W.kind==="OnConflictNode"},create(){return H({kind:"OnConflictNode"})},cloneWith(W,$){return H({...W,...$})},cloneWithIndexWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"And",$):qW.create($)})},cloneWithIndexOrWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"Or",$):qW.create($)})},cloneWithUpdateWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"And",$):qW.create($)})},cloneWithUpdateOrWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"Or",$):qW.create($)})},cloneWithoutIndexWhere(W){return H({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return H({...W,updateWhere:void 0})}});class T1{#W;constructor(W){this.#W=H(W)}column(W){let $=WW.create(W);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,$]):H([$])})})}columns(W){let $=W.map(WW.create);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,...$]):H($)})})}constraint(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{constraint:i.create(W)})})}expression(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new T1({...this.#W,onConflictNode:gW.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new d9({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new M8({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{updates:G8(W)})})}$call(W){return W(this)}}class d9{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.onConflictNode}}class M8{#W;constructor(W){this.#W=H(W)}where(...W){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new M8({...this.#W,onConflictNode:gW.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var n9=H({is(W){return W.kind==="TopNode"},create(W,$){return H({kind:"TopNode",expression:W,modifiers:$})}});function L1(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid top expression: ${W}`);if(!aW($)&&!$k($))throw Error(`Invalid top modifiers: ${$}`);return n9.create(W,$)}function $k(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var z0=H({is(W){return W.kind==="OrActionNode"},create(W){return H({kind:"OrActionNode",action:W})}});class GW{#W;constructor(W){this.#W=H(W)}values(W){let[$,k]=n8(W);return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:$,values:k})})}columns(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:H(W.map(WW.create))})})}expression(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{values:uW(W)})})}defaultValues(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new GW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orIgnore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orAbort(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("abort")})})}orFail(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("fail")})})}orReplace(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("replace")})})}orRollback(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("rollback")})})}top(W,$){return new GW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}onConflict(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onConflict:W(new T1({onConflictNode:gW.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onDuplicateKey:a9.create(G8(W))})})}returning(W){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW())})}output(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new GW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new GW({...this.#W})}$castTo(){return new GW(this.#W)}$narrowType(){return new GW(this.#W)}$assertType(){return new GW(this.#W)}withPlugin(W){return new GW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new Y6($.insertId,$.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new GW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class H6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var A0=H({is(W){return W.kind==="LimitNode"},create(W){return H({kind:"LimitNode",limit:W})}});class PW{#W;constructor(W){this.#W=H(W)}where(...W){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new PW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new PW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(W){return new PW({...this.#W,queryNode:a1.cloneWithUsing(this.#W.queryNode,K1(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 PW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}returning(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new PW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new PW({...this.#W,queryNode:a1.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new PW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new PW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new PW({...this.#W,queryNode:a1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}modifyEnd(W){return new PW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new PW({...this.#W})}$castTo(){return new PW(this.#W)}$narrowType(){return new PW(this.#W)}$assertType(){return new PW(this.#W)}withPlugin(W){return new PW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new H6($.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new PW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class z6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}class KW{#W;constructor(W){this.#W=H(W)}where(...W){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new KW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new KW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}from(W){return new KW({...this.#W,queryNode:D1.cloneWithFromItems(this.#W.queryNode,K1(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 KW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new KW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new KW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new KW({...this.#W,queryNode:D1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}set(...W){return new KW({...this.#W,queryNode:D1.cloneWithUpdates(this.#W.queryNode,s9(...W))})}returning(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}modifyEnd(W){return new KW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new KW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new KW({...this.#W})}$castTo(){return new KW(this.#W)}$narrowType(){return new KW(this.#W)}$assertType(){return new KW(this.#W)}withPlugin(W){return new KW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new z6($.numAffectedRows??BigInt(0),$.numChangedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new KW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}var G6=H({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return H({kind:"CommonTableExpressionNameNode",table:mW.create(W),columns:$?H($.map(WW.create)):void 0})}});var j0=H({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return H({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return H({...W,...$})}});class L8{#W;constructor(W){this.#W=H(W)}materialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function M6(W,$){let k=$(r9()).toOperationNode();if(hW(W))return W(kk(k)).toOperationNode();return j0.create(o9(W),k)}function kk(W){return($)=>{return new L8({node:j0.create(o9($),W)})}}function o9(W){if(W.includes("(")){let $=W.split(/[\(\)]/),k=$[0],J=$[1].split(",").map((Z)=>Z.trim());return G6.create(k,J)}else return G6.create(W)}var K8=H({is(W){return W.kind==="WithNode"},create(W,$){return H({kind:"WithNode",expressions:H([W]),...$})},cloneWithExpression(W,$){return H({...W,expressions:H([...W.expressions,$])})}});var e9=["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 W5(W){let $="";for(let k=0;k<W;++k)$+=Jk();return $}function Jk(){return e9[~~(Math.random()*e9.length)]}function e(){return new $5}class $5{#W;get queryId(){if(this.#W===void 0)this.#W=W5(8);return this.#W}}function I(W){return W}class U8{nodeStack=[];#W=H({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)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let k=this.transformNodeImpl(W,$);return this.nodeStack.pop(),H(k)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return H(W.map((k)=>this.transformNode(k,$)))}transformSelectQuery(W,$){return I({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 I({kind:"SelectionNode",selection:this.transformNode(W.selection,$)})}transformColumn(W,$){return I({kind:"ColumnNode",column:this.transformNode(W.column,$)})}transformAlias(W,$){return I({kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)})}transformTable(W,$){return I({kind:"TableNode",table:this.transformNode(W.table,$)})}transformFrom(W,$){return I({kind:"FromNode",froms:this.transformNodeList(W.froms,$)})}transformReference(W,$){return I({kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)})}transformAnd(W,$){return I({kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformOr(W,$){return I({kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformValueList(W,$){return I({kind:"ValueListNode",values:this.transformNodeList(W.values,$)})}transformParens(W,$){return I({kind:"ParensNode",node:this.transformNode(W.node,$)})}transformJoin(W,$){return I({kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)})}transformRaw(W,$){return I({kind:"RawNode",sqlFragments:H([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)})}transformWhere(W,$){return I({kind:"WhereNode",where:this.transformNode(W.where,$)})}transformInsertQuery(W,$){return I({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,$),ignore:W.ignore,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 I({kind:"ValuesNode",values:this.transformNodeList(W.values,$)})}transformDeleteQuery(W,$){return I({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 I({kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)})}transformCreateTable(W,$){return I({kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),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 I({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 I({kind:"AddColumnNode",column:this.transformNode(W.column,$)})}transformDropTable(W,$){return I({kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformOrderBy(W,$){return I({kind:"OrderByNode",items:this.transformNodeList(W.items,$)})}transformOrderByItem(W,$){return I({kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls})}transformGroupBy(W,$){return I({kind:"GroupByNode",items:this.transformNodeList(W.items,$)})}transformGroupByItem(W,$){return I({kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)})}transformUpdateQuery(W,$){return I({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 I({kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)})}transformLimit(W,$){return I({kind:"LimitNode",limit:this.transformNode(W.limit,$)})}transformOffset(W,$){return I({kind:"OffsetNode",offset:this.transformNode(W.offset,$)})}transformOnConflict(W,$){return I({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 I({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)})}transformCreateIndex(W,$){return I({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 I({kind:"ListNode",items:this.transformNodeList(W.items,$)})}transformDropIndex(W,$){return I({kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformPrimaryKeyConstraint(W,$){return I({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformUniqueConstraint(W,$){return I({kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformForeignKeyConstraint(W,$){return I({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 I({kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all})}transformReferences(W,$){return I({kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate})}transformCheckConstraint(W,$){return I({kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)})}transformWith(W,$){return I({kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive})}transformCommonTableExpression(W,$){return I({kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)})}transformCommonTableExpressionName(W,$){return I({kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)})}transformHaving(W,$){return I({kind:"HavingNode",having:this.transformNode(W.having,$)})}transformCreateSchema(W,$){return I({kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists})}transformDropSchema(W,$){return I({kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade})}transformAlterTable(W,$){return I({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 I({kind:"DropColumnNode",column:this.transformNode(W.column,$)})}transformRenameColumn(W,$){return I({kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)})}transformAlterColumn(W,$){return I({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 I({kind:"ModifyColumnNode",column:this.transformNode(W.column,$)})}transformAddConstraint(W,$){return I({kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)})}transformDropConstraint(W,$){return I({kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier})}transformRenameConstraint(W,$){return I({kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)})}transformCreateView(W,$){return I({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 I({kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData})}transformDropView(W,$){return I({kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade})}transformGenerated(W,$){return I({kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)})}transformDefaultValue(W,$){return I({kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)})}transformOn(W,$){return I({kind:"OnNode",on:this.transformNode(W.on,$)})}transformSelectModifier(W,$){return I({kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)})}transformCreateType(W,$){return I({kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)})}transformDropType(W,$){return I({kind:"DropTypeNode",name:this.transformNode(W.name,$),ifExists:W.ifExists})}transformExplain(W,$){return I({kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)})}transformSchemableIdentifier(W,$){return I({kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)})}transformAggregateFunction(W,$){return I({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 I({kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)})}transformPartitionBy(W,$){return I({kind:"PartitionByNode",items:this.transformNodeList(W.items,$)})}transformPartitionByItem(W,$){return I({kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)})}transformBinaryOperation(W,$){return I({kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)})}transformUnaryOperation(W,$){return I({kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)})}transformUsing(W,$){return I({kind:"UsingNode",tables:this.transformNodeList(W.tables,$)})}transformFunction(W,$){return I({kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)})}transformCase(W,$){return I({kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement})}transformWhen(W,$){return I({kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)})}transformJSONReference(W,$){return I({kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)})}transformJSONPath(W,$){return I({kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)})}transformJSONPathLeg(W,$){return I({kind:"JSONPathLegNode",type:W.type,value:W.value})}transformJSONOperatorChain(W,$){return I({kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)})}transformTuple(W,$){return I({kind:"TupleNode",values:this.transformNodeList(W.values,$)})}transformMergeQuery(W,$){return I({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 I({kind:"MatchedNode",not:W.not,bySource:W.bySource})}transformAddIndex(W,$){return I({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 I({kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)})}transformFetch(W,$){return I({kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier})}transformTop(W,$){return I({kind:"TopNode",expression:W.expression,modifiers:W.modifiers})}transformOutput(W,$){return I({kind:"OutputNode",selections:this.transformNodeList(W.selections,$)})}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}}var Zk=H({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),Xk={json_agg:!0,to_json:!0};class L6 extends U8{#W;#$=new Set;#k=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!this.#Z(W))return super.transformNodeImpl(W,$);let k=this.#X(W);for(let X of k)this.#k.add(X);let J=this.#z(W);for(let X of J)this.#$.add(X);let Z=super.transformNodeImpl(W,$);for(let X of J)this.#$.delete(X);for(let X of k)this.#k.delete(X);return Z}transformSchemableIdentifier(W,$){let k=super.transformSchemableIdentifier(W,$);if(k.schema||!this.#$.has(W.identifier.name))return k;return{...k,schema:i.create(this.#W)}}transformReferences(W,$){let k=super.transformReferences(W,$);if(k.table.table.schema)return k;return{...k,table:mW.createWithSchema(this.#W,k.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#J(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#J(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((k)=>mW.is(k)&&!k.table.schema?{...k,table:this.transformIdentifier(k.table.identifier,$)}:this.transformNode(k,$))}}#J(W,$,k){return Xk[W.func]?W[k].map((J)=>!mW.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[k],$)}#Z(W){return W.kind in Zk}#z(W){let $=new Set;if("name"in W&&W.name&&IW.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let k of W.from.froms)this.#Y(k,$);if("into"in W&&W.into)this.#Y(W.into,$);if("table"in W&&W.table)this.#Y(W.table,$);if("joins"in W&&W.joins)for(let k of W.joins)this.#Y(k.table,$);if("using"in W&&W.using)if(H1.is(W.using))this.#Y(W.using.table,$);else this.#Y(W.using,$);return $}#X(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#Y(W,$){if(mW.is(W))return this.#H(W.table,$);if(AW.is(W)&&mW.is(W.node))return this.#H(W.node.table,$);if(a8.is(W)){for(let k of W.items)this.#Y(k,$);return}if(z8.is(W)){for(let k of W.tables)this.#Y(k,$);return}}#H(W,$){let k=W.identifier.name;if(!this.#$.has(k)&&!this.#k.has(k))$.add(k)}#G(W,$){for(let k of W.expressions){let J=k.name.table.table.identifier.name;if(!this.#k.has(J))$.add(J)}}}class W1{#W;constructor(W){this.#W=new L6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var k5=H({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return H({kind:"MatchedNode",not:W,bySource:$})}});function K6(W,$,k){return k1.create(E0([k5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&k?jW($[0],$[1],$[2]):MW($)]:[]],"and",!1))}function C0(W){if(_W(W))return YW.create([W],[]);if(LW(W))return W.toOperationNode();return W}class o8{#W;#$;#k;constructor(){this.#W=new Promise((W,$)=>{this.#k=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{if(this.#$)this.#$(W)};reject=(W)=>{if(this.#k)this.#k(W)}}async function r8(W){let $=new o8,k=new o8;return W.provideConnection(async(J)=>{return $.resolve(J),await k.promise}).catch((J)=>$.reject(J)),H({connection:await $.promise,release:k.resolve})}var Yk=H([]);class V8{#W;constructor(W=Yk){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let k of this.#W){let J=k.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){return await this.provideConnection(async($)=>{let k=await $.executeQuery(W);if("numUpdatedOrDeletedRows"in k)P1("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#$(k,W.queryId)})}async*stream(W,$){let{connection:k,release:J}=await r8(this);try{for await(let Z of k.streamQuery(W,$))yield await this.#$(Z,W.queryId)}finally{J()}}async#$(W,$){for(let k of this.#W)W=await k.transformResult({result:W,queryId:$});return W}}class Q0 extends V8{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 Q0([...this.plugins,W])}withPlugins(W){return new Q0([...this.plugins,...W])}withPluginAtFront(W){return new Q0([W,...this.plugins])}withoutPlugins(){return new Q0([])}}var n1=new Q0;class U6{numChangedRows;constructor(W){this.numChangedRows=W}}class x1{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new x1({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new x1({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(...W){return new lW({...this.#W,queryNode:eW.cloneWithUsing(this.#W.queryNode,d1("Using",W))})}returning(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}}class lW{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new lW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new lW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,k){return this.#$([W,$,k],!0)}#$(W,$){return new V6({...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!0},W,$))})}whenNotMatched(){return this.#k([])}whenNotMatchedAnd(...W){return this.#k(W)}whenNotMatchedAndRef(W,$,k){return this.#k([W,$,k],!0)}whenNotMatchedBySource(){return this.#k([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#k(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,k){return this.#k([W,$,k],!0,!0)}returning(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}#k(W,$=!1,k=!1){let J={...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!1,bySource:k},W,$))};return new(k?V6:J5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new lW({...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(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new U6($.numAffectedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}}class V6{#W;constructor(W){this.#W=H(W)}thenDelete(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("delete"))})}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenUpdate(W){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(W(new KW({queryId:this.#W.queryId,executor:n1,queryNode:D1.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class J5{#W;constructor(W){this.#W=H(W)}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenInsertValues(W){let[$,k]=n8(W);return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(fW.cloneWith(fW.createWithoutInto(),{columns:$,values:k})))})}}class v1{#W;constructor(W){this.#W=H(W)}selectFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.createFrom(K1(W),this.#W.withNode)})}selectNoFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.cloneWithSelections(HW.create(this.#W.withNode),NW(W))})}insertInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode)})}replaceInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode,!0)})}deleteFrom(W){return new PW({queryId:e(),executor:this.#W.executor,queryNode:a1.create(K1(W),this.#W.withNode)})}updateTable(W){return new KW({queryId:e(),executor:this.#W.executor,queryNode:D1.create(K1(W),this.#W.withNode)})}mergeInto(W){return new x1({queryId:e(),executor:this.#W.executor,queryNode:eW.create(R6(W),this.#W.withNode)})}with(W,$){let k=M6(W,$);return new v1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k)})}withRecursive(W,$){let k=M6(W,$);return new v1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k,{recursive:!0})})}withPlugin(W){return new v1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new v1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new v1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}}function r9(){return new v1({executor:n1})}function Z5(W,$){return new S0({joinNode:H1.create(W,G0($))})}function X5(){return new N0({overNode:H8.create()})}function d1(W,$){if($.length===3)return zk(W,$[0],$[1],$[2]);else if($.length===2)return Hk(W,$[0],$[1]);else if($.length===1)return Gk(W,$[0]);else throw Error("not implemented")}function Hk(W,$,k){return k(Z5(W,$)).toOperationNode()}function zk(W,$,k,J){return H1.createWithOn(W,G0($),jW(k,"=",J))}function Gk(W,$){return H1.create(W,G0($))}var Y5=H({is(W){return W.kind==="OffsetNode"},create(W){return H({kind:"OffsetNode",offset:W})}});var H5=H({is(W){return W.kind==="GroupByItemNode"},create(W){return H({kind:"GroupByItemNode",groupBy:W})}});function z5(W){return W=hW(W)?W(G1()):W,C1(W).map(H5.create)}var e8=H({is(W){return W.kind==="SetOperationNode"},create(W,$,k){return H({kind:"SetOperationNode",operator:W,expression:$,all:k})}});function M0(W,$,k){if(hW($))$=$(W4());if(!bW($))$=[$];return $.map((J)=>e8.create(W,uW(J),k))}class ZW{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new ZW(this.#W)}$notNull(){return new ZW(this.#W)}toOperationNode(){return this.#W}}class J4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}class $4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}$castTo(){return new $4(this.#W)}toOperationNode(){return rW.create(this.#W)}}class k4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new k4(this.#W)}toOperationNode(){return rW.create(this.#W)}}var G5=H({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:EW.create(W),modifier:$}}});function M5(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid fetch row count: ${W}`);if(!Mk($))throw Error(`Invalid fetch modifier: ${$}`);return G5.create(W,$)}function Mk(W){return W==="only"||W==="with ties"}class d{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}having(...W){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,MW(W))})}havingRef(W,$,k){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,jW(W,$,k))})}select(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,NW(W))})}distinctOn(W){return new d({...this.#W,queryNode:HW.cloneWithDistinctOn(this.#W.queryNode,C1(W))})}modifyFront(W){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}distinct(){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.create("Distinct"))})}forUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForUpdate",W?J8(W).map(kW):void 0))})}forShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForShare",W?J8(W).map(kW):void 0))})}forKeyShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForKeyShare",W?J8(W).map(kW):void 0))})}forNoKeyUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForNoKeyUpdate",W?J8(W).map(kW):void 0))})}skipLocked(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("SkipLocked"))})}noWait(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("NoWait"))})}selectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,CW(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 d({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new d({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}groupBy(W){return new d({...this.#W,queryNode:HW.cloneWithGroupByItems(this.#W.queryNode,z5(W))})}limit(W){return new d({...this.#W,queryNode:HW.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}offset(W){return new d({...this.#W,queryNode:HW.cloneWithOffset(this.#W.queryNode,Y5.create(zW(W)))})}fetch(W,$="only"){return new d({...this.#W,queryNode:HW.cloneWithFetch(this.#W.queryNode,M5(W,$))})}top(W,$){return new d({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}union(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!1))})}unionAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!0))})}intersect(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!1))})}intersectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!0))})}except(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!1))})}exceptAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!0))})}as(W){return new L5(this,W)}clearSelect(){return new d({...this.#W,queryNode:HW.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new d({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new d({...this.#W,queryNode:HW.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new d({...this.#W,queryNode:HW.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new d({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new d({...this.#W,queryNode:HW.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new d({...this.#W})}$castTo(){return new d(this.#W)}$narrowType(){return new d(this.#W)}$assertType(){return new d(this.#W)}$asTuple(){return new ZW(this.toOperationNode())}$asScalar(){return new ZW(this.toOperationNode())}withPlugin(W){return new d({...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(){let W=this.compile();return(await this.#W.executor.executeQuery(W)).rows}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new d({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}function x0(W){return new d(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 AW.create(this.#W.toOperationNode(),i.create(this.#$))}}var E1=H({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return H({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return H({...W,distinct:!0})},cloneWithOrderBy(W,$,k=!1){let J=k?"withinGroup":"orderBy";return H({...W,[J]:W[J]?Q1.cloneWithItems(W[J],$):Q1.create($)})},cloneWithFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"And",$):qW.create($)})},cloneWithOrFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"Or",$):qW.create($)})},cloneWithOver(W,$){return H({...W,over:$})}});var F6=H({is(W){return W.kind==="FunctionNode"},create(W,$){return H({kind:"FunctionNode",func:W,arguments:$})}});class iW{#W;constructor(W){this.#W=H(W)}get expressionType(){return}as(W){return new K5(this,W)}distinct(){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithOrderByItems(this.#W.aggregateFunctionNode,oW(W))})}clearOrderBy(){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithOrderBy(this.#W.aggregateFunctionNode,oW(W),!0)})}filterWhere(...W){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithFilter(this.#W.aggregateFunctionNode,MW(W))})}filterWhereRef(W,$,k){return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithFilter(this.#W.aggregateFunctionNode,jW(W,$,k))})}over(W){let $=X5();return new iW({...this.#W,aggregateFunctionNode:E1.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new iW(this.#W)}$notNull(){return new iW(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class K5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),i.create(this.#$))}}function Z4(){let W=(k,J)=>{return new ZW(F6.create(k,C1(J??[])))},$=(k,J)=>{return new iW({aggregateFunctionNode:E1.create(k,J?C1(J):void 0)})};return Object.assign(W,{agg:$,avg(k){return $("avg",[k])},coalesce(...k){return W("coalesce",k)},count(k){return $("count",[k])},countAll(k){return new iW({aggregateFunctionNode:E1.create("count",CW(k))})},max(k){return $("max",[k])},min(k){return $("min",[k])},sum(k){return $("sum",[k])},any(k){return W("any",[k])},jsonAgg(k){return new iW({aggregateFunctionNode:E1.create("json_agg",[_W(k)?kW(k):k.toOperationNode()])})},toJson(k){return new ZW(F6.create("to_json",[_W(k)?kW(k):k.toOperationNode()]))}})}var U5=H({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return H({kind:"UnaryOperationNode",operator:W,operand:$})}});function V5(W,$){return U5.create(dW.create(W),xW($))}var $1=H({is(W){return W.kind==="CaseNode"},create(W){return H({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return H({...W,when:H(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return H({...W,when:W.when?H([...W.when.slice(0,-1),k1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return H({...W,...$})}});class R8{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}}class w6{#W;constructor(W){this.#W=H(W)}then(W){return new R5({...this.#W,node:$1.cloneWithThen(this.#W.node,t8(W)?Y8(W):zW(W))})}}class R5{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}else(W){return new F5({...this.#W,node:$1.cloneWith(this.#W.node,{else:t8(W)?Y8(W):zW(W)})})}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}class F5{#W;constructor(W){this.#W=H(W)}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}var _6=H({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return H({kind:"JSONPathLegNode",type:W,value:$})}});class w8{#W;constructor(W){this.#W=W}at(W){return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(T0.is(this.#W))return new F8(T0.cloneWithTraversal(this.#W,t1.is(this.#W.traversal)?t1.cloneWithLeg(this.#W.traversal,_6.create(W,$)):i8.cloneWithValue(this.#W.traversal,EW.createImmediate($))));return new F8(t1.cloneWithLeg(this.#W,_6.create(W,$)))}}class F8 extends w8{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new w5(this,W)}$castTo(){return new F8(this.#W)}$notNull(){return new F8(this.#W)}toOperationNode(){return this.#W}}class w5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var h6=H({is(W){return W.kind==="TupleNode"},create(W){return H({kind:"TupleNode",values:H(W)})}});var Lk=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],Kk=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],_5=H({is(W){return W.kind==="DataTypeNode"},create(W){return H({kind:"DataTypeNode",dataType:W})}});function h5(W){if(Lk.includes(W))return!0;if(Kk.some(($)=>$.test(W)))return!0;return!1}function U1(W){if(LW(W))return W.toOperationNode();if(h5(W))return _5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var P5=H({is(W){return W.kind==="CastNode"},create(W,$){return H({kind:"CastNode",expression:W,dataType:$})}});function W4(W=n1){function $(Z,X,G){return new ZW(s8(Z,X,G))}function k(Z,X){return new ZW(V5(Z,X))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(Z){return x0({queryId:e(),executor:W,queryNode:HW.createFrom(K1(Z))})},case(Z){return new R8({node:$1.create(aW(Z)?void 0:xW(Z))})},ref(Z,X){if(aW(X))return new ZW(nW(Z));return new w8(b9(Z,X))},jsonPath(){return new w8(t1.create())},table(Z){return new ZW(kW(Z))},val(Z){return new ZW(zW(Z))},refTuple(...Z){return new ZW(h6.create(Z.map(xW)))},tuple(...Z){return new ZW(h6.create(Z.map(zW)))},lit(Z){return new ZW(Y8(Z))},unary:k,not(Z){return k("not",Z)},exists(Z){return k("exists",Z)},neg(Z){return k("-",Z)},between(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between"),cW.create(zW(X),zW(G))))},betweenSymmetric(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between symmetric"),cW.create(zW(X),zW(G))))},and(Z){if(bW(Z))return new ZW(E0(Z,"and"));return new ZW(e4(Z,"and"))},or(Z){if(bW(Z))return new ZW(E0(Z,"or"));return new ZW(e4(Z,"or"))},parens(...Z){let X=MW(Z);if(rW.is(X))return new ZW(X);else return new ZW(rW.create(X))},cast(Z,X){return new ZW(P5.create(xW(Z),U1(X)))},withSchema(Z){return W4(W.withPluginAtFront(new W1(Z)))}});return J.fn=Z4(),J.eb=J,J}function G1(W){return W4()}function uW(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function d8(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function j1(W){return c8(W)||A9(W)||hW(W)}class P6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new D5(this.#W,W)}}class D5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return AW.create(kW(this.#W),i.create(this.#$))}}function f5(W){return TW(W)&&LW(W)&&_W(W.table)&&_W(W.alias)}function K1(W){if(bW(W))return W.map(($)=>G0($));else return[G0(W)]}function G0(W){if(_W(W))return R6(W);else if(f5(W))return W.toOperationNode();else return d8(W)}function R6(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(T5);return AW.create(kW(k),i.create(J))}else return kW(W)}function kW(W){if(W.includes(".")){let[k,J]=W.split(".").map(T5);return mW.createWithSchema(k,J)}else return mW.create(W)}function T5(W){return W.trim()}var D6=H({is(W){return W.kind==="AddColumnNode"},create(W){return H({kind:"AddColumnNode",column:W})}});var UW=H({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return H({kind:"ColumnDefinitionNode",column:WW.create(W),dataType:$})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):[$]})},cloneWith(W,$){return H({...W,...$})}});var f6=H({is(W){return W.kind==="DropColumnNode"},create(W){return H({kind:"DropColumnNode",column:WW.create(W)})}});var T6=H({is(W){return W.kind==="RenameColumnNode"},create(W,$){return H({kind:"RenameColumnNode",column:WW.create(W),renameTo:WW.create($)})}});var q0=H({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return H({kind:"CheckConstraintNode",expression:W,name:$?i.create($):void 0})}});var v5=["no action","restrict","cascade","set null","set default"],b0=H({is(W){return W.kind==="ReferencesNode"},create(W,$){return H({kind:"ReferencesNode",table:W,columns:H([...$])})},cloneWithOnDelete(W,$){return H({...W,onDelete:$})},cloneWithOnUpdate(W,$){return H({...W,onUpdate:$})}});function X4(W){return LW(W)?W.toOperationNode():EW.createImmediate(W)}var _8=H({is(W){return W.kind==="GeneratedNode"},create(W){return H({kind:"GeneratedNode",...W})},createWithExpression(W){return H({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return H({...W,...$})}});var E5=H({is(W){return W.kind==="DefaultValueNode"},create(W){return H({kind:"DefaultValueNode",defaultValue:W})}});function B0(W){if(v5.includes(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class VW{#W;constructor(W){this.#W=W}autoIncrement(){return new VW(UW.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new VW(UW.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new VW(UW.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=nW(W);if(!$.table||D0.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new VW(UW.cloneWith(this.#W,{references:b0.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnDelete(this.#W.references,B0(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnUpdate(this.#W.references,B0(W))}))}unique(){return new VW(UW.cloneWith(this.#W,{unique:!0}))}notNull(){return new VW(UW.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new VW(UW.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new VW(UW.cloneWith(this.#W,{defaultTo:E5.create(X4(W))}))}check(W){return new VW(UW.cloneWith(this.#W,{check:q0.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new VW(UW.cloneWith(this.#W,{generated:_8.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new VW(UW.cloneWith(this.#W,{generated:_8.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new VW(UW.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new VW(UW.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new VW(UW.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new VW(UW.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var v6=H({is(W){return W.kind==="ModifyColumnNode"},create(W){return H({kind:"ModifyColumnNode",column:W})}});var V1=H({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,k,J){return H({kind:"ForeignKeyConstraintNode",columns:W,references:b0.create($,k),name:J?i.create(J):void 0})},cloneWith(W,$){return H({...W,...$})}});class R1{#W;constructor(W){this.#W=W}onDelete(W){return new R1(V1.cloneWith(this.#W,{onDelete:B0(W)}))}onUpdate(W){return new R1(V1.cloneWith(this.#W,{onUpdate:B0(W)}))}deferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var I0=H({is(W){return W.kind==="AddConstraintNode"},create(W){return H({kind:"AddConstraintNode",constraint:W})}});var S1=H({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,k){return H({kind:"UniqueConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0,nullsNotDistinct:k})},cloneWith(W,$){return H({...W,...$})}});var y0=H({is(W){return W.kind==="DropConstraintNode"},create(W){return H({kind:"DropConstraintNode",constraintName:i.create(W)})},cloneWith(W,$){return H({...W,...$})}});var g0=H({is(W){return W.kind==="AlterColumnNode"},create(W,$,k){return H({kind:"AlterColumnNode",column:WW.create(W),[$]:k})}});class Y4{#W;constructor(W){this.#W=W}setDataType(W){return new m0(g0.create(this.#W,"dataType",U1(W)))}setDefault(W){return new m0(g0.create(this.#W,"setDefault",X4(W)))}dropDefault(){return new m0(g0.create(this.#W,"dropDefault",!0))}setNotNull(){return new m0(g0.create(this.#W,"setNotNull",!0))}dropNotNull(){return new m0(g0.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class m0{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class o1{#W;constructor(W){this.#W=H(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(){await this.#W.executor.executeQuery(this.compile())}}class q1{#W;constructor(W){this.#W=H(W)}onDelete(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class L0{#W;constructor(W){this.#W=H(W)}ifExists(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.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(){await this.#W.executor.executeQuery(this.compile())}}var b1=H({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return H({kind:"PrimaryKeyConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0})},cloneWith(W,$){return H({...W,...$})}});var r1=H({is(W){return W.kind==="AddIndexNode"},create(W){return H({kind:"AddIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});class e1{#W;constructor(W){this.#W=H(W)}unique(){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[v0(W)])})})}columns(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,W.map(v0))})})}expression(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{using:YW.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(){await this.#W.executor.executeQuery(this.compile())}}class N1{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N1(S1.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class B1{#W;constructor(W){this.#W=W}deferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class h8{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var S5=H({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return H({kind:"RenameConstraintNode",oldName:i.create(W),newName:i.create($)})}});class E6{#W;constructor(W){this.#W=H(W)}renameTo(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameTo:kW(W)})})}setSchema(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{setSchema:i.create(W)})})}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,v6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new q1({...this.#W,constraintBuilder:X})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}dropConstraint(W){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.create(W)})})}renameConstraint(W,$){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameConstraint:S5.create(W,$)})})}addIndex(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.create(W)})})}dropIndex(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropIndex:l1.create(W)})})}$call(W){return W(this)}}class F1{#W;constructor(W){this.#W=H(W)}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,v6.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(){await this.#W.executor.executeQuery(this.compile())}}class P8 extends U8{transformPrimitiveValueList(W){return s1.create(W.values.map(EW.createImmediate))}transformValue(W){return EW.createImmediate(W.value)}}class J1{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{table:kW(W)})})}column(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[v0(W)])})}columns(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,W.map(v0))})}expression(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{using:YW.createWithSql(W)})})}where(...W){let $=new P8;return new J1({...this.#W,node:g.cloneWithWhere(this.#W.node,$.transformNode(MW(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(){await this.#W.executor.executeQuery(this.compile())}}class H4{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new H4({...this.#W,node:m8.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(){await this.#W.executor.executeQuery(this.compile())}}function N5(W){if(O9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class pW{#W;constructor(W){this.#W=H(W)}temporary(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{onCommit:N5(W)})})}ifNotExists(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new pW({...this.#W,node:BW.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,X.toOperationNode())})}modifyFront(W){return new pW({...this.#W,node:BW.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new pW({...this.#W,node:BW.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{selectQuery:uW(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(){await this.#W.executor.executeQuery(this.compile())}}class c0{#W;constructor(W){this.#W=H(W)}on(W){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{table:kW(W)})})}ifExists(){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new c0({...this.#W,node:l1.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(){await this.#W.executor.executeQuery(this.compile())}}class D8{#W;constructor(W){this.#W=H(W)}ifExists(){return new D8({...this.#W,node:Z8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new D8({...this.#W,node:Z8.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(){await this.#W.executor.executeQuery(this.compile())}}class f8{#W;constructor(W){this.#W=H(W)}ifExists(){return new f8({...this.#W,node:X8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new f8({...this.#W,node:X8.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(){await this.#W.executor.executeQuery(this.compile())}}var w1=H({is(W){return W.kind==="CreateViewNode"},create(W){return H({kind:"CreateViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class S6{#W=new P8;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class I1{#W;constructor(W){this.#W=H(W)}temporary(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{columns:W.map(n4)})})}as(W){let $=W.withPlugin(new S6).toOperationNode();return new I1({...this.#W,node:w1.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(){await this.#W.executor.executeQuery(this.compile())}}var u0=H({is(W){return W.kind==="DropViewNode"},create(W){return H({kind:"DropViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class l0{#W;constructor(W){this.#W=H(W)}materialized(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new l0({...this.#W,node:u0.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(){await this.#W.executor.executeQuery(this.compile())}}var z4=H({is(W){return W.kind==="CreateTypeNode"},create(W){return H({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return H({...W,enum:s1.create($.map(EW.createImmediate))})}});class G4{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new G4({...this.#W,node:z4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var M4=H({is(W){return W.kind==="DropTypeNode"},create(W){return H({kind:"DropTypeNode",name:W})},cloneWith(W,$){return H({...W,...$})}});class L4{#W;constructor(W){this.#W=H(W)}ifExists(){return new L4({...this.#W,node:M4.cloneWith(this.#W.node,{ifExists:!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(){await this.#W.executor.executeQuery(this.compile())}}function N6(W){if(W.includes(".")){let k=W.split(".").map(Uk);if(k.length===2)return IW.createWithSchema(k[0],k[1]);else throw Error(`invalid schemable identifier ${W}`)}else return IW.create(W)}function Uk(W){return W.trim()}var i0=H({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return H({kind:"RefreshMaterializedViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class p0{#W;constructor(W){this.#W=H(W)}concurrently(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new p0({...this.#W,node:i0.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(){await this.#W.executor.executeQuery(this.compile())}}class t0{#W;constructor(W){this.#W=W}createTable(W){return new pW({queryId:e(),executor:this.#W,node:BW.create(kW(W))})}dropTable(W){return new f8({queryId:e(),executor:this.#W,node:X8.create(kW(W))})}createIndex(W){return new J1({queryId:e(),executor:this.#W,node:X1.create(W)})}dropIndex(W){return new c0({queryId:e(),executor:this.#W,node:l1.create(W)})}createSchema(W){return new H4({queryId:e(),executor:this.#W,node:m8.create(W)})}dropSchema(W){return new D8({queryId:e(),executor:this.#W,node:Z8.create(W)})}alterTable(W){return new E6({queryId:e(),executor:this.#W,node:$W.create(kW(W))})}createView(W){return new I1({queryId:e(),executor:this.#W,node:w1.create(W)})}refreshMaterializedView(W){return new p0({queryId:e(),executor:this.#W,node:i0.create(W)})}dropView(W){return new l0({queryId:e(),executor:this.#W,node:u0.create(W)})}createType(W){return new G4({queryId:e(),executor:this.#W,node:z4.create(N6(W))})}dropType(W){return new L4({queryId:e(),executor:this.#W,node:M4.create(N6(W))})}withPlugin(W){return new t0(this.#W.withPlugin(W))}withoutPlugins(){return new t0(this.#W.withoutPlugins())}withSchema(W){return new t0(this.#W.withPluginAtFront(new W1(W)))}}class O6{ref(W){return new t4(W)}table(W){return new P6(W)}}class A6{#W;constructor(W){this.#W=W}async provideConnection(W){let $=await this.#W.acquireConnection();try{return await W($)}finally{await this.#W.releaseConnection($)}}}class W0 extends V8{#W;#$;#k;constructor(W,$,k,J=[]){super(J);this.#W=W,this.#$=$,this.#k=k}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W){return this.#k.provideConnection(W)}withPlugins(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,...W])}withPlugin(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,W])}withPluginAtFront(W){return new W0(this.#W,this.#$,this.#k,[W,...this.plugins])}withConnectionProvider(W){return new W0(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new W0(this.#W,this.#$,this.#k,[])}}function K4(){if(typeof performance<"u"&&hW(performance.now))return performance.now();else return Date.now()}class j6{#W;#$;#k;#J;#Z;#z=new WeakSet;constructor(W,$){this.#J=!1,this.#W=W,this.#$=$}async init(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#k)this.#k=this.#W.init().then(()=>{this.#J=!0}).catch((W)=>{return this.#k=void 0,Promise.reject(W)});await this.#k}async acquireConnection(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#J)await this.init();let W=await this.#W.acquireConnection();if(!this.#z.has(W)){if(this.#X())this.#Y(W);this.#z.add(W)}return W}async releaseConnection(W){await this.#W.releaseConnection(W)}beginTransaction(W,$){return this.#W.beginTransaction(W,$)}commitTransaction(W){return this.#W.commitTransaction(W)}rollbackTransaction(W){return this.#W.rollbackTransaction(W)}savepoint(W,$,k){if(this.#W.savepoint)return this.#W.savepoint(W,$,k);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(W,$,k){if(this.#W.rollbackToSavepoint)return this.#W.rollbackToSavepoint(W,$,k);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(W,$,k){if(this.#W.releaseSavepoint)return this.#W.releaseSavepoint(W,$,k);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#k)return;if(await this.#k,!this.#Z)this.#Z=this.#W.destroy().catch((W)=>{return this.#Z=void 0,Promise.reject(W)});await this.#Z}#X(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#Y(W){let{executeQuery:$,streamQuery:k}=W,J=this;W.executeQuery=async(Z)=>{let X,G=K4();try{return await $.call(W,Z)}catch(z){throw X=z,await J.#H(z,Z,G),z}finally{if(!X)await J.#G(Z,G)}},W.streamQuery=async function*(Z,X){let G,z=K4();try{for await(let V of k.call(W,Z,X))yield V}catch(V){throw G=V,await J.#H(V,Z,z),V}finally{if(!G)await J.#G(Z,z,!0)}}}async#H(W,$,k){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#L(k)}))}async#G(W,$,k=!1){await this.#$.query(()=>({level:"query",isStream:k,query:W,queryDurationMillis:this.#L($)}))}#L(W){return K4()-W}}var Vk=()=>{};class T8{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch(Vk);return this.#$=this.#k(W).finally(()=>{this.#$=void 0}),this.#$}async#k(W){return await W(this.#W)}}var Rk=["read only","read write"],Fk=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function C6(W){if(W.accessMode&&!Rk.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!Fk.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var wk=["query","error"],Dw=H(wk);class Q6{#W;#$;constructor(W){if(hW(W))this.#$=W,this.#W=H({query:!0,error:!0});else this.#$=_k,this.#W=H({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 _k(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 O5(W){return TW(W)&&hW(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class g1 extends v1{#W;constructor(W){let $,k;if(hk(W))$={executor:W.executor},k={...W};else{let J=W.dialect,Z=J.createDriver(),X=J.createQueryCompiler(),G=J.createAdapter(),z=new Q6(W.log??[]),V=new j6(Z,z),w=new A6(V),R=new W0(X,G,w,W.plugins??[]);$={executor:R},k={config:W,executor:R,dialect:J,driver:V}}super($);this.#W=H(k)}get schema(){return new t0(this.#W.executor)}get dynamic(){return new O6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new R8({node:$1.create(aW(W)?void 0:uW(W))})}get fn(){return Z4()}transaction(){return new U4({...this.#W})}startTransaction(){return new V4({...this.#W})}connection(){return new A5({...this.#W})}withPlugin(W){return new g1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new g1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new g1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new g1({...this.#W})}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}executeQuery(W,$){if($!==void 0)P1("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let k=O5(W)?W.compile():W;return this.getExecutor().executeQuery(k)}async[Symbol.asyncDispose](){await this.destroy()}}class U0 extends g1{#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")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new U0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new U0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new U0({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new U0({...this.#W})}}function hk(W){return TW(W)&&TW(W.config)&&TW(W.driver)&&TW(W.executor)&&TW(W.dialect)}class A5{#W;constructor(W){this.#W=H(W)}async execute(W){return this.#W.executor.provideConnection(async($)=>{let k=this.#W.executor.withConnectionProvider(new T8($)),J=new g1({...this.#W,executor:k});return await W(J)})}}class U4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new U4({...this.#W,accessMode:W})}setIsolationLevel(W){return new U4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:k,...J}=this.#W,Z={isolationLevel:$,accessMode:k};return C6(Z),this.#W.executor.provideConnection(async(X)=>{let G=this.#W.executor.withConnectionProvider(new T8(X)),z=new U0({...J,executor:G}),V=!1;try{await this.#W.driver.beginTransaction(X,Z),V=!0;let w=await W(z);return await this.#W.driver.commitTransaction(X),w}catch(w){if(V)await this.#W.driver.rollbackTransaction(X);throw w}})}}class V4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new V4({...this.#W,accessMode:W})}setIsolationLevel(W){return new V4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...k}=this.#W,J={isolationLevel:W,accessMode:$};C6(J);let Z=await r8(this.#W.executor);return await this.#W.driver.beginTransaction(Z.connection,J),new y1({...k,connection:Z,executor:this.#W.executor.withConnectionProvider(new T8(Z.connection))})}}class y1 extends U0{#W;#$;#k;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new $0(W.executor,$)};let{connection:k,...J}=W;super(J);this.#W=H(W),this.#k=$;let Z=e();this.#$=(X)=>W.executor.compileQuery(X,Z)}get isCommitted(){return this.#k.isCommitted}get isRolledBack(){return this.#k.isRolledBack}commit(){return K0(this.#k),new s0(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#k.isCommitted=!0,this.#W.connection.release()})}rollback(){return K0(this.#k),new s0(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#k.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}rollbackToSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}releaseSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}withPlugin(W){return new y1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new y1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new y1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new y1({...this.#W})}}class s0{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function K0(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class $0{#W;#$;constructor(W,$){if(W instanceof $0)this.#W=W.#W;else this.#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 K0(this.#$),this.#W.executeQuery(W)}stream(W,$){return K0(this.#$),this.#W.stream(W,$)}withConnectionProvider(W){return new $0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new $0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new $0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new $0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new $0(this.#W.withoutPlugins(),this.#$)}}class v8{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new j5(this,W)}$castTo(){return new v8({...this.#W})}$notNull(){return new v8(this.#W)}withPlugin(W){return new v8({...this.#W,plugins:this.#W.plugins!==void 0?H([...this.#W.plugins,W]):H([W])})}toOperationNode(){return this.#k(this.#$())}compile(W){return this.#J(this.#$(W))}async execute(W){let $=this.#$(W);return $.executeQuery(this.#J($))}#$(W){let $=W!==void 0?W.getExecutor():n1;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#k(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#J(W){return W.compileQuery(this.#k(W),this.#W.queryId)}}function m1(W){return new v8(W)}class j5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var k0=Object.assign((W,...$)=>{return m1({queryId:e(),rawNode:YW.create(W,$?.map(C5)??[])})},{ref(W){return m1({queryId:e(),rawNode:YW.createWithChild(nW(W))})},val(W){return m1({queryId:e(),rawNode:YW.createWithChild(zW(W))})},value(W){return this.val(W)},table(W){return m1({queryId:e(),rawNode:YW.createWithChild(kW(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",m1({queryId:e(),rawNode:YW.create($,W.map(i.create))})},lit(W){return m1({queryId:e(),rawNode:YW.createWithChild(EW.createImmediate(W))})},literal(W){return this.lit(W)},raw(W){return m1({queryId:e(),rawNode:YW.createWithSql(W)})},join(W,$=k0`, `){let k=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let Z=0;Z<W.length;++Z)if(k[2*Z]=C5(W[Z]),Z!==W.length-1)k[2*Z+1]=J;return m1({queryId:e(),rawNode:YW.createWithChildren(k)})}});function C5(W){if(LW(W))return W.toOperationNode();return zW(W)}class x6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=H({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)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var Pk=/'/g;class q6 extends x6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),H({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!fW.is(this.parentNode)&&!BW.is(this.parentNode)&&!w1.is(this.parentNode)&&!e8.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 k=W.length-1;for(let J=0;J<=k;J++)if(this.visitNode(W[J]),J<k)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&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.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.ignore)P1("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(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&&!rW.is(this.parentNode)&&!YW.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(!_W(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 k=0;k<$.length;++k)if(this.appendValue($[k]),k!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(fk[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:k}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),k.length>J)this.visitNode(k[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&&W.frontModifiers.length>0)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(" as "),this.visitNode(W.selectQuery);else{if(this.append(" ("),this.compileList([...W.columns,...W.constraints??[]]),this.append(")"),W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}}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 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&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.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.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," ")}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 "),Y0(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){this.append("drop column "),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(Dk[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 ");this.visitNode(W.name)}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 dW.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";if(this.append($?"[":"."),this.append(String(W.value)),$)this.append("]")}visitJSONOperatorChain(W){for(let $=0,k=W.values.length;$<k;$++){if($===k-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.append("add "),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(),k=this.getRightIdentifierWrapper(),J="";for(let Z of W)if(J+=Z,Z===$)J+=$;else if(Z===k)J+=k;return J}sanitizeStringLiteral(W){return W.replace(Pk,"''")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(_W(W))this.appendStringLiteral(W);else if(u1(W)||Y0(W)||P0(W))this.append(W.toString());else if(h0(W))this.append("null");else if(S9(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 W.sort(($,k)=>$.modifier&&k.modifier?Q5[$.modifier]-Q5[k.modifier]:1),H(W)}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var Dk=H({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Q5=H({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),fk=H({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 E8=H({raw(W,$=[]){return H({sql:W,query:YW.createWithSql(W),parameters:H($),queryId:e()})}});class b6{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class B6{transformQuery(W){return W.node}async transformResult(W){return W.result}}var y6="kysely_migration",F4="kysely_migration_lock",Tk=!1,I6="migration_lock",j_=H({__noMigrations__:!0});class g6{#W;constructor(W){this.#W=H(W)}async getMigrations(){let $=await this.#M(this.#J)?await this.#W.db.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#R()).map(({name:J,...Z})=>{let X=$.find((G)=>G.name===J);return{name:J,migration:Z,executedAt:X?new Date(X.timestamp):void 0}})}async migrateToLatest(){return this.#$(()=>({direction:"Up",step:1/0}))}async migrateTo(W){return this.#$(({migrations:$,executedMigrations:k,pendingMigrations:J})=>{if(TW(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!$.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Z=k.indexOf(W),X=J.findIndex((G)=>G.name===W);if(Z!==-1)return{direction:"Down",step:k.length-Z-1};else if(X!==-1)return{direction:"Up",step:X+1};else throw Error(`migration "${W}" isn't executed or pending`)})}async migrateUp(){return this.#$(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#$(()=>({direction:"Down",step:1}))}async#$(W){try{return await this.#Y(),await this.#H(),await this.#G(),await this.#L(),await this.#F(W)}catch($){if($ instanceof R4)return $.resultSet;return{error:$}}}get#k(){return this.#W.migrationTableSchema}get#J(){return this.#W.migrationTableName??y6}get#Z(){return this.#W.migrationLockTableName??F4}get#z(){return this.#W.allowUnorderedMigrations??Tk}get#X(){if(this.#k)return new W1(this.#k);return new B6}async#Y(){if(!this.#k)return;if(await this.#U())return;try{await this.#K(this.#W.db.schema.createSchema(this.#k))}catch($){if(!await this.#U())throw $}}async#H(){if(await this.#M(this.#J))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#J).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#M(this.#J))throw $}}async#G(){if(await this.#M(this.#Z))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#Z).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#M(this.#Z))throw $}}async#L(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#X).insertInto(this.#Z).values({id:I6,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#U(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#k)}async#M(W){let $=this.#k;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.#X).selectFrom(this.#Z).where("id","=",I6).select("id").executeTakeFirst()}async#F(W){let $=this.#W.db.getExecutor().adapter,k=H({lockTable:this.#W.migrationLockTableName??F4,lockRowId:I6,lockTableSchema:this.#W.migrationTableSchema}),J=async(Z)=>{try{await $.acquireMigrationLock(Z,k);let X=await this.#w(Z);if(X.migrations.length===0)return{results:[]};let{direction:G,step:z}=W(X);if(z<=0)return{results:[]};if(G==="Down")return await this.#f(Z,X,z);else if(G==="Up")return await this.#T(Z,X,z);return{results:[]}}finally{await $.releaseMigrationLock(Z,k)}};if($.supportsTransactionalDdl&&!this.#W.disableTransactions)return this.#W.db.transaction().execute(J);else return this.#W.db.connection().execute(J)}async#w(W){let $=await this.#R(),k=await this.#h(W);if(this.#P($,k),!this.#z)this.#D($,k);let J=this.#_($,k);return H({migrations:$,executedMigrations:k,lastMigration:N9(k),pendingMigrations:J})}#_(W,$){return W.filter((k)=>{return!$.includes(k.name)})}async#R(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#h(W){let $=await W.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute(),k=this.#W.nameComparator||((J,Z)=>J.localeCompare(Z));return $.sort((J,Z)=>{if(J.timestamp===Z.timestamp)return k(J.name,Z.name);return new Date(J.timestamp).getTime()-new Date(Z.timestamp).getTime()}).map((J)=>J.name)}#P(W,$){for(let k of $)if(!W.some((J)=>J.name===k))throw Error(`corrupted migrations: previously executed migration ${k} is missing`)}#D(W,$){for(let k=0;k<$.length;++k)if(W[k].name!==$[k])throw Error(`corrupted migrations: expected previously executed migration ${$[k]} to be at index ${k} but ${W[k].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#f(W,$,k){let J=$.executedMigrations.slice().reverse().slice(0,k).map((X)=>{return $.migrations.find((G)=>G.name===X)}),Z=J.map((X)=>{return{migrationName:X.name,direction:"Down",status:"NotExecuted"}});for(let X=0;X<Z.length;++X){let G=J[X];try{if(G.down)await G.down(W),await W.withPlugin(this.#X).deleteFrom(this.#J).where("name","=",G.name).execute(),Z[X]={migrationName:G.name,direction:"Down",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Down",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#T(W,$,k){let Z=$.pendingMigrations.slice(0,k).map((X)=>{return{migrationName:X.name,direction:"Up",status:"NotExecuted"}});for(let X=0;X<Z.length;X++){let G=$.pendingMigrations[X];try{await G.up(W),await W.withPlugin(this.#X).insertInto(this.#J).values({name:G.name,timestamp:new Date().toISOString()}).execute(),Z[X]={migrationName:G.name,direction:"Up",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Up",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#K(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class R4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}var vk=/"/g;class S8 extends q6{sanitizeIdentifier(W){return W.replace(vk,'""')}}class N8{#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",k0`col_description(a.attrelid, a.attnum)`.as("column_description"),k0`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k0`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","!=",y6).where("c.relname","!=",F4);let k=await $.execute();return this.#$(k)}async getMetadata(W){return{tables:await this.getTables(W)}}#$(W){return W.reduce(($,k)=>{let J=$.find((Z)=>Z.name===k.table&&Z.schema===k.schema);if(!J)J=H({name:k.table,isView:k.table_type==="v",schema:k.schema,columns:[]}),$.push(J);return J.columns.push(H({name:k.column,dataType:k.type,dataTypeSchema:k.type_schema,isNullable:!k.not_null,isAutoIncrementing:k.auto_incrementing!==null,hasDefaultValue:k.has_default,comment:k.column_description??void 0})),$},[])}}var Ek=BigInt("3853314791062309107");class O8 extends b6{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k0`select pg_advisory_xact_lock(${k0.lit(Ek)})`.execute(W)}async releaseMigrationLock(W,$){}}class m6{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let k of $)if(k.endsWith(".js")||k.endsWith(".ts")&&!k.endsWith(".d.ts")||k.endsWith(".mjs")||k.endsWith(".mts")&&!k.endsWith(".d.mts")){let J=await import(this.#W.path.join(this.#W.migrationFolder,k)),Z=k.substring(0,k.lastIndexOf("."));if(x5(J?.default))W[Z]=J.default;else if(x5(J))W[Z]=J}return W}}function x5(W){return TW(W)&&hW(W.up)}var{create:Sk,defineProperty:d0,getOwnPropertyDescriptor:Nk,getOwnPropertyNames:Ok,getPrototypeOf:Ak}=Object,jk=Object.prototype.hasOwnProperty,Ck=(W,$,k)=>($ in W)?d0(W,$,{enumerable:!0,configurable:!0,writable:!0,value:k}):W[$]=k,U=(W,$)=>d0(W,"name",{value:$,configurable:!0}),tW=(W,$)=>()=>(W&&($=W(W=0)),$),r=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),_1=(W,$)=>{for(var k in $)d0(W,k,{get:$[k],enumerable:!0})},m5=(W,$,k,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let Z of Ok($))!jk.call(W,Z)&&Z!==k&&d0(W,Z,{get:()=>$[Z],enumerable:!(J=Nk($,Z))||J.enumerable});return W},R0=(W,$,k)=>(k=W!=null?Sk(Ak(W)):{},m5($||!W||!W.__esModule?d0(k,"default",{value:W,enumerable:!0}):k,W)),QW=(W)=>m5(d0({},"__esModule",{value:!0}),W),s=(W,$,k)=>Ck(W,typeof $!="symbol"?$+"":$,k),Qk=r((W)=>{l(),W.byteLength=V,W.toByteArray=R,W.fromByteArray=D;var $=[],k=[],J=typeof Uint8Array<"u"?Uint8Array:Array,Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(X=0,G=Z.length;X<G;++X)$[X]=Z[X],k[Z.charCodeAt(X)]=X;var X,G;k[45]=62,k[95]=63;function z(F){var M=F.length;if(M%4>0)throw Error("Invalid string. Length must be a multiple of 4");var P=F.indexOf("=");P===-1&&(P=M);var f=P===M?0:4-P%4;return[P,f]}U(z,"getLens");function V(F){var M=z(F),P=M[0],f=M[1];return(P+f)*3/4-f}U(V,"byteLength");function w(F,M,P){return(M+P)*3/4-P}U(w,"_byteLength");function R(F){var M,P=z(F),f=P[0],T=P[1],S=new J(w(F,f,T)),q=0,Q=T>0?f-4:f,v;for(v=0;v<Q;v+=4)M=k[F.charCodeAt(v)]<<18|k[F.charCodeAt(v+1)]<<12|k[F.charCodeAt(v+2)]<<6|k[F.charCodeAt(v+3)],S[q++]=M>>16&255,S[q++]=M>>8&255,S[q++]=M&255;return T===2&&(M=k[F.charCodeAt(v)]<<2|k[F.charCodeAt(v+1)]>>4,S[q++]=M&255),T===1&&(M=k[F.charCodeAt(v)]<<10|k[F.charCodeAt(v+1)]<<4|k[F.charCodeAt(v+2)]>>2,S[q++]=M>>8&255,S[q++]=M&255),S}U(R,"toByteArray");function h(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}U(h,"tripletToBase64");function _(F,M,P){for(var f,T=[],S=M;S<P;S+=3)f=(F[S]<<16&16711680)+(F[S+1]<<8&65280)+(F[S+2]&255),T.push(h(f));return T.join("")}U(_,"encodeChunk");function D(F){for(var M,P=F.length,f=P%3,T=[],S=16383,q=0,Q=P-f;q<Q;q+=S)T.push(_(F,q,q+S>Q?Q:q+S));return f===1?(M=F[P-1],T.push($[M>>2]+$[M<<4&63]+"==")):f===2&&(M=(F[P-2]<<8)+F[P-1],T.push($[M>>10]+$[M>>4&63]+$[M<<2&63]+"=")),T.join("")}U(D,"fromByteArray")}),xk=r((W)=>{l(),W.read=function($,k,J,Z,X){var G,z,V=X*8-Z-1,w=(1<<V)-1,R=w>>1,h=-7,_=J?X-1:0,D=J?-1:1,F=$[k+_];for(_+=D,G=F&(1<<-h)-1,F>>=-h,h+=V;h>0;G=G*256+$[k+_],_+=D,h-=8);for(z=G&(1<<-h)-1,G>>=-h,h+=Z;h>0;z=z*256+$[k+_],_+=D,h-=8);if(G===0)G=1-R;else{if(G===w)return z?NaN:(F?-1:1)*(1/0);z=z+Math.pow(2,Z),G=G-R}return(F?-1:1)*z*Math.pow(2,G-Z)},W.write=function($,k,J,Z,X,G){var z,V,w,R=G*8-X-1,h=(1<<R)-1,_=h>>1,D=X===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=Z?0:G-1,M=Z?1:-1,P=k<0||k===0&&1/k<0?1:0;for(k=Math.abs(k),isNaN(k)||k===1/0?(V=isNaN(k)?1:0,z=h):(z=Math.floor(Math.log(k)/Math.LN2),k*(w=Math.pow(2,-z))<1&&(z--,w*=2),z+_>=1?k+=D/w:k+=D*Math.pow(2,1-_),k*w>=2&&(z++,w/=2),z+_>=h?(V=0,z=h):z+_>=1?(V=(k*w-1)*Math.pow(2,X),z=z+_):(V=k*Math.pow(2,_-1)*Math.pow(2,X),z=0));X>=8;$[J+F]=V&255,F+=M,V/=256,X-=8);for(z=z<<X|V,R+=X;R>0;$[J+F]=z&255,F+=M,z/=256,R-=8);$[J+F-M]|=P*128}}),qk=r((W)=>{l();var $=Qk(),k=xk(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=z,W.SlowBuffer=T,W.INSPECT_MAX_BYTES=50;var Z=2147483647;W.kMaxLength=Z,z.TYPED_ARRAY_SUPPORT=X(),!z.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 X(){try{let Y=new Uint8Array(1),L={foo:U(function(){return 42},"foo")};return Object.setPrototypeOf(L,Uint8Array.prototype),Object.setPrototypeOf(Y,L),Y.foo()===42}catch{return!1}}U(X,"typedArraySupport"),Object.defineProperty(z.prototype,"parent",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(z.prototype,"offset",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.byteOffset},"get")});function G(Y){if(Y>Z)throw RangeError('The value "'+Y+'" is invalid for option "size"');let L=new Uint8Array(Y);return Object.setPrototypeOf(L,z.prototype),L}U(G,"createBuffer");function z(Y,L,K){if(typeof Y=="number"){if(typeof L=="string")throw TypeError('The "string" argument must be of type string. Received type number');return h(Y)}return V(Y,L,K)}U(z,"Buffer"),z.poolSize=8192;function V(Y,L,K){if(typeof Y=="string")return _(Y,L);if(ArrayBuffer.isView(Y))return F(Y);if(Y==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y);if(Z1(Y,ArrayBuffer)||Y&&Z1(Y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z1(Y,SharedArrayBuffer)||Y&&Z1(Y.buffer,SharedArrayBuffer)))return M(Y,L,K);if(typeof Y=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let E=Y.valueOf&&Y.valueOf();if(E!=null&&E!==Y)return z.from(E,L,K);let O=P(Y);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Y[Symbol.toPrimitive]=="function")return z.from(Y[Symbol.toPrimitive]("string"),L,K);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y)}U(V,"from"),z.from=function(Y,L,K){return V(Y,L,K)},Object.setPrototypeOf(z.prototype,Uint8Array.prototype),Object.setPrototypeOf(z,Uint8Array);function w(Y){if(typeof Y!="number")throw TypeError('"size" argument must be of type number');if(Y<0)throw RangeError('The value "'+Y+'" is invalid for option "size"')}U(w,"assertSize");function R(Y,L,K){return w(Y),Y<=0?G(Y):L!==void 0?typeof K=="string"?G(Y).fill(L,K):G(Y).fill(L):G(Y)}U(R,"alloc"),z.alloc=function(Y,L,K){return R(Y,L,K)};function h(Y){return w(Y),G(Y<0?0:f(Y)|0)}U(h,"allocUnsafe"),z.allocUnsafe=function(Y){return h(Y)},z.allocUnsafeSlow=function(Y){return h(Y)};function _(Y,L){if((typeof L!="string"||L==="")&&(L="utf8"),!z.isEncoding(L))throw TypeError("Unknown encoding: "+L);let K=S(Y,L)|0,E=G(K),O=E.write(Y,L);return O!==K&&(E=E.slice(0,O)),E}U(_,"fromString");function D(Y){let L=Y.length<0?0:f(Y.length)|0,K=G(L);for(let E=0;E<L;E+=1)K[E]=Y[E]&255;return K}U(D,"fromArrayLike");function F(Y){if(Z1(Y,Uint8Array)){let L=new Uint8Array(Y);return M(L.buffer,L.byteOffset,L.byteLength)}return D(Y)}U(F,"fromArrayView");function M(Y,L,K){if(L<0||Y.byteLength<L)throw RangeError('"offset" is outside of buffer bounds');if(Y.byteLength<L+(K||0))throw RangeError('"length" is outside of buffer bounds');let E;return L===void 0&&K===void 0?E=new Uint8Array(Y):K===void 0?E=new Uint8Array(Y,L):E=new Uint8Array(Y,L,K),Object.setPrototypeOf(E,z.prototype),E}U(M,"fromArrayBuffer");function P(Y){if(z.isBuffer(Y)){let L=f(Y.length)|0,K=G(L);return K.length===0||Y.copy(K,0,0,L),K}if(Y.length!==void 0)return typeof Y.length!="number"||I8(Y.length)?G(0):D(Y);if(Y.type==="Buffer"&&Array.isArray(Y.data))return D(Y.data)}U(P,"fromObject");function f(Y){if(Y>=Z)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Z.toString(16)+" bytes");return Y|0}U(f,"checked");function T(Y){return+Y!=Y&&(Y=0),z.alloc(+Y)}U(T,"SlowBuffer"),z.isBuffer=U(function(Y){return Y!=null&&Y._isBuffer===!0&&Y!==z.prototype},"isBuffer"),z.compare=U(function(Y,L){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),Z1(L,Uint8Array)&&(L=z.from(L,L.offset,L.byteLength)),!z.isBuffer(Y)||!z.isBuffer(L))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(Y===L)return 0;let K=Y.length,E=L.length;for(let O=0,x=Math.min(K,E);O<x;++O)if(Y[O]!==L[O]){K=Y[O],E=L[O];break}return K<E?-1:E<K?1:0},"compare"),z.isEncoding=U(function(Y){switch(String(Y).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"),z.concat=U(function(Y,L){if(!Array.isArray(Y))throw TypeError('"list" argument must be an Array of Buffers');if(Y.length===0)return z.alloc(0);let K;if(L===void 0)for(L=0,K=0;K<Y.length;++K)L+=Y[K].length;let E=z.allocUnsafe(L),O=0;for(K=0;K<Y.length;++K){let x=Y[K];if(Z1(x,Uint8Array))O+x.length>E.length?(z.isBuffer(x)||(x=z.from(x)),x.copy(E,O)):Uint8Array.prototype.set.call(E,x,O);else if(z.isBuffer(x))x.copy(E,O);else throw TypeError('"list" argument must be an Array of Buffers');O+=x.length}return E},"concat");function S(Y,L){if(z.isBuffer(Y))return Y.length;if(ArrayBuffer.isView(Y)||Z1(Y,ArrayBuffer))return Y.byteLength;if(typeof Y!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Y);let K=Y.length,E=arguments.length>2&&arguments[2]===!0;if(!E&&K===0)return 0;let O=!1;for(;;)switch(L){case"ascii":case"latin1":case"binary":return K;case"utf8":case"utf-8":return B8(Y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K*2;case"hex":return K>>>1;case"base64":return B4(Y).length;default:if(O)return E?-1:B8(Y).length;L=(""+L).toLowerCase(),O=!0}}U(S,"byteLength"),z.byteLength=S;function q(Y,L,K){let E=!1;if((L===void 0||L<0)&&(L=0),L>this.length||((K===void 0||K>this.length)&&(K=this.length),K<=0)||(K>>>=0,L>>>=0,K<=L))return"";for(Y||(Y="utf8");;)switch(Y){case"hex":return n(this,L,K);case"utf8":case"utf-8":return B(this,L,K);case"ascii":return a(this,L,K);case"latin1":case"binary":return JW(this,L,K);case"base64":return c(this,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sW(this,L,K);default:if(E)throw TypeError("Unknown encoding: "+Y);Y=(Y+"").toLowerCase(),E=!0}}U(q,"slowToString"),z.prototype._isBuffer=!0;function Q(Y,L,K){let E=Y[L];Y[L]=Y[K],Y[K]=E}U(Q,"swap"),z.prototype.swap16=U(function(){let Y=this.length;if(Y%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let L=0;L<Y;L+=2)Q(this,L,L+1);return this},"swap16"),z.prototype.swap32=U(function(){let Y=this.length;if(Y%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let L=0;L<Y;L+=4)Q(this,L,L+3),Q(this,L+1,L+2);return this},"swap32"),z.prototype.swap64=U(function(){let Y=this.length;if(Y%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let L=0;L<Y;L+=8)Q(this,L,L+7),Q(this,L+1,L+6),Q(this,L+2,L+5),Q(this,L+3,L+4);return this},"swap64"),z.prototype.toString=U(function(){let Y=this.length;return Y===0?"":arguments.length===0?B(this,0,Y):q.apply(this,arguments)},"toString"),z.prototype.toLocaleString=z.prototype.toString,z.prototype.equals=U(function(Y){if(!z.isBuffer(Y))throw TypeError("Argument must be a Buffer");return this===Y?!0:z.compare(this,Y)===0},"equals"),z.prototype.inspect=U(function(){let Y="",L=W.INSPECT_MAX_BYTES;return Y=this.toString("hex",0,L).replace(/(.{2})/g,"$1 ").trim(),this.length>L&&(Y+=" ... "),"<Buffer "+Y+">"},"inspect"),J&&(z.prototype[J]=z.prototype.inspect),z.prototype.compare=U(function(Y,L,K,E,O){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),!z.isBuffer(Y))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof Y);if(L===void 0&&(L=0),K===void 0&&(K=Y?Y.length:0),E===void 0&&(E=0),O===void 0&&(O=this.length),L<0||K>Y.length||E<0||O>this.length)throw RangeError("out of range index");if(E>=O&&L>=K)return 0;if(E>=O)return-1;if(L>=K)return 1;if(L>>>=0,K>>>=0,E>>>=0,O>>>=0,this===Y)return 0;let x=O-E,y=K-L,FW=Math.min(x,y),OW=this.slice(E,O),DW=Y.slice(L,K);for(let wW=0;wW<FW;++wW)if(OW[wW]!==DW[wW]){x=OW[wW],y=DW[wW];break}return x<y?-1:y<x?1:0},"compare");function v(Y,L,K,E,O){if(Y.length===0)return-1;if(typeof K=="string"?(E=K,K=0):K>2147483647?K=2147483647:K<-2147483648&&(K=-2147483648),K=+K,I8(K)&&(K=O?0:Y.length-1),K<0&&(K=Y.length+K),K>=Y.length){if(O)return-1;K=Y.length-1}else if(K<0)if(O)K=0;else return-1;if(typeof L=="string"&&(L=z.from(L,E)),z.isBuffer(L))return L.length===0?-1:j(Y,L,K,E,O);if(typeof L=="number")return L=L&255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(Y,L,K):Uint8Array.prototype.lastIndexOf.call(Y,L,K):j(Y,[L],K,E,O);throw TypeError("val must be string, number or Buffer")}U(v,"bidirectionalIndexOf");function j(Y,L,K,E,O){let x=1,y=Y.length,FW=L.length;if(E!==void 0&&(E=String(E).toLowerCase(),E==="ucs2"||E==="ucs-2"||E==="utf16le"||E==="utf-16le")){if(Y.length<2||L.length<2)return-1;x=2,y/=2,FW/=2,K/=2}function OW(wW,vW){return x===1?wW[vW]:wW.readUInt16BE(vW*x)}U(OW,"read");let DW;if(O){let wW=-1;for(DW=K;DW<y;DW++)if(OW(Y,DW)===OW(L,wW===-1?0:DW-wW)){if(wW===-1&&(wW=DW),DW-wW+1===FW)return wW*x}else wW!==-1&&(DW-=DW-wW),wW=-1}else for(K+FW>y&&(K=y-FW),DW=K;DW>=0;DW--){let wW=!0;for(let vW=0;vW<FW;vW++)if(OW(Y,DW+vW)!==OW(L,vW)){wW=!1;break}if(wW)return DW}return-1}U(j,"arrayIndexOf"),z.prototype.includes=U(function(Y,L,K){return this.indexOf(Y,L,K)!==-1},"includes"),z.prototype.indexOf=U(function(Y,L,K){return v(this,Y,L,K,!0)},"indexOf"),z.prototype.lastIndexOf=U(function(Y,L,K){return v(this,Y,L,K,!1)},"lastIndexOf");function A(Y,L,K,E){K=Number(K)||0;let O=Y.length-K;E?(E=Number(E),E>O&&(E=O)):E=O;let x=L.length;E>x/2&&(E=x/2);let y;for(y=0;y<E;++y){let FW=parseInt(L.substr(y*2,2),16);if(I8(FW))return y;Y[K+y]=FW}return y}U(A,"hexWrite");function N(Y,L,K,E){return W8(B8(L,Y.length-K),Y,K,E)}U(N,"utf8Write");function b(Y,L,K,E){return W8(Z9(L),Y,K,E)}U(b,"asciiWrite");function C(Y,L,K,E){return W8(B4(L),Y,K,E)}U(C,"base64Write");function u(Y,L,K,E){return W8(X9(L,Y.length-K),Y,K,E)}U(u,"ucs2Write"),z.prototype.write=U(function(Y,L,K,E){if(L===void 0)E="utf8",K=this.length,L=0;else if(K===void 0&&typeof L=="string")E=L,K=this.length,L=0;else if(isFinite(L))L=L>>>0,isFinite(K)?(K=K>>>0,E===void 0&&(E="utf8")):(E=K,K=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let O=this.length-L;if((K===void 0||K>O)&&(K=O),Y.length>0&&(K<0||L<0)||L>this.length)throw RangeError("Attempt to write outside buffer bounds");E||(E="utf8");let x=!1;for(;;)switch(E){case"hex":return A(this,Y,L,K);case"utf8":case"utf-8":return N(this,Y,L,K);case"ascii":case"latin1":case"binary":return b(this,Y,L,K);case"base64":return C(this,Y,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u(this,Y,L,K);default:if(x)throw TypeError("Unknown encoding: "+E);E=(""+E).toLowerCase(),x=!0}},"write"),z.prototype.toJSON=U(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function c(Y,L,K){return L===0&&K===Y.length?$.fromByteArray(Y):$.fromByteArray(Y.slice(L,K))}U(c,"base64Slice");function B(Y,L,K){K=Math.min(Y.length,K);let E=[],O=L;for(;O<K;){let x=Y[O],y=null,FW=x>239?4:x>223?3:x>191?2:1;if(O+FW<=K){let OW,DW,wW,vW;switch(FW){case 1:x<128&&(y=x);break;case 2:OW=Y[O+1],(OW&192)===128&&(vW=(x&31)<<6|OW&63,vW>127&&(y=vW));break;case 3:OW=Y[O+1],DW=Y[O+2],(OW&192)===128&&(DW&192)===128&&(vW=(x&15)<<12|(OW&63)<<6|DW&63,vW>2047&&(vW<55296||vW>57343)&&(y=vW));break;case 4:OW=Y[O+1],DW=Y[O+2],wW=Y[O+3],(OW&192)===128&&(DW&192)===128&&(wW&192)===128&&(vW=(x&15)<<18|(OW&63)<<12|(DW&63)<<6|wW&63,vW>65535&&vW<1114112&&(y=vW))}}y===null?(y=65533,FW=1):y>65535&&(y-=65536,E.push(y>>>10&1023|55296),y=56320|y&1023),E.push(y),O+=FW}return p(E)}U(B,"utf8Slice");var m=4096;function p(Y){let L=Y.length;if(L<=m)return String.fromCharCode.apply(String,Y);let K="",E=0;for(;E<L;)K+=String.fromCharCode.apply(String,Y.slice(E,E+=m));return K}U(p,"decodeCodePointsArray");function a(Y,L,K){let E="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)E+=String.fromCharCode(Y[O]&127);return E}U(a,"asciiSlice");function JW(Y,L,K){let E="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)E+=String.fromCharCode(Y[O]);return E}U(JW,"latin1Slice");function n(Y,L,K){let E=Y.length;(!L||L<0)&&(L=0),(!K||K<0||K>E)&&(K=E);let O="";for(let x=L;x<K;++x)O+=p7[Y[x]];return O}U(n,"hexSlice");function sW(Y,L,K){let E=Y.slice(L,K),O="";for(let x=0;x<E.length-1;x+=2)O+=String.fromCharCode(E[x]+E[x+1]*256);return O}U(sW,"utf16leSlice"),z.prototype.slice=U(function(Y,L){let K=this.length;Y=~~Y,L=L===void 0?K:~~L,Y<0?(Y+=K,Y<0&&(Y=0)):Y>K&&(Y=K),L<0?(L+=K,L<0&&(L=0)):L>K&&(L=K),L<Y&&(L=Y);let E=this.subarray(Y,L);return Object.setPrototypeOf(E,z.prototype),E},"slice");function RW(Y,L,K){if(Y%1!==0||Y<0)throw RangeError("offset is not uint");if(Y+L>K)throw RangeError("Trying to access beyond buffer length")}U(RW,"checkOffset"),z.prototype.readUintLE=z.prototype.readUIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)E+=this[Y+x]*O;return E},"readUIntLE"),z.prototype.readUintBE=z.prototype.readUIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y+--L],O=1;for(;L>0&&(O*=256);)E+=this[Y+--L]*O;return E},"readUIntBE"),z.prototype.readUint8=z.prototype.readUInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]},"readUInt8"),z.prototype.readUint16LE=z.prototype.readUInt16LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]|this[Y+1]<<8},"readUInt16LE"),z.prototype.readUint16BE=z.prototype.readUInt16BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]<<8|this[Y+1]},"readUInt16BE"),z.prototype.readUint32LE=z.prototype.readUInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),(this[Y]|this[Y+1]<<8|this[Y+2]<<16)+this[Y+3]*16777216},"readUInt32LE"),z.prototype.readUint32BE=z.prototype.readUInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]*16777216+(this[Y+1]<<16|this[Y+2]<<8|this[Y+3])},"readUInt32BE"),z.prototype.readBigUInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216,O=this[++Y]+this[++Y]*256+this[++Y]*65536+K*16777216;return BigInt(E)+(BigInt(O)<<BigInt(32))},"readBigUInt64LE")),z.prototype.readBigUInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=L*16777216+this[++Y]*65536+this[++Y]*256+this[++Y],O=this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K;return(BigInt(E)<<BigInt(32))+BigInt(O)},"readBigUInt64BE")),z.prototype.readIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)E+=this[Y+x]*O;return O*=128,E>=O&&(E-=Math.pow(2,8*L)),E},"readIntLE"),z.prototype.readIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let E=L,O=1,x=this[Y+--E];for(;E>0&&(O*=256);)x+=this[Y+--E]*O;return O*=128,x>=O&&(x-=Math.pow(2,8*L)),x},"readIntBE"),z.prototype.readInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]&128?(255-this[Y]+1)*-1:this[Y]},"readInt8"),z.prototype.readInt16LE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y]|this[Y+1]<<8;return K&32768?K|4294901760:K},"readInt16LE"),z.prototype.readInt16BE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y+1]|this[Y]<<8;return K&32768?K|4294901760:K},"readInt16BE"),z.prototype.readInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]|this[Y+1]<<8|this[Y+2]<<16|this[Y+3]<<24},"readInt32LE"),z.prototype.readInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]<<24|this[Y+1]<<16|this[Y+2]<<8|this[Y+3]},"readInt32BE"),z.prototype.readBigInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=this[Y+4]+this[Y+5]*256+this[Y+6]*65536+(K<<24);return(BigInt(E)<<BigInt(32))+BigInt(L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216)},"readBigInt64LE")),z.prototype.readBigInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let E=(L<<24)+this[++Y]*65536+this[++Y]*256+this[++Y];return(BigInt(E)<<BigInt(32))+BigInt(this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K)},"readBigInt64BE")),z.prototype.readFloatLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!0,23,4)},"readFloatLE"),z.prototype.readFloatBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!1,23,4)},"readFloatBE"),z.prototype.readDoubleLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!0,52,8)},"readDoubleLE"),z.prototype.readDoubleBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!1,52,8)},"readDoubleBE");function SW(Y,L,K,E,O,x){if(!z.isBuffer(Y))throw TypeError('"buffer" argument must be a Buffer instance');if(L>O||L<x)throw RangeError('"value" argument is out of bounds');if(K+E>Y.length)throw RangeError("Index out of range")}U(SW,"checkInt"),z.prototype.writeUintLE=z.prototype.writeUIntLE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,K=K>>>0,!E){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=1,x=0;for(this[L]=Y&255;++x<K&&(O*=256);)this[L+x]=Y/O&255;return L+K},"writeUIntLE"),z.prototype.writeUintBE=z.prototype.writeUIntBE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,K=K>>>0,!E){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=K-1,x=1;for(this[L+O]=Y&255;--O>=0&&(x*=256);)this[L+O]=Y/x&255;return L+K},"writeUIntBE"),z.prototype.writeUint8=z.prototype.writeUInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,255,0),this[L]=Y&255,L+1},"writeUInt8"),z.prototype.writeUint16LE=z.prototype.writeUInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeUInt16LE"),z.prototype.writeUint16BE=z.prototype.writeUInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeUInt16BE"),z.prototype.writeUint32LE=z.prototype.writeUInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L+3]=Y>>>24,this[L+2]=Y>>>16,this[L+1]=Y>>>8,this[L]=Y&255,L+4},"writeUInt32LE"),z.prototype.writeUint32BE=z.prototype.writeUInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeUInt32BE");function r0(Y,L,K,E,O){b4(L,E,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,K}U(r0,"wrtBigUInt64LE");function e0(Y,L,K,E,O){b4(L,E,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K+7]=x,x=x>>8,Y[K+6]=x,x=x>>8,Y[K+5]=x,x=x>>8,Y[K+4]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K+3]=y,y=y>>8,Y[K+2]=y,y=y>>8,Y[K+1]=y,y=y>>8,Y[K]=y,K+8}U(e0,"wrtBigUInt64BE"),z.prototype.writeBigUInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),z.prototype.writeBigUInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),z.prototype.writeIntLE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,!E){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=0,x=1,y=0;for(this[L]=Y&255;++O<K&&(x*=256);)Y<0&&y===0&&this[L+O-1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntLE"),z.prototype.writeIntBE=U(function(Y,L,K,E){if(Y=+Y,L=L>>>0,!E){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=K-1,x=1,y=0;for(this[L+O]=Y&255;--O>=0&&(x*=256);)Y<0&&y===0&&this[L+O+1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntBE"),z.prototype.writeInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,127,-128),Y<0&&(Y=255+Y+1),this[L]=Y&255,L+1},"writeInt8"),z.prototype.writeInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeInt16LE"),z.prototype.writeInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeInt16BE"),z.prototype.writeInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),this[L]=Y&255,this[L+1]=Y>>>8,this[L+2]=Y>>>16,this[L+3]=Y>>>24,L+4},"writeInt32LE"),z.prototype.writeInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),Y<0&&(Y=4294967295+Y+1),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeInt32BE"),z.prototype.writeBigInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),z.prototype.writeBigInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function C4(Y,L,K,E,O,x){if(K+E>Y.length)throw RangeError("Index out of range");if(K<0)throw RangeError("Index out of range")}U(C4,"checkIEEE754");function Q4(Y,L,K,E,O){return L=+L,K=K>>>0,O||C4(Y,L,K,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),k.write(Y,L,K,E,23,4),K+4}U(Q4,"writeFloat"),z.prototype.writeFloatLE=U(function(Y,L,K){return Q4(this,Y,L,!0,K)},"writeFloatLE"),z.prototype.writeFloatBE=U(function(Y,L,K){return Q4(this,Y,L,!1,K)},"writeFloatBE");function x4(Y,L,K,E,O){return L=+L,K=K>>>0,O||C4(Y,L,K,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),k.write(Y,L,K,E,52,8),K+8}U(x4,"writeDouble"),z.prototype.writeDoubleLE=U(function(Y,L,K){return x4(this,Y,L,!0,K)},"writeDoubleLE"),z.prototype.writeDoubleBE=U(function(Y,L,K){return x4(this,Y,L,!1,K)},"writeDoubleBE"),z.prototype.copy=U(function(Y,L,K,E){if(!z.isBuffer(Y))throw TypeError("argument should be a Buffer");if(K||(K=0),!E&&E!==0&&(E=this.length),L>=Y.length&&(L=Y.length),L||(L=0),E>0&&E<K&&(E=K),E===K||Y.length===0||this.length===0)return 0;if(L<0)throw RangeError("targetStart out of bounds");if(K<0||K>=this.length)throw RangeError("Index out of range");if(E<0)throw RangeError("sourceEnd out of bounds");E>this.length&&(E=this.length),Y.length-L<E-K&&(E=Y.length-L+K);let O=E-K;return this===Y&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(L,K,E):Uint8Array.prototype.set.call(Y,this.subarray(K,E),L),O},"copy"),z.prototype.fill=U(function(Y,L,K,E){if(typeof Y=="string"){if(typeof L=="string"?(E=L,L=0,K=this.length):typeof K=="string"&&(E=K,K=this.length),E!==void 0&&typeof E!="string")throw TypeError("encoding must be a string");if(typeof E=="string"&&!z.isEncoding(E))throw TypeError("Unknown encoding: "+E);if(Y.length===1){let x=Y.charCodeAt(0);(E==="utf8"&&x<128||E==="latin1")&&(Y=x)}}else typeof Y=="number"?Y=Y&255:typeof Y=="boolean"&&(Y=Number(Y));if(L<0||this.length<L||this.length<K)throw RangeError("Out of range index");if(K<=L)return this;L=L>>>0,K=K===void 0?this.length:K>>>0,Y||(Y=0);let O;if(typeof Y=="number")for(O=L;O<K;++O)this[O]=Y;else{let x=z.isBuffer(Y)?Y:z.from(Y,E),y=x.length;if(y===0)throw TypeError('The value "'+Y+'" is invalid for argument "value"');for(O=0;O<K-L;++O)this[O+L]=x[O%y]}return this},"fill");var w0={};function b8(Y,L,K){var E;w0[Y]=(E=class extends K{constructor(){super(),Object.defineProperty(this,"message",{value:L.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Y}]`,this.stack,delete this.name}get code(){return Y}set code(O){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:O,writable:!0})}toString(){return`${this.name} [${Y}]: ${this.message}`}},U(E,"NodeError"),E)}U(b8,"E"),b8("ERR_BUFFER_OUT_OF_BOUNDS",function(Y){return Y?`${Y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),b8("ERR_INVALID_ARG_TYPE",function(Y,L){return`The "${Y}" argument must be of type number. Received type ${typeof L}`},TypeError),b8("ERR_OUT_OF_RANGE",function(Y,L,K){let E=`The value of "${Y}" is out of range.`,O=K;return Number.isInteger(K)&&Math.abs(K)>4294967296?O=q4(String(K)):typeof K=="bigint"&&(O=String(K),(K>BigInt(2)**BigInt(32)||K<-(BigInt(2)**BigInt(32)))&&(O=q4(O)),O+="n"),E+=` It must be ${L}. Received ${O}`,E},RangeError);function q4(Y){let L="",K=Y.length,E=Y[0]==="-"?1:0;for(;K>=E+4;K-=3)L=`_${Y.slice(K-3,K)}${L}`;return`${Y.slice(0,K)}${L}`}U(q4,"addNumericalSeparator");function k9(Y,L,K){Z0(L,"offset"),(Y[L]===void 0||Y[L+K]===void 0)&&_0(L,Y.length-(K+1))}U(k9,"checkBounds");function b4(Y,L,K,E,O,x){if(Y>K||Y<L){let y=typeof L=="bigint"?"n":"",FW;throw x>3?L===0||L===BigInt(0)?FW=`>= 0${y} and < 2${y} ** ${(x+1)*8}${y}`:FW=`>= -(2${y} ** ${(x+1)*8-1}${y}) and < 2 ** ${(x+1)*8-1}${y}`:FW=`>= ${L}${y} and <= ${K}${y}`,new w0.ERR_OUT_OF_RANGE("value",FW,Y)}k9(E,O,x)}U(b4,"checkIntBI");function Z0(Y,L){if(typeof Y!="number")throw new w0.ERR_INVALID_ARG_TYPE(L,"number",Y)}U(Z0,"validateNumber");function _0(Y,L,K){throw Math.floor(Y)!==Y?(Z0(Y,K),new w0.ERR_OUT_OF_RANGE(K||"offset","an integer",Y)):L<0?new w0.ERR_BUFFER_OUT_OF_BOUNDS:new w0.ERR_OUT_OF_RANGE(K||"offset",`>= ${K?1:0} and <= ${L}`,Y)}U(_0,"boundsError");var i7=/[^+/0-9A-Za-z-_]/g;function J9(Y){if(Y=Y.split("=")[0],Y=Y.trim().replace(i7,""),Y.length<2)return"";for(;Y.length%4!==0;)Y=Y+"=";return Y}U(J9,"base64clean");function B8(Y,L){L=L||1/0;let K,E=Y.length,O=null,x=[];for(let y=0;y<E;++y){if(K=Y.charCodeAt(y),K>55295&&K<57344){if(!O){if(K>56319){(L-=3)>-1&&x.push(239,191,189);continue}else if(y+1===E){(L-=3)>-1&&x.push(239,191,189);continue}O=K;continue}if(K<56320){(L-=3)>-1&&x.push(239,191,189),O=K;continue}K=(O-55296<<10|K-56320)+65536}else O&&(L-=3)>-1&&x.push(239,191,189);if(O=null,K<128){if((L-=1)<0)break;x.push(K)}else if(K<2048){if((L-=2)<0)break;x.push(K>>6|192,K&63|128)}else if(K<65536){if((L-=3)<0)break;x.push(K>>12|224,K>>6&63|128,K&63|128)}else if(K<1114112){if((L-=4)<0)break;x.push(K>>18|240,K>>12&63|128,K>>6&63|128,K&63|128)}else throw Error("Invalid code point")}return x}U(B8,"utf8ToBytes");function Z9(Y){let L=[];for(let K=0;K<Y.length;++K)L.push(Y.charCodeAt(K)&255);return L}U(Z9,"asciiToBytes");function X9(Y,L){let K,E,O,x=[];for(let y=0;y<Y.length&&!((L-=2)<0);++y)K=Y.charCodeAt(y),E=K>>8,O=K%256,x.push(O),x.push(E);return x}U(X9,"utf16leToBytes");function B4(Y){return $.toByteArray(J9(Y))}U(B4,"base64ToBytes");function W8(Y,L,K,E){let O;for(O=0;O<E&&!(O+K>=L.length||O>=Y.length);++O)L[O+K]=Y[O];return O}U(W8,"blitBuffer");function Z1(Y,L){return Y instanceof L||Y!=null&&Y.constructor!=null&&Y.constructor.name!=null&&Y.constructor.name===L.name}U(Z1,"isInstance");function I8(Y){return Y!==Y}U(I8,"numberIsNaN");var p7=function(){let Y="0123456789abcdef",L=Array(256);for(let K=0;K<16;++K){let E=K*16;for(let O=0;O<16;++O)L[E+O]=Y[K]+Y[O]}return L}();function O1(Y){return typeof BigInt>"u"?Y9:Y}U(O1,"defineBigIntMethod");function Y9(){throw Error("BigInt not supported")}U(Y9,"BufferBigIntNotDefined")}),D4,t6,bk,t,o,l=tW(()=>{D4=globalThis,t6=globalThis.setImmediate??((W)=>setTimeout(W,0)),bk=globalThis.clearImmediate??((W)=>clearTimeout(W)),t=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:qk().Buffer,o=globalThis.process??{},o.env??(o.env={});try{o.nextTick(()=>{})}catch{let W=Promise.resolve();o.nextTick=W.then.bind(W)}}),F0=r((W,$)=>{l();var k=typeof Reflect=="object"?Reflect:null,J=k&&typeof k.apply=="function"?k.apply:U(function(v,j,A){return Function.prototype.apply.call(v,j,A)},"ReflectApply"),Z;k&&typeof k.ownKeys=="function"?Z=k.ownKeys:Object.getOwnPropertySymbols?Z=U(function(v){return Object.getOwnPropertyNames(v).concat(Object.getOwnPropertySymbols(v))},"ReflectOwnKeys"):Z=U(function(v){return Object.getOwnPropertyNames(v)},"ReflectOwnKeys");function X(v){console&&console.warn&&console.warn(v)}U(X,"ProcessEmitWarning");var G=Number.isNaN||U(function(v){return v!==v},"NumberIsNaN");function z(){z.init.call(this)}U(z,"EventEmitter"),$.exports=z,$.exports.once=S,z.EventEmitter=z,z.prototype._events=void 0,z.prototype._eventsCount=0,z.prototype._maxListeners=void 0;var V=10;function w(v){if(typeof v!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}U(w,"checkListener"),Object.defineProperty(z,"defaultMaxListeners",{enumerable:!0,get:U(function(){return V},"get"),set:U(function(v){if(typeof v!="number"||v<0||G(v))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");V=v},"set")}),z.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},z.prototype.setMaxListeners=U(function(v){if(typeof v!="number"||v<0||G(v))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this},"setMaxListeners");function R(v){return v._maxListeners===void 0?z.defaultMaxListeners:v._maxListeners}U(R,"_getMaxListeners"),z.prototype.getMaxListeners=U(function(){return R(this)},"getMaxListeners"),z.prototype.emit=U(function(v){for(var j=[],A=1;A<arguments.length;A++)j.push(arguments[A]);var N=v==="error",b=this._events;if(b!==void 0)N=N&&b.error===void 0;else if(!N)return!1;if(N){var C;if(j.length>0&&(C=j[0]),C instanceof Error)throw C;var u=Error("Unhandled error."+(C?" ("+C.message+")":""));throw u.context=C,u}var c=b[v];if(c===void 0)return!1;if(typeof c=="function")J(c,this,j);else for(var B=c.length,m=P(c,B),A=0;A<B;++A)J(m[A],this,j);return!0},"emit");function h(v,j,A,N){var b,C,u;if(w(A),C=v._events,C===void 0?(C=v._events=Object.create(null),v._eventsCount=0):(C.newListener!==void 0&&(v.emit("newListener",j,A.listener?A.listener:A),C=v._events),u=C[j]),u===void 0)u=C[j]=A,++v._eventsCount;else if(typeof u=="function"?u=C[j]=N?[A,u]:[u,A]:N?u.unshift(A):u.push(A),b=R(v),b>0&&u.length>b&&!u.warned){u.warned=!0;var c=Error("Possible EventEmitter memory leak detected. "+u.length+" "+String(j)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=v,c.type=j,c.count=u.length,X(c)}return v}U(h,"_addListener"),z.prototype.addListener=U(function(v,j){return h(this,v,j,!1)},"addListener"),z.prototype.on=z.prototype.addListener,z.prototype.prependListener=U(function(v,j){return h(this,v,j,!0)},"prependListener");function _(){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(_,"onceWrapper");function D(v,j,A){var N={fired:!1,wrapFn:void 0,target:v,type:j,listener:A},b=_.bind(N);return b.listener=A,N.wrapFn=b,b}U(D,"_onceWrap"),z.prototype.once=U(function(v,j){return w(j),this.on(v,D(this,v,j)),this},"once"),z.prototype.prependOnceListener=U(function(v,j){return w(j),this.prependListener(v,D(this,v,j)),this},"prependOnceListener"),z.prototype.removeListener=U(function(v,j){var A,N,b,C,u;if(w(j),N=this._events,N===void 0)return this;if(A=N[v],A===void 0)return this;if(A===j||A.listener===j)--this._eventsCount===0?this._events=Object.create(null):(delete N[v],N.removeListener&&this.emit("removeListener",v,A.listener||j));else if(typeof A!="function"){for(b=-1,C=A.length-1;C>=0;C--)if(A[C]===j||A[C].listener===j){u=A[C].listener,b=C;break}if(b<0)return this;b===0?A.shift():f(A,b),A.length===1&&(N[v]=A[0]),N.removeListener!==void 0&&this.emit("removeListener",v,u||j)}return this},"removeListener"),z.prototype.off=z.prototype.removeListener,z.prototype.removeAllListeners=U(function(v){var j,A,N;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[v]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[v]),this;if(arguments.length===0){var b=Object.keys(A),C;for(N=0;N<b.length;++N)C=b[N],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(j=A[v],typeof j=="function")this.removeListener(v,j);else if(j!==void 0)for(N=j.length-1;N>=0;N--)this.removeListener(v,j[N]);return this},"removeAllListeners");function F(v,j,A){var N=v._events;if(N===void 0)return[];var b=N[j];return b===void 0?[]:typeof b=="function"?A?[b.listener||b]:[b]:A?T(b):P(b,b.length)}U(F,"_listeners"),z.prototype.listeners=U(function(v){return F(this,v,!0)},"listeners"),z.prototype.rawListeners=U(function(v){return F(this,v,!1)},"rawListeners"),z.listenerCount=function(v,j){return typeof v.listenerCount=="function"?v.listenerCount(j):M.call(v,j)},z.prototype.listenerCount=M;function M(v){var j=this._events;if(j!==void 0){var A=j[v];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}U(M,"listenerCount"),z.prototype.eventNames=U(function(){return this._eventsCount>0?Z(this._events):[]},"eventNames");function P(v,j){for(var A=Array(j),N=0;N<j;++N)A[N]=v[N];return A}U(P,"arrayClone");function f(v,j){for(;j+1<v.length;j++)v[j]=v[j+1];v.pop()}U(f,"spliceOne");function T(v){for(var j=Array(v.length),A=0;A<j.length;++A)j[A]=v[A].listener||v[A];return j}U(T,"unwrapListeners");function S(v,j){return new Promise(function(A,N){function b(u){v.removeListener(j,C),N(u)}U(b,"errorListener");function C(){typeof v.removeListener=="function"&&v.removeListener("error",b),A([].slice.call(arguments))}U(C,"resolver"),Q(v,j,C,{once:!0}),j!=="error"&&q(v,b,{once:!0})})}U(S,"once");function q(v,j,A){typeof v.on=="function"&&Q(v,"error",j,A)}U(q,"addErrorHandlerIfEventEmitter");function Q(v,j,A,N){if(typeof v.on=="function")N.once?v.once(j,A):v.on(j,A);else if(typeof v.addEventListener=="function")v.addEventListener(j,U(function b(C){N.once&&v.removeEventListener(j,b),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}U(Q,"eventTargetAgnosticAddListener")}),c5={};_1(c5,{Socket:()=>V0,isIP:()=>u5});function u5(W){return 0}var q5,c6,A8,V0,Q8=tW(()=>{l(),q5=R0(F0(),1),U(u5,"isIP"),c6=/^[^.]+\./,A8=class W extends q5.EventEmitter{constructor(){super(...arguments);s(this,"opts",{}),s(this,"connecting",!1),s(this,"pending",!0),s(this,"writable",!0),s(this,"encrypted",!1),s(this,"authorized",!1),s(this,"destroyed",!1),s(this,"ws",null),s(this,"writeBuffer"),s(this,"tlsState",0),s(this,"tlsRead"),s(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($,k){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($,k):`${J}?address=${$}:${k}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,k,J){this.connecting=!0,J&&this.once("connect",J);let Z=U(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),X=U((z,V=!1)=>{z.binaryType="arraybuffer",z.addEventListener("error",(w)=>{this.emit("error",w),this.emit("close")}),z.addEventListener("message",(w)=>{if(this.tlsState===0){let R=t.from(w.data);this.emit("data",R)}}),z.addEventListener("close",()=>{this.emit("close")}),V?Z():z.addEventListener("open",Z)},"configureWebSocket"),G;try{G=this.wsProxyAddrForHost(k,typeof $=="string"?parseInt($,10):$)}catch(z){this.emit("error",z),this.emit("close");return}try{let z=(this.useSecureWebSocket?"wss:":"ws:")+"//"+G;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(z),X(this.ws);else try{this.ws=new WebSocket(z),X(this.ws)}catch{this.ws=new __unstable_WebSocket(z),X(this.ws)}}catch(z){let V=(this.useSecureWebSocket?"https:":"http:")+"//"+G;fetch(V,{headers:{Upgrade:"websocket"}}).then((w)=>{if(this.ws=w.webSocket,this.ws==null)throw z;this.ws.accept(),X(this.ws,!0)}).catch((w)=>{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: ${w}`)),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 k=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),Z=J.read.bind(J),X=this.rawWrite.bind(this),{read:G,write:z}=await this.subtls.startTls($,k,Z,X,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=G,this.tlsWrite=z,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 k=t.from($);this.emit("data",k)}}}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 k=new Uint8Array(this.writeBuffer.length+$.length);k.set(this.writeBuffer),k.set($,this.writeBuffer.length),this.writeBuffer=k}}write($,k="utf8",J=(Z)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=t.from($,k)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,k,J)}):(this.tlsWrite($),J()),!0)}end($=t.alloc(0),k="utf8",J=()=>{}){return this.write($,k,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},U(A8,"Socket"),s(A8,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:U((W,$,k)=>{let J;return k?.jwtAuth?J=W.replace(c6,"apiauth."):J=W.replace(c6,"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}),s(A8,"opts",{}),V0=A8}),l5={};_1(l5,{parse:()=>s6});function s6(W,$=!1){let{protocol:k}=new URL(W),J="http:"+W.substring(k.length),{username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,searchParams:h,hash:_}=new URL(J);X=decodeURIComponent(X),Z=decodeURIComponent(Z),w=decodeURIComponent(w);let D=Z+":"+X,F=$?Object.fromEntries(h.entries()):R;return{href:W,protocol:k,auth:D,username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,query:F,hash:_}}var i5=tW(()=>{l(),U(s6,"parse")}),p5=r((W)=>{l(),W.parse=function(Z,X){return new k(Z,X).parse()};var $=class Z{constructor(X,G){this.source=X,this.transform=G||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var X=this.source[this.position++];return X==="\\"?{value:this.source[this.position++],escaped:!0}:{value:X,escaped:!1}}record(X){this.recorded.push(X)}newEntry(X){var G;(this.recorded.length>0||X)&&(G=this.recorded.join(""),G==="NULL"&&!X&&(G=null),G!==null&&(G=this.transform(G)),this.entries.push(G),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var X=this.nextCharacter();if(X.value==="=")break}}parse(X){var G,z,V;for(this.consumeDimensions();!this.isEof();)if(G=this.nextCharacter(),G.value==="{"&&!V)this.dimension++,this.dimension>1&&(z=new Z(this.source.substr(this.position-1),this.transform),this.entries.push(z.parse(!0)),this.position+=z.position-2);else if(G.value==="}"&&!V){if(this.dimension--,!this.dimension&&(this.newEntry(),X))return this.entries}else G.value==='"'&&!G.escaped?(V&&this.newEntry(!0),V=!V):G.value===","&&!V?this.newEntry():this.record(G.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};U($,"ArrayParser");var k=$;function J(Z){return Z}U(J,"identity")}),t5=r((W,$)=>{l();var k=p5();$.exports={create:U(function(J,Z){return{parse:U(function(){return k.parse(J,Z)},"parse")}},"create")}}),Bk=r((W,$)=>{l();var k=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Z=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,X=/^-?infinity$/;$.exports=U(function(R){if(X.test(R))return Number(R.replace("i","I"));var h=k.exec(R);if(!h)return G(R)||null;var _=!!h[8],D=parseInt(h[1],10);_&&(D=V(D));var F=parseInt(h[2],10)-1,M=h[3],P=parseInt(h[4],10),f=parseInt(h[5],10),T=parseInt(h[6],10),S=h[7];S=S?1000*parseFloat(S):0;var q,Q=z(R);return Q!=null?(q=new Date(Date.UTC(D,F,M,P,f,T,S)),w(D)&&q.setUTCFullYear(D),Q!==0&&q.setTime(q.getTime()-Q)):(q=new Date(D,F,M,P,f,T,S),w(D)&&q.setFullYear(D)),q},"parseDate");function G(R){var h=J.exec(R);if(h){var _=parseInt(h[1],10),D=!!h[4];D&&(_=V(_));var F=parseInt(h[2],10)-1,M=h[3],P=new Date(_,F,M);return w(_)&&P.setFullYear(_),P}}U(G,"getDate");function z(R){if(R.endsWith("+00"))return 0;var h=Z.exec(R.split(" ")[1]);if(h){var _=h[1];if(_==="Z")return 0;var D=_==="-"?-1:1,F=parseInt(h[2],10)*3600+parseInt(h[3]||0,10)*60+parseInt(h[4]||0,10);return F*D*1000}}U(z,"timeZoneOffset");function V(R){return-(R-1)}U(V,"bcYearToNegativeYear");function w(R){return R>=0&&R<100}U(w,"is0To99")}),Ik=r((W,$)=>{l(),$.exports=J;var k=Object.prototype.hasOwnProperty;function J(Z){for(var X=1;X<arguments.length;X++){var G=arguments[X];for(var z in G)k.call(G,z)&&(Z[z]=G[z])}return Z}U(J,"extend")}),yk=r((W,$)=>{l();var k=Ik();$.exports=J;function J(T){if(!(this instanceof J))return new J(T);k(this,f(T))}U(J,"PostgresInterval");var Z=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var T=Z.filter(this.hasOwnProperty,this);return this.milliseconds&&T.indexOf("seconds")<0&&T.push("seconds"),T.length===0?"0":T.map(function(S){var q=this[S]||0;return S==="seconds"&&this.milliseconds&&(q=(q+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),q+" "+S},this).join(" ")};var X={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},G=["years","months","days"],z=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var T=G.map(q,this).join(""),S=z.map(q,this).join("");return"P"+T+"T"+S;function q(Q){var v=this[Q]||0;return Q==="seconds"&&this.milliseconds&&(v=(v+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),v+X[Q]}};var V="([+-]?\\d+)",w=V+"\\s+years?",R=V+"\\s+mons?",h=V+"\\s+days?",_="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",D=new RegExp([w,R,h,_].map(function(T){return"("+T+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},M=["hours","minutes","seconds","milliseconds"];function P(T){var S=T+"000000".slice(T.length);return parseInt(S,10)/1000}U(P,"parseMilliseconds");function f(T){if(!T)return{};var S=D.exec(T),q=S[8]==="-";return Object.keys(F).reduce(function(Q,v){var j=F[v],A=S[j];return!A||(A=v==="milliseconds"?P(A):parseInt(A,10),!A)||(q&&~M.indexOf(v)&&(A*=-1),Q[v]=A),Q},{})}U(f,"parse")}),gk=r((W,$)=>{l(),$.exports=U(function(k){if(/^\\x/.test(k))return new t(k.substr(2),"hex");for(var J="",Z=0;Z<k.length;)if(k[Z]!=="\\")J+=k[Z],++Z;else if(/[0-7]{3}/.test(k.substr(Z+1,3)))J+=String.fromCharCode(parseInt(k.substr(Z+1,3),8)),Z+=4;else{for(var X=1;Z+X<k.length&&k[Z+X]==="\\";)X++;for(var G=0;G<Math.floor(X/2);++G)J+="\\";Z+=Math.floor(X/2)*2}return new t(J,"binary")},"parseBytea")}),mk=r((W,$)=>{l();var k=p5(),J=t5(),Z=Bk(),X=yk(),G=gk();function z(N){return U(function(b){return b===null?b:N(b)},"nullAllowed")}U(z,"allowNull");function V(N){return N===null?N:N==="TRUE"||N==="t"||N==="true"||N==="y"||N==="yes"||N==="on"||N==="1"}U(V,"parseBool");function w(N){return N?k.parse(N,V):null}U(w,"parseBoolArray");function R(N){return parseInt(N,10)}U(R,"parseBaseTenInt");function h(N){return N?k.parse(N,z(R)):null}U(h,"parseIntegerArray");function _(N){return N?k.parse(N,z(function(b){return q(b).trim()})):null}U(_,"parseBigIntegerArray");var D=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=v(C)),C});return b.parse()},"parsePointArray"),F=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=parseFloat(C)),C});return b.parse()},"parseFloatArray"),M=U(function(N){if(!N)return null;var b=J.create(N);return b.parse()},"parseStringArray"),P=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=Z(C)),C});return b.parse()},"parseDateArray"),f=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=X(C)),C});return b.parse()},"parseIntervalArray"),T=U(function(N){return N?k.parse(N,z(G)):null},"parseByteAArray"),S=U(function(N){return parseInt(N,10)},"parseInteger"),q=U(function(N){var b=String(N);return/^\d+$/.test(b)?b:N},"parseBigInteger"),Q=U(function(N){return N?k.parse(N,z(JSON.parse)):null},"parseJsonArray"),v=U(function(N){return N[0]!=="("?null:(N=N.substring(1,N.length-1).split(","),{x:parseFloat(N[0]),y:parseFloat(N[1])})},"parsePoint"),j=U(function(N){if(N[0]!=="<"&&N[1]!=="(")return null;for(var b="(",C="",u=!1,c=2;c<N.length-1;c++){if(u||(b+=N[c]),N[c]===")"){u=!0;continue}else if(!u)continue;N[c]!==","&&(C+=N[c])}var B=v(b);return B.radius=parseFloat(C),B},"parseCircle"),A=U(function(N){N(20,q),N(21,S),N(23,S),N(26,S),N(700,parseFloat),N(701,parseFloat),N(16,V),N(1082,Z),N(1114,Z),N(1184,Z),N(600,v),N(651,M),N(718,j),N(1000,w),N(1001,T),N(1005,h),N(1007,h),N(1028,h),N(1016,_),N(1017,D),N(1021,F),N(1022,F),N(1231,F),N(1014,M),N(1015,M),N(1008,M),N(1009,M),N(1040,M),N(1041,M),N(1115,P),N(1182,P),N(1185,P),N(1186,X),N(1187,f),N(17,G),N(114,JSON.parse.bind(JSON)),N(3802,JSON.parse.bind(JSON)),N(199,Q),N(3807,Q),N(3907,M),N(2951,M),N(791,M),N(1183,M),N(1270,M)},"init");$.exports={init:A}}),ck=r((W,$)=>{l();var k=1e6;function J(Z){var X=Z.readInt32BE(0),G=Z.readUInt32BE(4),z="";X<0&&(X=~X+(G===0),G=~G+1>>>0,z="-");var V="",w,R,h,_,D,F;{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}return w=X%k,R=4294967296*w+G,h=""+R%k,z+h+V}U(J,"readInt8"),$.exports=J}),uk=r((W,$)=>{l();var k=ck(),J=U(function(M,P,f,T,S){f=f||0,T=T||!1,S=S||function(u,c,B){return u*Math.pow(2,B)+c};var q=f>>3,Q=U(function(u){return T?~u&255:u},"inv"),v=255,j=8-f%8;P<j&&(v=255<<8-P&255,j=P),f&&(v=v>>f%8);var A=0;f%8+P>=8&&(A=S(0,Q(M[q])&v,j));for(var N=P+f>>3,b=q+1;b<N;b++)A=S(A,Q(M[b]),8);var C=(P+f)%8;return C>0&&(A=S(A,Q(M[N])>>8-C,C)),A},"parseBits"),Z=U(function(M,P,f){var T=Math.pow(2,f-1)-1,S=J(M,1),q=J(M,f,1);if(q===0)return 0;var Q=1,v=U(function(A,N,b){A===0&&(A=1);for(var C=1;C<=b;C++)Q/=2,(N&1<<b-C)>0&&(A+=Q);return A},"parsePrecisionBits"),j=J(M,P,f+1,!1,v);return q==Math.pow(2,f+1)-1?j===0?S===0?1/0:-1/0:NaN:(S===0?1:-1)*Math.pow(2,q-T)*j},"parseFloatFromBits"),X=U(function(M){return J(M,1)==1?-1*(J(M,15,1,!0)+1):J(M,15,1)},"parseInt16"),G=U(function(M){return J(M,1)==1?-1*(J(M,31,1,!0)+1):J(M,31,1)},"parseInt32"),z=U(function(M){return Z(M,23,8)},"parseFloat32"),V=U(function(M){return Z(M,52,11)},"parseFloat64"),w=U(function(M){var P=J(M,16,32);if(P==49152)return NaN;for(var f=Math.pow(1e4,J(M,16,16)),T=0,S=[],q=J(M,16),Q=0;Q<q;Q++)T+=J(M,16,64+16*Q)*f,f/=1e4;var v=Math.pow(10,J(M,16,48));return(P===0?1:-1)*Math.round(T*v)/v},"parseNumeric"),R=U(function(M,P){var f=J(P,1),T=J(P,63,1),S=new Date((f===0?1:-1)*T/1000+946684800000);return M||S.setTime(S.getTime()+S.getTimezoneOffset()*60000),S.usec=T%1000,S.getMicroSeconds=function(){return this.usec},S.setMicroSeconds=function(q){this.usec=q},S.getUTCMicroSeconds=function(){return this.usec},S},"parseDate"),h=U(function(M){for(var P=J(M,32),f=J(M,32,32),T=J(M,32,64),S=96,q=[],Q=0;Q<P;Q++)q[Q]=J(M,32,S),S+=32,S+=32;var v=U(function(A){var N=J(M,32,S);if(S+=32,N==4294967295)return null;var b;if(A==23||A==20)return b=J(M,N*8,S),S+=N*8,b;if(A==25)return b=M.toString(this.encoding,S>>3,(S+=N<<3)>>3),b;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),j=U(function(A,N){var b=[],C;if(A.length>1){var u=A.shift();for(C=0;C<u;C++)b[C]=j(A,N);A.unshift(u)}else for(C=0;C<A[0];C++)b[C]=v(N);return b},"parse");return j(q,T)},"parseArray"),_=U(function(M){return M.toString("utf8")},"parseText"),D=U(function(M){return M===null?null:J(M,8)>0},"parseBool"),F=U(function(M){M(20,k),M(21,X),M(23,G),M(26,G),M(1700,w),M(700,z),M(701,V),M(16,D),M(1114,R.bind(null,!1)),M(1184,R.bind(null,!0)),M(1000,h),M(1007,h),M(1016,h),M(1008,h),M(1009,h),M(25,_)},"init");$.exports={init:F}}),lk=r((W,$)=>{l(),$.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}}),f4=r((W)=>{l();var $=mk(),k=uk(),J=t5(),Z=lk();W.getTypeParser=z,W.setTypeParser=V,W.arrayParser=J,W.builtins=Z;var X={text:{},binary:{}};function G(w){return String(w)}U(G,"noParse");function z(w,R){return R=R||"text",X[R]&&X[R][w]||G}U(z,"getTypeParser");function V(w,R,h){typeof R=="function"&&(h=R,R="text"),X[R][w]=h}U(V,"setTypeParser"),$.init(function(w,R){X.text[w]=R}),k.init(function(w,R){X.binary[w]=R})}),a6=r((W,$)=>{l();var k=f4();function J(Z){this._types=Z||k,this.text={},this.binary={}}U(J,"TypeOverrides"),J.prototype.getOverrides=function(Z){switch(Z){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(Z,X,G){typeof X=="function"&&(G=X,X="text"),this.getOverrides(X)[Z]=G},J.prototype.getTypeParser=function(Z,X){return X=X||"text",this.getOverrides(X)[Z]||this._types.getTypeParser(Z,X)},$.exports=J});function C8(W){let $=1779033703,k=3144134277,J=1013904242,Z=2773480762,X=1359893119,G=2600822924,z=528734635,V=1541459225,w=0,R=0,h=[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],_=U((T,S)=>T>>>S|T<<32-S,"rrot"),D=new Uint32Array(64),F=new Uint8Array(64),M=U(()=>{for(let b=0,C=0;b<16;b++,C+=4)D[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[b-15],7)^_(D[b-15],18)^D[b-15]>>>3,u=_(D[b-2],17)^_(D[b-2],19)^D[b-2]>>>10;D[b]=D[b-16]+C+D[b-7]+u|0}let T=$,S=k,q=J,Q=Z,v=X,j=G,A=z,N=V;for(let b=0;b<64;b++){let C=_(v,6)^_(v,11)^_(v,25),u=v&j^~v&A,c=N+C+u+h[b]+D[b]|0,B=_(T,2)^_(T,13)^_(T,22),m=T&S^T&q^S&q,p=B+m|0;N=A,A=j,j=v,v=Q+c|0,Q=q,q=S,S=T,T=c+p|0}$=$+T|0,k=k+S|0,J=J+q|0,Z=Z+Q|0,X=X+v|0,G=G+j|0,z=z+A|0,V=V+N|0,R=0},"process"),P=U((T)=>{typeof T=="string"&&(T=new TextEncoder().encode(T));for(let S=0;S<T.length;S++)F[R++]=T[S],R===64&&M();w+=T.length},"add"),f=U(()=>{if(F[R++]=128,R==64&&M(),R+8>64){for(;R<64;)F[R++]=0;M()}for(;R<58;)F[R++]=0;let T=w*8;F[R++]=T/1099511627776&255,F[R++]=T/4294967296&255,F[R++]=T>>>24,F[R++]=T>>>16&255,F[R++]=T>>>8&255,F[R++]=T&255,M();let S=new Uint8Array(32);return S[0]=$>>>24,S[1]=$>>>16&255,S[2]=$>>>8&255,S[3]=$&255,S[4]=k>>>24,S[5]=k>>>16&255,S[6]=k>>>8&255,S[7]=k&255,S[8]=J>>>24,S[9]=J>>>16&255,S[10]=J>>>8&255,S[11]=J&255,S[12]=Z>>>24,S[13]=Z>>>16&255,S[14]=Z>>>8&255,S[15]=Z&255,S[16]=X>>>24,S[17]=X>>>16&255,S[18]=X>>>8&255,S[19]=X&255,S[20]=G>>>24,S[21]=G>>>16&255,S[22]=G>>>8&255,S[23]=G&255,S[24]=z>>>24,S[25]=z>>>16&255,S[26]=z>>>8&255,S[27]=z&255,S[28]=V>>>24,S[29]=V>>>16&255,S[30]=V>>>8&255,S[31]=V&255,S},"digest");return W===void 0?{add:P,digest:f}:(P(W),f())}var ik=tW(()=>{l(),U(C8,"sha256")}),c1,l6,pk=tW(()=>{l(),c1=class W{constructor(){s(this,"_dataLength",0),s(this,"_bufferLength",0),s(this,"_state",new Int32Array(4)),s(this,"_buffer",new ArrayBuffer(68)),s(this,"_buffer8"),s(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,k=!1){return this.onePassHasher.start().appendByteArray($).end(k)}static hashStr($,k=!1){return this.onePassHasher.start().appendStr($).end(k)}static hashAsciiStr($,k=!1){return this.onePassHasher.start().appendAsciiStr($).end(k)}static _hex($){let{hexChars:k,hexOut:J}=W,Z,X,G,z;for(z=0;z<4;z+=1)for(X=z*8,Z=$[z],G=0;G<8;G+=2)J[X+1+G]=k.charAt(Z&15),Z>>>=4,J[X+0+G]=k.charAt(Z&15),Z>>>=4;return J.join("")}static _md5cycle($,k){let J=$[0],Z=$[1],X=$[2],G=$[3];J+=(Z&X|~Z&G)+k[0]-680876936|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[1]-389564586|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[2]+606105819|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[3]-1044525330|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[4]-176418897|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[5]+1200080426|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[6]-1473231341|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[7]-45705983|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[8]+1770035416|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[9]-1958414417|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[10]-42063|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[11]-1990404162|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[12]+1804603682|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[13]-40341101|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[14]-1502002290|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[15]+1236535329|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&G|X&~G)+k[1]-165796510|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[6]-1069501632|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[11]+643717713|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[0]-373897302|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[5]-701558691|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[10]+38016083|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[15]-660478335|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[4]-405537848|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[9]+568446438|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[14]-1019803690|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[3]-187363961|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[8]+1163531501|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[13]-1444681467|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[2]-51403784|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[7]+1735328473|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[12]-1926607734|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z^X^G)+k[5]-378558|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[8]-2022574463|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[11]+1839030562|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[14]-35309556|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[1]-1530992060|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[4]+1272893353|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[7]-155497632|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[10]-1094730640|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[13]+681279174|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[0]-358537222|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[3]-722521979|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[6]+76029189|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[9]-640364487|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[12]-421815835|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[15]+530742520|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[2]-995338651|0,Z=(Z<<23|Z>>>9)+X|0,J+=(X^(Z|~G))+k[0]-198630844|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[7]+1126891415|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[14]-1416354905|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[5]-57434055|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[12]+1700485571|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[3]-1894986606|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[10]-1051523|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[1]-2054922799|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[8]+1873313359|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[15]-30611744|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[6]-1560198380|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[13]+1309151649|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[4]-145523070|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[11]-1120210379|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[2]+718787259|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[9]-343485551|0,Z=(Z<<21|Z>>>11)+X|0,$[0]=J+$[0]|0,$[1]=Z+$[1]|0,$[2]=X+$[2]|0,$[3]=G+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G;for(G=0;G<$.length;G+=1){if(X=$.charCodeAt(G),X<128)k[Z++]=X;else if(X<2048)k[Z++]=(X>>>6)+192,k[Z++]=X&63|128;else if(X<55296||X>56319)k[Z++]=(X>>>12)+224,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128;else{if(X=(X-55296)*1024+($.charCodeAt(++G)-56320)+65536,X>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");k[Z++]=(X>>>18)+240,k[Z++]=X>>>12&63|128,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128}Z>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),Z-=64,J[0]=J[16])}return this._bufferLength=Z,this}appendAsciiStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$.charCodeAt(G++);if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,this}appendByteArray($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$[G++];if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,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:k,state:J}=$,Z=this._state,X;for(this._dataLength=$.length,this._bufferLength=$.buflen,Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[3],X=0;X<k.length;X+=1)this._buffer8[X]=k.charCodeAt(X)}end($=!1){let k=this._bufferLength,J=this._buffer8,Z=this._buffer32,X=(k>>2)+1;this._dataLength+=k;let G=this._dataLength*8;if(J[k]=128,J[k+1]=J[k+2]=J[k+3]=0,Z.set(W.buffer32Identity.subarray(X),X),k>55&&(W._md5cycle(this._state,Z),Z.set(W.buffer32Identity)),G<=4294967295)Z[14]=G;else{let z=G.toString(16).match(/(.*?)(.{0,8})$/);if(z===null)return;let V=parseInt(z[2],16),w=parseInt(z[1],16)||0;Z[14]=V,Z[15]=w}return W._md5cycle(this._state,Z),$?this._state:W._hex(this._state)}},U(c1,"Md5"),s(c1,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),s(c1,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),s(c1,"hexChars","0123456789abcdef"),s(c1,"hexOut",[]),s(c1,"onePassHasher",new c1),l6=c1}),d6={};_1(d6,{createHash:()=>a5,createHmac:()=>d5,randomBytes:()=>s5});function s5(W){return crypto.getRandomValues(t.alloc(W))}function a5(W){if(W==="sha256")return{update:U(function($){return{digest:U(function(){return t.from(C8($))},"digest")}},"update")};if(W==="md5")return{update:U(function($){return{digest:U(function(){return typeof $=="string"?l6.hashStr($):l6.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function d5(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:U(function(k){return{digest:U(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof k=="string"&&(k=new TextEncoder().encode(k));let J=$.length;if(J>64)$=C8($);else if(J<64){let V=new Uint8Array(64);V.set($),$=V}let Z=new Uint8Array(64),X=new Uint8Array(64);for(let V=0;V<64;V++)Z[V]=54^$[V],X[V]=92^$[V];let G=new Uint8Array(k.length+64);G.set(Z,0),G.set(k,64);let z=new Uint8Array(96);return z.set(X,0),z.set(C8(G),64),t.from(C8(z))},"digest")}},"update")}}var n5=tW(()=>{l(),ik(),pk(),U(s5,"randomBytes"),U(a5,"createHash"),U(d5,"createHmac")}),T4=r((W,$)=>{l(),$.exports={host:"localhost",user:o.platform==="win32"?o.env.USERNAME:o.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 k=f4(),J=k.getTypeParser(20,"text"),Z=k.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(X){k.setTypeParser(20,"text",X?k.getTypeParser(23,"text"):J),k.setTypeParser(1016,"text",X?k.getTypeParser(1007,"text"):Z)})}),v4=r((W,$)=>{l();var k=(n5(),QW(d6)),J=T4();function Z(F){var M=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+M+'"'}U(Z,"escapeElement");function X(F){for(var M="{",P=0;P<F.length;P++)P>0&&(M=M+","),F[P]===null||typeof F[P]>"u"?M=M+"NULL":Array.isArray(F[P])?M=M+X(F[P]):F[P]instanceof t?M+="\\\\x"+F[P].toString("hex"):M+=Z(G(F[P]));return M=M+"}",M}U(X,"arrayString");var G=U(function(F,M){if(F==null)return null;if(F instanceof t)return F;if(ArrayBuffer.isView(F)){var P=t.from(F.buffer,F.byteOffset,F.byteLength);return P.length===F.byteLength?P:P.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?R(F):w(F):Array.isArray(F)?X(F):typeof F=="object"?z(F,M):F.toString()},"prepareValue");function z(F,M){if(F&&typeof F.toPostgres=="function"){if(M=M||[],M.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return M.push(F),G(F.toPostgres(G),M)}return JSON.stringify(F)}U(z,"prepareObject");function V(F,M){for(F=""+F;F.length<M;)F="0"+F;return F}U(V,"pad");function w(F){var M=-F.getTimezoneOffset(),P=F.getFullYear(),f=P<1;f&&(P=Math.abs(P)+1);var T=V(P,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 M<0?(T+="-",M*=-1):T+="+",T+=V(Math.floor(M/60),2)+":"+V(M%60,2),f&&(T+=" BC"),T}U(w,"dateToString");function R(F){var M=F.getUTCFullYear(),P=M<1;P&&(M=Math.abs(M)+1);var f=V(M,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 f+="+00:00",P&&(f+=" BC"),f}U(R,"dateToStringUTC");function h(F,M,P){return F=typeof F=="string"?{text:F}:F,M&&(typeof M=="function"?F.callback=M:F.values=M),P&&(F.callback=P),F}U(h,"normalizeQueryConfig");var _=U(function(F){return k.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),D=U(function(F,M,P){var f=_(M+F),T=_(t.concat([t.from(f),P]));return"md5"+T},"postgresMd5PasswordHash");$.exports={prepareValue:U(function(F){return G(F)},"prepareValueWrapper"),normalizeQueryConfig:h,postgresMd5PasswordHash:D,md5:_}}),x8={};_1(x8,{default:()=>o5});var o5,E4=tW(()=>{l(),o5={}}),tk=r((W,$)=>{l();var k=(n5(),QW(d6));function J(M){if(M.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let P=k.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:P,response:"n,,n=*,r="+P,message:"SASLInitialResponse"}}U(J,"startSession");function Z(M,P,f){if(M.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof f!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let T=w(f);if(T.nonce.startsWith(M.clientNonce)){if(T.nonce.length===M.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 S=t.from(T.salt,"base64"),q=F(P,S,T.iteration),Q=D(q,"Client Key"),v=_(Q),j="n=*,r="+M.clientNonce,A="r="+T.nonce+",s="+T.salt+",i="+T.iteration,N="c=biws,r="+T.nonce,b=j+","+A+","+N,C=D(v,b),u=h(Q,C),c=u.toString("base64"),B=D(q,"Server Key"),m=D(B,b);M.message="SASLResponse",M.serverSignature=m.toString("base64"),M.response=N+",p="+c}U(Z,"continueSession");function X(M,P){if(M.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:f}=R(P);if(f!==M.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}U(X,"finalizeSession");function G(M){if(typeof M!="string")throw TypeError("SASL: text must be a string");return M.split("").map((P,f)=>M.charCodeAt(f)).every((P)=>P>=33&&P<=43||P>=45&&P<=126)}U(G,"isPrintableChars");function z(M){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(M)}U(z,"isBase64");function V(M){if(typeof M!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(M.split(",").map((P)=>{if(!/^.=/.test(P))throw Error("SASL: Invalid attribute pair entry");let f=P[0],T=P.substring(2);return[f,T]}))}U(V,"parseAttributePairs");function w(M){let P=V(M),f=P.get("r");if(f){if(!G(f))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let T=P.get("s");if(T){if(!z(T))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let S=P.get("i");if(S){if(!/^[1-9][0-9]*$/.test(S))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let q=parseInt(S,10);return{nonce:f,salt:T,iteration:q}}U(w,"parseServerFirstMessage");function R(M){let P=V(M).get("v");if(P){if(!z(P))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:P}}U(R,"parseServerFinalMessage");function h(M,P){if(!t.isBuffer(M))throw TypeError("first argument must be a Buffer");if(!t.isBuffer(P))throw TypeError("second argument must be a Buffer");if(M.length!==P.length)throw Error("Buffer lengths must match");if(M.length===0)throw Error("Buffers cannot be empty");return t.from(M.map((f,T)=>M[T]^P[T]))}U(h,"xorBuffers");function _(M){return k.createHash("sha256").update(M).digest()}U(_,"sha256");function D(M,P){return k.createHmac("sha256",M).update(P).digest()}U(D,"hmacSha256");function F(M,P,f){for(var T=D(M,t.concat([P,t.from([0,0,0,1])])),S=T,q=0;q<f-1;q++)T=D(M,T),S=h(S,T);return S}U(F,"Hi"),$.exports={startSession:J,continueSession:Z,finalizeSession:X}}),n6={};_1(n6,{join:()=>r5});function r5(...W){return W.join("/")}var e5=tW(()=>{l(),U(r5,"join")}),o6={};_1(o6,{stat:()=>W7});function W7(W,$){$(Error("No filesystem"))}var $7=tW(()=>{l(),U(W7,"stat")}),r6={};_1(r6,{default:()=>k7});var k7,J7=tW(()=>{l(),k7={}}),Z7={};_1(Z7,{StringDecoder:()=>X7});var u6,X7,sk=tW(()=>{l(),u6=class{constructor($){s(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},U(u6,"StringDecoder"),X7=u6}),ak=r((W,$)=>{l();var{Transform:k}=(J7(),QW(r6)),{StringDecoder:J}=(sk(),QW(Z7)),Z=Symbol("last"),X=Symbol("decoder");function G(h,_,D){let F;if(this.overflow){if(F=this[X].write(h).split(this.matcher),F.length===1)return D();F.shift(),this.overflow=!1}else this[Z]+=this[X].write(h),F=this[Z].split(this.matcher);this[Z]=F.pop();for(let M=0;M<F.length;M++)try{V(this,this.mapper(F[M]))}catch(P){return D(P)}if(this.overflow=this[Z].length>this.maxLength,this.overflow&&!this.skipOverflow){D(Error("maximum buffer reached"));return}D()}U(G,"transform");function z(h){if(this[Z]+=this[X].end(),this[Z])try{V(this,this.mapper(this[Z]))}catch(_){return h(_)}h()}U(z,"flush");function V(h,_){_!==void 0&&h.push(_)}U(V,"push");function w(h){return h}U(w,"noop");function R(h,_,D){switch(h=h||/\r?\n/,_=_||w,D=D||{},arguments.length){case 1:typeof h=="function"?(_=h,h=/\r?\n/):typeof h=="object"&&!(h instanceof RegExp)&&!h[Symbol.split]&&(D=h,h=/\r?\n/);break;case 2:typeof h=="function"?(D=_,_=h,h=/\r?\n/):typeof _=="object"&&(D=_,_=w)}D=Object.assign({},D),D.autoDestroy=!0,D.transform=G,D.flush=z,D.readableObjectMode=!0;let F=new k(D);return F[Z]="",F[X]=new J("utf8"),F.matcher=h,F.mapper=_,F.maxLength=D.maxLength,F.skipOverflow=D.skipOverflow||!1,F.overflow=!1,F._destroy=function(M,P){this._writableState.errorEmitted=!1,P(M)},F}U(R,"split"),$.exports=R}),dk=r((W,$)=>{l();var k=(e5(),QW(n6)),J=(J7(),QW(r6)).Stream,Z=ak(),X=(E4(),QW(x8)),G=5432,z=o.platform==="win32",V=o.stderr,w=56,R=7,h=61440,_=32768;function D(Q){return(Q&h)==_}U(D,"isRegFile");var F=["host","port","database","user","password"],M=F.length,P=F[M-1];function f(){var Q=V instanceof J&&V.writable===!0;if(Q){var v=Array.prototype.slice.call(arguments).concat(`
27
28
  `);V.write(X.format.apply(X,v))}}U(f,"warn"),Object.defineProperty($.exports,"isWin",{get:U(function(){return z},"get"),set:U(function(Q){z=Q},"set")}),$.exports.warnTo=function(Q){var v=V;return V=Q,v},$.exports.getFileName=function(Q){var v=Q||o.env,j=v.PGPASSFILE||(z?k.join(v.APPDATA||"./","postgresql","pgpass.conf"):k.join(v.HOME||"./",".pgpass"));return j},$.exports.usePgPass=function(Q,v){return Object.prototype.hasOwnProperty.call(o.env,"PGPASSWORD")?!1:z?!0:(v=v||"<unkn>",D(Q.mode)?Q.mode&(w|R)?(f('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',v),!1):!0:(f('WARNING: password file "%s" is not a plain file',v),!1))};var T=$.exports.match=function(Q,v){return F.slice(0,-1).reduce(function(j,A,N){return N==1&&Number(Q[A]||G)===Number(v[A])?j&&!0:j&&(v[A]==="*"||v[A]===Q[A])},!0)};$.exports.getPassword=function(Q,v,j){var A,N=v.pipe(Z());function b(c){var B=S(c);B&&q(B)&&T(Q,B)&&(A=B[P],N.end())}U(b,"onLine");var C=U(function(){v.destroy(),j(A)},"onEnd"),u=U(function(c){v.destroy(),f("WARNING: error on reading file: %s",c),j(void 0)},"onErr");v.on("error",u),N.on("data",b).on("end",C).on("error",u)};var S=$.exports.parseLine=function(Q){if(Q.length<11||Q.match(/^\s+#/))return null;for(var v="",j="",A=0,N=0,b=0,C={},u=!1,c=U(function(m,p,a){var JW=Q.substring(p,a);Object.hasOwnProperty.call(o.env,"PGPASS_NO_DEESCAPE")||(JW=JW.replace(/\\([:\\])/g,"$1")),C[F[m]]=JW},"addToObj"),B=0;B<Q.length-1;B+=1){if(v=Q.charAt(B+1),j=Q.charAt(B),u=A==M-1,u){c(A,N);break}B>=0&&v==":"&&j!=="\\"&&(c(A,N,B+1),N=B+2,A+=1)}return C=Object.keys(C).length===M?C:null,C},q=$.exports.isValidEntry=function(Q){for(var v={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}},j=0;j<F.length;j+=1){var A=v[j],N=Q[F[j]]||"",b=A(N);if(!b)return!1}return!0}}),nk=r((W,$)=>{l();var k=(e5(),QW(n6)),J=($7(),QW(o6)),Z=dk();$.exports=function(X,G){var z=Z.getFileName();J.stat(z,function(V,w){if(V||!Z.usePgPass(w,z))return G(void 0);var R=J.createReadStream(z);Z.getPassword(X,R,G)})},$.exports.warnTo=Z.warnTo}),Y7={};_1(Y7,{default:()=>H7});var H7,ok=tW(()=>{l(),H7={}}),rk=r((W,$)=>{l();var k=(i5(),QW(l5)),J=($7(),QW(o6));function Z(X){if(X.charAt(0)==="/"){var z=X.split(" ");return{host:z[0],database:z[1]}}var G=k.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(X)?encodeURI(X).replace(/\%25(\d\d)/g,"%$1"):X,!0),z=G.query;for(var V in z)Array.isArray(z[V])&&(z[V]=z[V][z[V].length-1]);var w=(G.auth||":").split(":");if(z.user=w[0],z.password=w.splice(1).join(":"),z.port=G.port,G.protocol=="socket:")return z.host=decodeURI(G.pathname),z.database=G.query.db,z.client_encoding=G.query.encoding,z;z.host||(z.host=G.hostname);var R=G.pathname;if(!z.host&&R&&/^%2f/i.test(R)){var h=R.split("/");z.host=decodeURIComponent(h[0]),R=h.splice(1).join("/")}switch(R&&R.charAt(0)==="/"&&(R=R.slice(1)||null),z.database=R&&decodeURI(R),(z.ssl==="true"||z.ssl==="1")&&(z.ssl=!0),z.ssl==="0"&&(z.ssl=!1),(z.sslcert||z.sslkey||z.sslrootcert||z.sslmode)&&(z.ssl={}),z.sslcert&&(z.ssl.cert=J.readFileSync(z.sslcert).toString()),z.sslkey&&(z.ssl.key=J.readFileSync(z.sslkey).toString()),z.sslrootcert&&(z.ssl.ca=J.readFileSync(z.sslrootcert).toString()),z.sslmode){case"disable":{z.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{z.ssl.rejectUnauthorized=!1;break}}return z}U(Z,"parse"),$.exports=Z,Z.parse=Z}),e6=r((W,$)=>{l();var k=(ok(),QW(Y7)),J=T4(),Z=rk().parse,X=U(function(h,_,D){return D===void 0?D=o.env["PG"+h.toUpperCase()]:D===!1||(D=o.env[D]),_[h]||D||J[h]},"val"),G=U(function(){switch(o.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"),z=U(function(h){return"'"+(""+h).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),V=U(function(h,_,D){var F=_[D];F!=null&&h.push(D+"="+z(F))},"add"),w=class{constructor(_){_=typeof _=="string"?Z(_):_||{},_.connectionString&&(_=Object.assign({},_,Z(_.connectionString))),this.user=X("user",_),this.database=X("database",_),this.database===void 0&&(this.database=this.user),this.port=parseInt(X("port",_),10),this.host=X("host",_),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:X("password",_)}),this.binary=X("binary",_),this.options=X("options",_),this.ssl=typeof _.ssl>"u"?G():_.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=X("client_encoding",_),this.replication=X("replication",_),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=X("application_name",_,"PGAPPNAME"),this.fallback_application_name=X("fallback_application_name",_,!1),this.statement_timeout=X("statement_timeout",_,!1),this.lock_timeout=X("lock_timeout",_,!1),this.idle_in_transaction_session_timeout=X("idle_in_transaction_session_timeout",_,!1),this.query_timeout=X("query_timeout",_,!1),_.connectionTimeoutMillis===void 0?this.connect_timeout=o.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(_.connectionTimeoutMillis/1000),_.keepAlive===!1?this.keepalives=0:_.keepAlive===!0&&(this.keepalives=1),typeof _.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(_.keepAliveInitialDelayMillis/1000))}getLibpqConnectionString(_){var D=[];V(D,this,"user"),V(D,this,"password"),V(D,this,"port"),V(D,this,"application_name"),V(D,this,"fallback_application_name"),V(D,this,"connect_timeout"),V(D,this,"options");var F=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(V(D,F,"sslmode"),V(D,F,"sslca"),V(D,F,"sslkey"),V(D,F,"sslcert"),V(D,F,"sslrootcert"),this.database&&D.push("dbname="+z(this.database)),this.replication&&D.push("replication="+z(this.replication)),this.host&&D.push("host="+z(this.host)),this.isDomainSocket)return _(null,D.join(" "));this.client_encoding&&D.push("client_encoding="+z(this.client_encoding)),k.lookup(this.host,function(M,P){return M?_(M,null):(D.push("hostaddr="+z(P)),_(null,D.join(" ")))})}};U(w,"ConnectionParameters");var R=w;$.exports=R}),ek=r((W,$)=>{l();var k=f4(),J=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Z=class{constructor(z,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=z==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(z){var V;z.text?V=J.exec(z.text):V=J.exec(z.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(z){for(var V=Array(z.length),w=0,R=z.length;w<R;w++){var h=z[w];h!==null?V[w]=this._parsers[w](h):V[w]=null}return V}parseRow(z){for(var V={},w=0,R=z.length;w<R;w++){var h=z[w],_=this.fields[w].name;h!==null?V[_]=this._parsers[w](h):V[_]=null}return V}addRow(z){this.rows.push(z)}addFields(z){this.fields=z,this.fields.length&&(this._parsers=Array(z.length));for(var V=0;V<z.length;V++){var w=z[V];this._types?this._parsers[V]=this._types.getTypeParser(w.dataTypeID,w.format||"text"):this._parsers[V]=k.getTypeParser(w.dataTypeID,w.format||"text")}}};U(Z,"Result");var X=Z;$.exports=X}),W2=r((W,$)=>{l();var{EventEmitter:k}=F0(),J=ek(),Z=v4(),X=class extends k{constructor(V,w,R){super(),V=Z.normalizeQueryConfig(V,w,R),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,o.domain&&V.callback&&(this.callback=o.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 w;if(!this._canceledDueToError){try{w=this._result.parseRow(V.fields)}catch(R){this._canceledDueToError=R;return}this.emit("row",w,this._result),this._accumulateRows&&this._result.addRow(w)}}handleCommandComplete(V,w){this._checkForMultirow(),this._result.addCommandComplete(V),this.rows&&w.sync()}handleEmptyQuery(V){this.rows&&V.sync()}handleError(V,w){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(w){o.nextTick(()=>{throw w})}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 w=V.parsedStatements[this.name];return this.text&&w&&this.text!==w?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,w){V.execute({portal:this.portal,rows:w}),w?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:Z.prepareValue})}catch(w){this.handleError(w,V);return}V.describe({type:"P",name:this.portal||""}),this._getRows(V,this.rows)}handleCopyInResponse(V){V.sendCopyFail("No source stream defined")}handleCopyData(V,w){}};U(X,"Query");var G=X;$.exports=G}),z7=r((W)=>{l(),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,m,p){super(B),this.length=m,this.name=p}};U($,"DatabaseError");var k=$;W.DatabaseError=k;var J=class{constructor(B,m){this.length=B,this.chunk=m,this.name="copyData"}};U(J,"CopyDataMessage");var Z=J;W.CopyDataMessage=Z;var X=class{constructor(B,m,p,a){this.length=B,this.name=m,this.binary=p,this.columnTypes=Array(a)}};U(X,"CopyResponse");var G=X;W.CopyResponse=G;var z=class{constructor(B,m,p,a,JW,n,sW){this.name=B,this.tableID=m,this.columnID=p,this.dataTypeID=a,this.dataTypeSize=JW,this.dataTypeModifier=n,this.format=sW}};U(z,"Field");var V=z;W.Field=V;var w=class{constructor(B,m){this.length=B,this.fieldCount=m,this.name="rowDescription",this.fields=Array(this.fieldCount)}};U(w,"RowDescriptionMessage");var R=w;W.RowDescriptionMessage=R;var h=class{constructor(B,m){this.length=B,this.parameterCount=m,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}};U(h,"ParameterDescriptionMessage");var _=h;W.ParameterDescriptionMessage=_;var D=class{constructor(B,m,p){this.length=B,this.parameterName=m,this.parameterValue=p,this.name="parameterStatus"}};U(D,"ParameterStatusMessage");var F=D;W.ParameterStatusMessage=F;var M=class{constructor(B,m){this.length=B,this.salt=m,this.name="authenticationMD5Password"}};U(M,"AuthenticationMD5Password");var P=M;W.AuthenticationMD5Password=P;var f=class{constructor(B,m,p){this.length=B,this.processID=m,this.secretKey=p,this.name="backendKeyData"}};U(f,"BackendKeyDataMessage");var T=f;W.BackendKeyDataMessage=T;var S=class{constructor(B,m,p,a){this.length=B,this.processId=m,this.channel=p,this.payload=a,this.name="notification"}};U(S,"NotificationResponseMessage");var q=S;W.NotificationResponseMessage=q;var Q=class{constructor(B,m){this.length=B,this.status=m,this.name="readyForQuery"}};U(Q,"ReadyForQueryMessage");var v=Q;W.ReadyForQueryMessage=v;var j=class{constructor(B,m){this.length=B,this.text=m,this.name="commandComplete"}};U(j,"CommandCompleteMessage");var A=j;W.CommandCompleteMessage=A;var N=class{constructor(B,m){this.length=B,this.fields=m,this.name="dataRow",this.fieldCount=m.length}};U(N,"DataRowMessage");var b=N;W.DataRowMessage=b;var C=class{constructor(B,m){this.length=B,this.message=m,this.name="notice"}};U(C,"NoticeMessage");var u=C;W.NoticeMessage=u}),$2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.Writer=void 0;var $=class{constructor(Z=256){this.size=Z,this.offset=5,this.headerPosition=0,this.buffer=t.allocUnsafe(Z)}ensure(Z){if(this.buffer.length-this.offset<Z){let X=this.buffer,G=X.length+(X.length>>1)+Z;this.buffer=t.allocUnsafe(G),X.copy(this.buffer)}}addInt32(Z){return this.ensure(4),this.buffer[this.offset++]=Z>>>24&255,this.buffer[this.offset++]=Z>>>16&255,this.buffer[this.offset++]=Z>>>8&255,this.buffer[this.offset++]=Z>>>0&255,this}addInt16(Z){return this.ensure(2),this.buffer[this.offset++]=Z>>>8&255,this.buffer[this.offset++]=Z>>>0&255,this}addCString(Z){if(!Z)this.ensure(1);else{let X=t.byteLength(Z);this.ensure(X+1),this.buffer.write(Z,this.offset,"utf-8"),this.offset+=X}return this.buffer[this.offset++]=0,this}addString(Z=""){let X=t.byteLength(Z);return this.ensure(X),this.buffer.write(Z,this.offset),this.offset+=X,this}add(Z){return this.ensure(Z.length),Z.copy(this.buffer,this.offset),this.offset+=Z.length,this}join(Z){if(Z){this.buffer[this.headerPosition]=Z;let X=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(X,this.headerPosition+1)}return this.buffer.slice(Z?0:5,this.offset)}flush(Z){let X=this.join(Z);return this.offset=5,this.headerPosition=0,this.buffer=t.allocUnsafe(this.size),X}};U($,"Writer");var k=$;W.Writer=k}),k2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.serialize=void 0;var $=$2(),k=new $.Writer,J=U((B)=>{k.addInt16(3).addInt16(0);for(let a of Object.keys(B))k.addCString(a).addCString(B[a]);k.addCString("client_encoding").addCString("UTF8");let m=k.addCString("").flush(),p=m.length+4;return new $.Writer().addInt32(p).add(m).flush()},"startup"),Z=U(()=>{let B=t.allocUnsafe(8);return B.writeInt32BE(8,0),B.writeInt32BE(80877103,4),B},"requestSsl"),X=U((B)=>k.addCString(B).flush(112),"password"),G=U(function(B,m){return k.addCString(B).addInt32(t.byteLength(m)).addString(m),k.flush(112)},"sendSASLInitialResponseMessage"),z=U(function(B){return k.addString(B).flush(112)},"sendSCRAMClientFinalMessage"),V=U((B)=>k.addCString(B).flush(81),"query"),w=[],R=U((B)=>{let m=B.name||"";m.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",m,m.length),console.error("This can cause conflicts and silent errors executing queries"));let p=B.types||w,a=p.length,JW=k.addCString(m).addCString(B.text).addInt16(a);for(let n=0;n<a;n++)JW.addInt32(p[n]);return k.flush(80)},"parse"),h=new $.Writer,_=U(function(B,m){for(let p=0;p<B.length;p++){let a=m?m(B[p],p):B[p];a==null?(k.addInt16(0),h.addInt32(-1)):a instanceof t?(k.addInt16(1),h.addInt32(a.length),h.add(a)):(k.addInt16(0),h.addInt32(t.byteLength(a)),h.addString(a))}},"writeValues"),D=U((B={})=>{let m=B.portal||"",p=B.statement||"",a=B.binary||!1,JW=B.values||w,n=JW.length;return k.addCString(m).addCString(p),k.addInt16(n),_(JW,B.valueMapper),k.addInt16(n),k.add(h.flush()),k.addInt16(a?1:0),k.flush(66)},"bind"),F=t.from([69,0,0,0,9,0,0,0,0,0]),M=U((B)=>{if(!B||!B.portal&&!B.rows)return F;let m=B.portal||"",p=B.rows||0,a=t.byteLength(m),JW=4+a+1+4,n=t.allocUnsafe(1+JW);return n[0]=69,n.writeInt32BE(JW,1),n.write(m,5,"utf-8"),n[a+5]=0,n.writeUInt32BE(p,n.length-4),n},"execute"),P=U((B,m)=>{let p=t.allocUnsafe(16);return p.writeInt32BE(16,0),p.writeInt16BE(1234,4),p.writeInt16BE(5678,6),p.writeInt32BE(B,8),p.writeInt32BE(m,12),p},"cancel"),f=U((B,m)=>{let p=4+t.byteLength(m)+1,a=t.allocUnsafe(1+p);return a[0]=B,a.writeInt32BE(p,1),a.write(m,5,"utf-8"),a[p]=0,a},"cstringMessage"),T=k.addCString("P").flush(68),S=k.addCString("S").flush(68),q=U((B)=>B.name?f(68,`${B.type}${B.name||""}`):B.type==="P"?T:S,"describe"),Q=U((B)=>{let m=`${B.type}${B.name||""}`;return f(67,m)},"close"),v=U((B)=>k.add(B).flush(100),"copyData"),j=U((B)=>f(102,B),"copyFail"),A=U((B)=>t.from([B,0,0,0,4]),"codeOnlyBuffer"),N=A(72),b=A(83),C=A(88),u=A(99),c={startup:J,password:X,requestSsl:Z,sendSASLInitialResponseMessage:G,sendSCRAMClientFinalMessage:z,query:V,parse:R,bind:D,execute:M,describe:q,close:Q,flush:U(()=>N,"flush"),sync:U(()=>b,"sync"),end:U(()=>C,"end"),copyData:v,copyDone:U(()=>u,"copyDone"),copyFail:j,cancel:P};W.serialize=c}),J2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.BufferReader=void 0;var $=t.allocUnsafe(0),k=class{constructor(X=0){this.offset=X,this.buffer=$,this.encoding="utf-8"}setBuffer(X,G){this.offset=X,this.buffer=G}int16(){let X=this.buffer.readInt16BE(this.offset);return this.offset+=2,X}byte(){let X=this.buffer[this.offset];return this.offset++,X}int32(){let X=this.buffer.readInt32BE(this.offset);return this.offset+=4,X}uint32(){let X=this.buffer.readUInt32BE(this.offset);return this.offset+=4,X}string(X){let G=this.buffer.toString(this.encoding,this.offset,this.offset+X);return this.offset+=X,G}cstring(){let X=this.offset,G=X;for(;this.buffer[G++]!==0;);return this.offset=G,this.buffer.toString(this.encoding,X,G-1)}bytes(X){let G=this.buffer.slice(this.offset,this.offset+X);return this.offset+=X,G}};U(k,"BufferReader");var J=k;W.BufferReader=J}),Z2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.Parser=void 0;var $=z7(),k=J2(),J=1,Z=4,X=J+Z,G=t.allocUnsafe(0),z=class{constructor(R){if(this.buffer=G,this.bufferLength=0,this.bufferOffset=0,this.reader=new k.BufferReader,R?.mode==="binary")throw Error("Binary mode not supported yet");this.mode=R?.mode||"text"}parse(R,h){this.mergeBuffer(R);let _=this.bufferOffset+this.bufferLength,D=this.bufferOffset;for(;D+X<=_;){let F=this.buffer[D],M=this.buffer.readUInt32BE(D+J),P=J+M;if(P+D<=_){let f=this.handlePacket(D+X,F,M,this.buffer);h(f),D+=P}else break}D===_?(this.buffer=G,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=_-D,this.bufferOffset=D)}mergeBuffer(R){if(this.bufferLength>0){let h=this.bufferLength+R.byteLength;if(h+this.bufferOffset>this.buffer.byteLength){let _;if(h<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)_=this.buffer;else{let D=this.buffer.byteLength*2;for(;h>=D;)D*=2;_=t.allocUnsafe(D)}this.buffer.copy(_,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=_,this.bufferOffset=0}R.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=h}else this.buffer=R,this.bufferOffset=0,this.bufferLength=R.byteLength}handlePacket(R,h,_,D){switch(h){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(R,_,D);case 67:return this.parseCommandCompleteMessage(R,_,D);case 90:return this.parseReadyForQueryMessage(R,_,D);case 65:return this.parseNotificationMessage(R,_,D);case 82:return this.parseAuthenticationResponse(R,_,D);case 83:return this.parseParameterStatusMessage(R,_,D);case 75:return this.parseBackendKeyData(R,_,D);case 69:return this.parseErrorMessage(R,_,D,"error");case 78:return this.parseErrorMessage(R,_,D,"notice");case 84:return this.parseRowDescriptionMessage(R,_,D);case 116:return this.parseParameterDescriptionMessage(R,_,D);case 71:return this.parseCopyInMessage(R,_,D);case 72:return this.parseCopyOutMessage(R,_,D);case 100:return this.parseCopyData(R,_,D);default:return new $.DatabaseError("received invalid response: "+h.toString(16),_,"error")}}parseReadyForQueryMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.string(1);return new $.ReadyForQueryMessage(h,D)}parseCommandCompleteMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.cstring();return new $.CommandCompleteMessage(h,D)}parseCopyData(R,h,_){let D=_.slice(R,R+(h-4));return new $.CopyDataMessage(h,D)}parseCopyInMessage(R,h,_){return this.parseCopyMessage(R,h,_,"copyInResponse")}parseCopyOutMessage(R,h,_){return this.parseCopyMessage(R,h,_,"copyOutResponse")}parseCopyMessage(R,h,_,D){this.reader.setBuffer(R,_);let F=this.reader.byte()!==0,M=this.reader.int16(),P=new $.CopyResponse(h,D,F,M);for(let f=0;f<M;f++)P.columnTypes[f]=this.reader.int16();return P}parseNotificationMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F=this.reader.cstring(),M=this.reader.cstring();return new $.NotificationResponseMessage(h,D,F,M)}parseRowDescriptionMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=new $.RowDescriptionMessage(h,D);for(let M=0;M<D;M++)F.fields[M]=this.parseField();return F}parseField(){let R=this.reader.cstring(),h=this.reader.uint32(),_=this.reader.int16(),D=this.reader.uint32(),F=this.reader.int16(),M=this.reader.int32(),P=this.reader.int16()===0?"text":"binary";return new $.Field(R,h,_,D,F,M,P)}parseParameterDescriptionMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=new $.ParameterDescriptionMessage(h,D);for(let M=0;M<D;M++)F.dataTypeIDs[M]=this.reader.int32();return F}parseDataRowMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=Array(D);for(let M=0;M<D;M++){let P=this.reader.int32();F[M]=P===-1?null:this.reader.string(P)}return new $.DataRowMessage(h,F)}parseParameterStatusMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.cstring(),F=this.reader.cstring();return new $.ParameterStatusMessage(h,D,F)}parseBackendKeyData(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F=this.reader.int32();return new $.BackendKeyDataMessage(h,D,F)}parseAuthenticationResponse(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F={name:"authenticationOk",length:h};switch(D){case 0:break;case 3:F.length===8&&(F.name="authenticationCleartextPassword");break;case 5:if(F.length===12){F.name="authenticationMD5Password";let M=this.reader.bytes(4);return new $.AuthenticationMD5Password(h,M)}break;case 10:{F.name="authenticationSASL",F.mechanisms=[];let M;do M=this.reader.cstring(),M&&F.mechanisms.push(M);while(M)}break;case 11:F.name="authenticationSASLContinue",F.data=this.reader.string(h-8);break;case 12:F.name="authenticationSASLFinal",F.data=this.reader.string(h-8);break;default:throw Error("Unknown authenticationOk message type "+D)}return F}parseErrorMessage(R,h,_,D){this.reader.setBuffer(R,_);let F={},M=this.reader.string(1);for(;M!=="\x00";)F[M]=this.reader.cstring(),M=this.reader.string(1);let P=F.M,f=D==="notice"?new $.NoticeMessage(h,P):new $.DatabaseError(P,h,D);return f.severity=F.S,f.code=F.C,f.detail=F.D,f.hint=F.H,f.position=F.P,f.internalPosition=F.p,f.internalQuery=F.q,f.where=F.W,f.schema=F.s,f.table=F.t,f.column=F.c,f.dataType=F.d,f.constraint=F.n,f.file=F.F,f.line=F.L,f.routine=F.R,f}};U(z,"Parser");var V=z;W.Parser=V}),G7=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.DatabaseError=W.serialize=W.parse=void 0;var $=z7();Object.defineProperty(W,"DatabaseError",{enumerable:!0,get:U(function(){return $.DatabaseError},"get")});var k=k2();Object.defineProperty(W,"serialize",{enumerable:!0,get:U(function(){return k.serialize},"get")});var J=Z2();function Z(X,G){let z=new J.Parser;return X.on("data",(V)=>z.parse(V,G)),new Promise((V)=>X.on("end",()=>V()))}U(Z,"parse"),W.parse=Z}),M7={};_1(M7,{connect:()=>L7});function L7({socket:W,servername:$}){return W.startTls($),W}var X2=tW(()=>{l(),U(L7,"connect")}),K7=r((W,$)=>{l();var k=(Q8(),QW(c5)),J=F0().EventEmitter,{parse:Z,serialize:X}=G7(),G=X.flush(),z=X.sync(),V=X.end(),w=class extends J{constructor(_){super(),_=_||{},this.stream=_.stream||new k.Socket,this._keepAlive=_.keepAlive,this._keepAliveInitialDelayMillis=_.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=_.ssl||!1,this._ending=!1,this._emitMessage=!1;var D=this;this.on("newListener",function(F){F==="message"&&(D._emitMessage=!0)})}connect(_,D){var F=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(_,D),this.stream.once("connect",function(){F._keepAlive&&F.stream.setKeepAlive(!0,F._keepAliveInitialDelayMillis),F.emit("connect")});let M=U(function(P){F._ending&&(P.code==="ECONNRESET"||P.code==="EPIPE")||F.emit("error",P)},"reportStreamError");if(this.stream.on("error",M),this.stream.on("close",function(){F.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(P){var f=P.toString("utf8");switch(f){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 T=(X2(),QW(M7));let S={socket:F.stream};F.ssl!==!0&&(Object.assign(S,F.ssl),("key"in F.ssl)&&(S.key=F.ssl.key)),k.isIP(D)===0&&(S.servername=D);try{F.stream=T.connect(S)}catch(q){return F.emit("error",q)}F.attachListeners(F.stream),F.stream.on("error",M),F.emit("sslconnect")})}attachListeners(_){_.on("end",()=>{this.emit("end")}),Z(_,(D)=>{var F=D.name==="error"?"errorMessage":D.name;this._emitMessage&&this.emit("message",D),this.emit(F,D)})}requestSsl(){this.stream.write(X.requestSsl())}startup(_){this.stream.write(X.startup(_))}cancel(_,D){this._send(X.cancel(_,D))}password(_){this._send(X.password(_))}sendSASLInitialResponseMessage(_,D){this._send(X.sendSASLInitialResponseMessage(_,D))}sendSCRAMClientFinalMessage(_){this._send(X.sendSCRAMClientFinalMessage(_))}_send(_){return this.stream.writable?this.stream.write(_):!1}query(_){this._send(X.query(_))}parse(_){this._send(X.parse(_))}bind(_){this._send(X.bind(_))}execute(_){this._send(X.execute(_))}flush(){this.stream.writable&&this.stream.write(G)}sync(){this._ending=!0,this._send(G),this._send(z)}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(_){this._send(X.close(_))}describe(_){this._send(X.describe(_))}sendCopyFromChunk(_){this._send(X.copyData(_))}endCopyFrom(){this._send(X.copyDone())}sendCopyFail(_){this._send(X.copyFail(_))}};U(w,"Connection");var R=w;$.exports=R}),Y2=r((W,$)=>{l();var k=F0().EventEmitter,J=(E4(),QW(x8)),Z=v4(),X=tk(),G=nk(),z=a6(),V=e6(),w=W2(),R=T4(),h=K7(),_=class extends k{constructor(M){super(),this.connectionParameters=new V(M),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 P=M||{};this._Promise=P.Promise||D4.Promise,this._types=new z(P.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=P.connection||new h({stream:P.stream,ssl:this.connectionParameters.ssl,keepAlive:P.keepAlive||!1,keepAliveInitialDelayMillis:P.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=P.binary||R.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=P.connectionTimeoutMillis||0}_errorAllQueries(M){let P=U((f)=>{o.nextTick(()=>{f.handleError(M,this.connection)})},"enqueueError");this.activeQuery&&(P(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(P),this.queryQueue.length=0}_connect(M){var P=this,f=this.connection;if(this._connectionCallback=M,this._connecting||this._connected){let T=Error("Client has already been connected. You cannot reuse a client.");o.nextTick(()=>{M(T)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{f._ending=!0,f.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?f.connect(this.host+"/.s.PGSQL."+this.port):f.connect(this.port,this.host),f.on("connect",function(){P.ssl?f.requestSsl():f.startup(P.getStartupConf())}),f.on("sslconnect",function(){f.startup(P.getStartupConf())}),this._attachListeners(f),f.once("end",()=>{let T=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(T),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(T):this._handleErrorEvent(T):this._connectionError||this._handleErrorEvent(T)),o.nextTick(()=>{this.emit("end")})})}connect(M){if(M){this._connect(M);return}return new this._Promise((P,f)=>{this._connect((T)=>{T?f(T):P()})})}_attachListeners(M){M.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),M.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),M.on("authenticationSASL",this._handleAuthSASL.bind(this)),M.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),M.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),M.on("backendKeyData",this._handleBackendKeyData.bind(this)),M.on("error",this._handleErrorEvent.bind(this)),M.on("errorMessage",this._handleErrorMessage.bind(this)),M.on("readyForQuery",this._handleReadyForQuery.bind(this)),M.on("notice",this._handleNotice.bind(this)),M.on("rowDescription",this._handleRowDescription.bind(this)),M.on("dataRow",this._handleDataRow.bind(this)),M.on("portalSuspended",this._handlePortalSuspended.bind(this)),M.on("emptyQuery",this._handleEmptyQuery.bind(this)),M.on("commandComplete",this._handleCommandComplete.bind(this)),M.on("parseComplete",this._handleParseComplete.bind(this)),M.on("copyInResponse",this._handleCopyInResponse.bind(this)),M.on("copyData",this._handleCopyData.bind(this)),M.on("notification",this._handleNotification.bind(this))}_checkPgPass(M){let P=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then((f)=>{if(f!==void 0){if(typeof f!="string"){P.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=f}else this.connectionParameters.password=this.password=null;M()}).catch((f)=>{P.emit("error",f)}):this.password!==null?M():G(this.connectionParameters,(f)=>{f!==void 0&&(this.connectionParameters.password=this.password=f),M()})}_handleAuthCleartextPassword(M){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(M){this._checkPgPass(()=>{let P=Z.postgresMd5PasswordHash(this.user,this.password,M.salt);this.connection.password(P)})}_handleAuthSASL(M){this._checkPgPass(()=>{this.saslSession=X.startSession(M.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(M){X.continueSession(this.saslSession,this.password,M.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}_handleAuthSASLFinal(M){X.finalizeSession(this.saslSession,M.data),this.saslSession=null}_handleBackendKeyData(M){this.processID=M.processID,this.secretKey=M.secretKey}_handleReadyForQuery(M){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:P}=this;this.activeQuery=null,this.readyForQuery=!0,P&&P.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(M){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(M);this.emit("error",M)}}_handleErrorEvent(M){if(this._connecting)return this._handleErrorWhileConnecting(M);this._queryable=!1,this._errorAllQueries(M),this.emit("error",M)}_handleErrorMessage(M){if(this._connecting)return this._handleErrorWhileConnecting(M);let P=this.activeQuery;if(!P){this._handleErrorEvent(M);return}this.activeQuery=null,P.handleError(M,this.connection)}_handleRowDescription(M){this.activeQuery.handleRowDescription(M)}_handleDataRow(M){this.activeQuery.handleDataRow(M)}_handlePortalSuspended(M){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(M){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(M){this.activeQuery.handleCommandComplete(M,this.connection)}_handleParseComplete(M){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(M){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(M){this.activeQuery.handleCopyData(M,this.connection)}_handleNotification(M){this.emit("notification",M)}_handleNotice(M){this.emit("notice",M)}getStartupConf(){var M=this.connectionParameters,P={user:M.user,database:M.database},f=M.application_name||M.fallback_application_name;return f&&(P.application_name=f),M.replication&&(P.replication=""+M.replication),M.statement_timeout&&(P.statement_timeout=String(parseInt(M.statement_timeout,10))),M.lock_timeout&&(P.lock_timeout=String(parseInt(M.lock_timeout,10))),M.idle_in_transaction_session_timeout&&(P.idle_in_transaction_session_timeout=String(parseInt(M.idle_in_transaction_session_timeout,10))),M.options&&(P.options=M.options),P}cancel(M,P){if(M.activeQuery===P){var f=this.connection;this.host&&this.host.indexOf("/")===0?f.connect(this.host+"/.s.PGSQL."+this.port):f.connect(this.port,this.host),f.on("connect",function(){f.cancel(M.processID,M.secretKey)})}else M.queryQueue.indexOf(P)!==-1&&M.queryQueue.splice(M.queryQueue.indexOf(P),1)}setTypeParser(M,P,f){return this._types.setTypeParser(M,P,f)}getTypeParser(M,P){return this._types.getTypeParser(M,P)}escapeIdentifier(M){return'"'+M.replace(/"/g,'""')+'"'}escapeLiteral(M){for(var P=!1,f="'",T=0;T<M.length;T++){var S=M[T];S==="'"?f+=S+S:S==="\\"?(f+=S+S,P=!0):f+=S}return f+="'",P===!0&&(f=" E"+f),f}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let M=this.activeQuery.submit(this.connection);M&&o.nextTick(()=>{this.activeQuery.handleError(M,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(M,P,f){var T,S,q,Q,v;if(M==null)throw TypeError("Client was passed a null or undefined query");return typeof M.submit=="function"?(q=M.query_timeout||this.connectionParameters.query_timeout,S=T=M,typeof P=="function"&&(T.callback=T.callback||P)):(q=this.connectionParameters.query_timeout,T=new w(M,P,f),T.callback||(S=new this._Promise((j,A)=>{T.callback=(N,b)=>N?A(N):j(b)}))),q&&(v=T.callback,Q=setTimeout(()=>{var j=Error("Query read timeout");o.nextTick(()=>{T.handleError(j,this.connection)}),v(j),T.callback=()=>{};var A=this.queryQueue.indexOf(T);A>-1&&this.queryQueue.splice(A,1),this._pulseQueryQueue()},q),T.callback=(j,A)=>{clearTimeout(Q),v(j,A)}),this.binary&&!T.binary&&(T.binary=!0),T._result&&!T._result._types&&(T._result._types=this._types),this._queryable?this._ending?(o.nextTick(()=>{T.handleError(Error("Client was closed and is not queryable"),this.connection)}),S):(this.queryQueue.push(T),this._pulseQueryQueue(),S):(o.nextTick(()=>{T.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),S)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(M){if(this._ending=!0,!this.connection._connecting)if(M)M();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),M)this.connection.once("end",M);else return new this._Promise((P)=>{this.connection.once("end",P)})}};U(_,"Client");var D=_;D.Query=w,$.exports=D}),H2=r((W,$)=>{l();var k=F0().EventEmitter,J=U(function(){},"NOOP"),Z=U((F,M)=>{let P=F.findIndex(M);return P===-1?void 0:F.splice(P,1)[0]},"removeWhere"),X=class{constructor(M,P,f){this.client=M,this.idleListener=P,this.timeoutId=f}};U(X,"IdleItem");var G=X,z=class{constructor(M){this.callback=M}};U(z,"PendingItem");var V=z;function w(){throw Error("Release called on client which has already been released to the pool.")}U(w,"throwOnDoubleRelease");function R(F,M){if(M)return{callback:M,result:void 0};let P,f,T=U(function(q,Q){q?P(q):f(Q)},"cb"),S=new F(function(q,Q){f=q,P=Q}).catch((q)=>{throw Error.captureStackTrace(q),q});return{callback:T,result:S}}U(R,"promisify");function h(F,M){return U(function P(f){f.client=M,M.removeListener("error",P),M.on("error",()=>{F.log("additional client error after disconnection due to error",f)}),F._remove(M),F.emit("error",f,M)},"idleListener")}U(h,"makeIdleListener");var _=class extends k{constructor(M,P){super(),this.options=Object.assign({},M),M!=null&&"password"in M&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:M.password}),M!=null&&M.ssl&&M.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||P||S4().Client,this.Promise=this.options.Promise||D4.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((P)=>{this._remove(P.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 M=this._pendingQueue.shift();if(this._idle.length){let P=this._idle.pop();clearTimeout(P.timeoutId);let f=P.client;f.ref&&f.ref();let T=P.idleListener;return this._acquireClient(f,M,T,!1)}if(!this._isFull())return this.newClient(M);throw Error("unexpected condition")}_remove(M){let P=Z(this._idle,(f)=>f.client===M);P!==void 0&&clearTimeout(P.timeoutId),this._clients=this._clients.filter((f)=>f!==M),M.end(),this.emit("remove",M)}connect(M){if(this.ending){let T=Error("Cannot use a pool after calling end on the pool");return M?M(T):this.Promise.reject(T)}let P=R(this.Promise,M),f=P.result;if(this._isFull()||this._idle.length){if(this._idle.length&&o.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new V(P.callback)),f;let T=U((Q,v,j)=>{clearTimeout(q),P.callback(Q,v,j)},"queueCallback"),S=new V(T),q=setTimeout(()=>{Z(this._pendingQueue,(Q)=>Q.callback===T),S.timedOut=!0,P.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return q.unref&&q.unref(),this._pendingQueue.push(S),f}return this.newClient(new V(P.callback)),f}newClient(M){let P=new this.Client(this.options);this._clients.push(P);let f=h(this,P);this.log("checking client timeout");let T,S=!1;this.options.connectionTimeoutMillis&&(T=setTimeout(()=>{this.log("ending client due to timeout"),S=!0,P.connection?P.connection.stream.destroy():P.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),P.connect((q)=>{if(T&&clearTimeout(T),P.on("error",f),q)this.log("client failed to connect",q),this._clients=this._clients.filter((Q)=>Q!==P),S&&(q=Error("Connection terminated due to connection timeout",{cause:q})),this._pulseQueue(),M.timedOut||M.callback(q,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(P),this._idle.findIndex((v)=>v.client===P)!==-1&&this._acquireClient(P,new V((v,j,A)=>A()),f,!1)},this.options.maxLifetimeSeconds*1000);Q.unref(),P.once("end",()=>clearTimeout(Q))}return this._acquireClient(P,M,f,!0)}})}_acquireClient(M,P,f,T){T&&this.emit("connect",M),this.emit("acquire",M),M.release=this._releaseOnce(M,f),M.removeListener("error",f),P.timedOut?T&&this.options.verify?this.options.verify(M,M.release):M.release():T&&this.options.verify?this.options.verify(M,(S)=>{if(S)return M.release(S),P.callback(S,void 0,J);P.callback(void 0,M,M.release)}):P.callback(void 0,M,M.release)}_releaseOnce(M,P){let f=!1;return(T)=>{f&&w(),f=!0,this._release(M,P,T)}}_release(M,P,f){if(M.on("error",P),M._poolUseCount=(M._poolUseCount||0)+1,this.emit("release",f,M),f||this.ending||!M._queryable||M._ending||M._poolUseCount>=this.options.maxUses){M._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(M),this._pulseQueue();return}if(this._expired.has(M)){this.log("remove expired client"),this._expired.delete(M),this._remove(M),this._pulseQueue();return}let T;this.options.idleTimeoutMillis&&this._isAboveMin()&&(T=setTimeout(()=>{this.log("remove idle client"),this._remove(M)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&T.unref()),this.options.allowExitOnIdle&&M.unref(),this._idle.push(new G(M,P,T)),this._pulseQueue()}query(M,P,f){if(typeof M=="function"){let S=R(this.Promise,M);return t6(function(){return S.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),S.result}typeof P=="function"&&(f=P,P=void 0);let T=R(this.Promise,f);return f=T.callback,this.connect((S,q)=>{if(S)return f(S);let Q=!1,v=U((j)=>{Q||(Q=!0,q.release(j),f(j))},"onError");q.once("error",v),this.log("dispatching query");try{q.query(M,P,(j,A)=>{if(this.log("query dispatched"),q.removeListener("error",v),!Q)return Q=!0,q.release(j),j?f(j):f(void 0,A)})}catch(j){return q.release(j),f(j)}}),T.result}end(M){if(this.log("ending"),this.ending){let f=Error("Called end on pool more than once");return M?M(f):this.Promise.reject(f)}this.ending=!0;let P=R(this.Promise,M);return this._endCallback=P.callback,this._pulseQueue(),P.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((M,P)=>M+(this._expired.has(P)?1:0),0)}get totalCount(){return this._clients.length}};U(_,"Pool");var D=_;$.exports=D}),U7={};_1(U7,{default:()=>V7});var V7,z2=tW(()=>{l(),V7={}}),G2=r((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"}}),M2=r((W,$)=>{l();var k=F0().EventEmitter,J=(E4(),QW(x8)),Z=v4(),X=$.exports=function(z,V,w){k.call(this),z=Z.normalizeQueryConfig(z,V,w),this.text=z.text,this.values=z.values,this.name=z.name,this.callback=z.callback,this.state="new",this._arrayMode=z.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(R){R==="row"&&(this._emitRowEvents=!0)}.bind(this))};J.inherits(X,k);var G={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};X.prototype.handleError=function(z){var V=this.native.pq.resultErrorFields();if(V)for(var w in V){var R=G[w]||w;z[R]=V[w]}this.callback?this.callback(z):this.emit("error",z),this.state="error"},X.prototype.then=function(z,V){return this._getPromise().then(z,V)},X.prototype.catch=function(z){return this._getPromise().catch(z)},X.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(z,V){this._once("end",z),this._once("error",V)}.bind(this)),this._promise)},X.prototype.submit=function(z){this.state="running";var V=this;this.native=z.native,z.native.arrayMode=this._arrayMode;var w=U(function(_,D,F){if(z.native.arrayMode=!1,t6(function(){V.emit("_done")}),_)return V.handleError(_);V._emitRowEvents&&(F.length>1?D.forEach((M,P)=>{M.forEach((f)=>{V.emit("row",f,F[P])})}):D.forEach(function(M){V.emit("row",M,F)})),V.state="end",V.emit("end",F),V.callback&&V.callback(null,F)},"after");if(o.domain&&(w=o.domain.bind(w)),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 R=(this.values||[]).map(Z.prepareValue);if(z.namedQueries[this.name]){if(this.text&&z.namedQueries[this.name]!==this.text){let _=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return w(_)}return z.native.execute(this.name,R,w)}return z.native.prepare(this.name,this.text,R.length,function(_){return _?w(_):(z.namedQueries[V.name]=V.text,V.native.execute(V.name,R,w))})}else if(this.values){if(!Array.isArray(this.values)){let _=Error("Query values must be an array");return w(_)}var h=this.values.map(Z.prepareValue);z.native.query(this.text,h,w)}else z.native.query(this.text,w)}}),L2=r((W,$)=>{l();var k=(z2(),QW(U7)),J=a6(),Z=G2(),X=F0().EventEmitter,G=(E4(),QW(x8)),z=e6(),V=M2(),w=$.exports=function(R){X.call(this),R=R||{},this._Promise=R.Promise||D4.Promise,this._types=new J(R.types),this.native=new k({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var h=this.connectionParameters=new z(R);this.user=h.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:h.password}),this.database=h.database,this.host=h.host,this.port=h.port,this.namedQueries={}};w.Query=V,G.inherits(w,X),w.prototype._errorAllQueries=function(R){let h=U((_)=>{o.nextTick(()=>{_.native=this.native,_.handleError(R)})},"enqueueError");this._hasActiveQuery()&&(h(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(h),this._queryQueue.length=0},w.prototype._connect=function(R){var h=this;if(this._connecting){o.nextTick(()=>R(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(_,D){if(_)return R(_);h.native.connect(D,function(F){if(F)return h.native.end(),R(F);h._connected=!0,h.native.on("error",function(M){h._queryable=!1,h._errorAllQueries(M),h.emit("error",M)}),h.native.on("notification",function(M){h.emit("notification",{channel:M.relname,payload:M.extra})}),h.emit("connect"),h._pulseQueryQueue(!0),R()})})},w.prototype.connect=function(R){if(R){this._connect(R);return}return new this._Promise((h,_)=>{this._connect((D)=>{D?_(D):h()})})},w.prototype.query=function(R,h,_){var D,F,M,P,f;if(R==null)throw TypeError("Client was passed a null or undefined query");if(typeof R.submit=="function")M=R.query_timeout||this.connectionParameters.query_timeout,F=D=R,typeof h=="function"&&(R.callback=h);else if(M=this.connectionParameters.query_timeout,D=new V(R,h,_),!D.callback){let T,S;F=new this._Promise((q,Q)=>{T=q,S=Q}),D.callback=(q,Q)=>q?S(q):T(Q)}return M&&(f=D.callback,P=setTimeout(()=>{var T=Error("Query read timeout");o.nextTick(()=>{D.handleError(T,this.connection)}),f(T),D.callback=()=>{};var S=this._queryQueue.indexOf(D);S>-1&&this._queryQueue.splice(S,1),this._pulseQueryQueue()},M),D.callback=(T,S)=>{clearTimeout(P),f(T,S)}),this._queryable?this._ending?(D.native=this.native,o.nextTick(()=>{D.handleError(Error("Client was closed and is not queryable"))}),F):(this._queryQueue.push(D),this._pulseQueryQueue(),F):(D.native=this.native,o.nextTick(()=>{D.handleError(Error("Client has encountered a connection error and is not queryable"))}),F)},w.prototype.end=function(R){var h=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,R));var _;return R||(_=new this._Promise(function(D,F){R=U((M)=>M?F(M):D(),"cb")})),this.native.end(function(){h._errorAllQueries(Error("Connection terminated")),o.nextTick(()=>{h.emit("end"),R&&R()})}),_},w.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},w.prototype._pulseQueryQueue=function(R){if(this._connected&&!this._hasActiveQuery()){var h=this._queryQueue.shift();if(!h){R||this.emit("drain");return}this._activeQuery=h,h.submit(this);var _=this;h.once("_done",function(){_._pulseQueryQueue()})}},w.prototype.cancel=function(R){this._activeQuery===R?this.native.cancel(function(){}):this._queryQueue.indexOf(R)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(R),1)},w.prototype.ref=function(){},w.prototype.unref=function(){},w.prototype.setTypeParser=function(R,h,_){return this._types.setTypeParser(R,h,_)},w.prototype.getTypeParser=function(R,h){return this._types.getTypeParser(R,h)}}),b5=r((W,$)=>{l(),$.exports=L2()}),S4=r((W,$)=>{l();var k=Y2(),J=T4(),Z=K7(),X=H2(),{DatabaseError:G}=G7(),z=U((w)=>{var R;return R=class extends X{constructor(h){super(h,w)}},U(R,"BoundPool"),R},"poolFactory"),V=U(function(w){this.defaults=J,this.Client=w,this.Query=this.Client.Query,this.Pool=z(this.Client),this._pools=[],this.Connection=Z,this.types=f4(),this.DatabaseError=G},"PG");typeof o.env.NODE_PG_FORCE_NATIVE<"u"?$.exports=new V(b5()):($.exports=new V(k),Object.defineProperty($.exports,"native",{configurable:!0,enumerable:!1,get(){var w=null;try{w=new V(b5())}catch(R){if(R.code!=="MODULE_NOT_FOUND")throw R}return Object.defineProperty($.exports,"native",{value:w}),w}}))});l();l();Q8();i5();l();var{defineProperty:K2,defineProperties:U2,getOwnPropertyDescriptors:V2,getOwnPropertySymbols:B5}=Object,R2=Object.prototype.hasOwnProperty,F2=Object.prototype.propertyIsEnumerable,I5=U((W,$,k)=>($ in W)?K2(W,$,{enumerable:!0,configurable:!0,writable:!0,value:k}):W[$]=k,"__defNormalProp"),w2=U((W,$)=>{for(var k in $||($={}))R2.call($,k)&&I5(W,k,$[k]);if(B5)for(var k of B5($))F2.call($,k)&&I5(W,k,$[k]);return W},"__spreadValues"),_2=U((W,$)=>U2(W,V2($)),"__spreadProps"),h2=1008000,y5=new Uint8Array(new Uint16Array([258]).buffer)[0]===2,P2=new TextDecoder,W9=new TextEncoder,w4=W9.encode("0123456789abcdef"),_4=W9.encode("0123456789ABCDEF"),D2=W9.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),R7=D2.slice();R7[62]=45;R7[63]=95;var j8,h4;function F7(W,{alphabet:$,scratchArr:k}={}){if(!j8)if(j8=new Uint16Array(256),h4=new Uint16Array(256),y5)for(let D=0;D<256;D++)j8[D]=w4[D&15]<<8|w4[D>>>4],h4[D]=_4[D&15]<<8|_4[D>>>4];else for(let D=0;D<256;D++)j8[D]=w4[D&15]|w4[D>>>4]<<8,h4[D]=_4[D&15]|_4[D>>>4]<<8;W.byteOffset%4!==0&&(W=new Uint8Array(W));let J=W.length,Z=J>>>1,X=J>>>2,G=k||new Uint16Array(J),z=new Uint32Array(W.buffer,W.byteOffset,X),V=new Uint32Array(G.buffer,G.byteOffset,Z),w=$==="upper"?h4:j8,R=0,h=0,_;if(y5)for(;R<X;)_=z[R++],V[h++]=w[_>>>8&255]<<16|w[_&255],V[h++]=w[_>>>24]<<16|w[_>>>16&255];else for(;R<X;)_=z[R++],V[h++]=w[_>>>24]<<16|w[_>>>16&255],V[h++]=w[_>>>8&255]<<16|w[_&255];for(R<<=2;R<J;)G[R]=w[W[R++]];return P2.decode(G.subarray(0,J))}U(F7,"_toHex");function w7(W,$={}){let k="",J=W.length,Z=h2>>>1,X=Math.ceil(J/Z),G=new Uint16Array(X>1?Z:J);for(let z=0;z<X;z++){let V=z*Z,w=V+Z;k+=F7(W.subarray(V,w),_2(w2({},$),{scratchArr:G}))}return k}U(w7,"_toHexChunked");function _7(W,$={}){return $.alphabet!=="upper"&&typeof W.toHex=="function"?W.toHex():w7(W,$)}U(_7,"toHex");l();var h7=class W{constructor($,k){this.strings=$,this.values=k}toParameterizedQuery($={query:"",params:[]}){let{strings:k,values:J}=this;for(let Z=0,X=k.length;Z<X;Z++)if($.query+=k[Z],Z<J.length){let G=J[Z];if(G instanceof f7)$.query+=G.sql;else if(G instanceof P4)if(G.queryData instanceof W)G.queryData.toParameterizedQuery($);else{if(G.queryData.params?.length)throw Error("This query is not composable");$.query+=G.queryData.query}else{let{params:z}=$;z.push(G),$.query+="$"+z.length,(G instanceof t||ArrayBuffer.isView(G))&&($.query+="::bytea")}}return $}};U(h7,"SqlTemplate");var P7=h7,D7=class{constructor($){this.sql=$}};U(D7,"UnsafeRawSql");var f7=D7;l();function $9(){typeof window<"u"&&typeof document<"u"&&typeof console<"u"&&typeof console.warn=="function"&&console.warn(`
28
29
  ************************************************************
29
30
  * *
@@ -39,7 +40,7 @@ Expecting one of '${k.join("', '")}'`);let J=`${W}Help`;return this.on(J,(Z)=>{l
39
40
  * using the disableWarningInBrowsers configuration *
40
41
  * parameter. *
41
42
  * *
42
- ************************************************************`)}U($9,"warnIfBrowser");Q8();var f2=R0(a6()),T2=R0(v4()),T7=class W extends Error{constructor($){super($);s(this,"name","NeonDbError"),s(this,"severity"),s(this,"code"),s(this,"detail"),s(this,"hint"),s(this,"position"),s(this,"internalPosition"),s(this,"internalQuery"),s(this,"where"),s(this,"schema"),s(this,"table"),s(this,"column"),s(this,"dataType"),s(this,"constraint"),s(this,"file"),s(this,"line"),s(this,"routine"),s(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};U(T7,"NeonDbError");var a0=T7,g5="transaction() expects an array of queries, or a function returning an array of queries",v2=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function v7(W){return W instanceof t?"\\x"+_7(W):W}U(v7,"encodeBuffersAsBytea");function i6(W){let{query:$,params:k}=W instanceof P7?W.toParameterizedQuery():W;return{query:$,params:k.map((J)=>v7((0,T2.prepareValue)(J)))}}U(i6,"prepareQuery");function N4(W,{arrayMode:$,fullResults:k,fetchOptions:J,isolationLevel:Z,readOnly:X,deferrable:G,authToken:z,disableWarningInBrowsers:V}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let w;try{w=s6(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:R,username:h,hostname:_,port:D,pathname:F}=w;if(R!=="postgres:"&&R!=="postgresql:"||!h||!_||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function M(f,...T){if(!(Array.isArray(f)&&Array.isArray(f.raw)&&Array.isArray(T)))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 P4(P,new P7(f,T))}U(M,"templateFn"),M.query=(f,T,S)=>new P4(P,{query:f,params:T??[]},S),M.unsafe=(f)=>new f7(f),M.transaction=async(f,T)=>{if(typeof f=="function"&&(f=f(M)),!Array.isArray(f))throw Error(g5);f.forEach((Q)=>{if(!(Q instanceof P4))throw Error(g5)});let S=f.map((Q)=>Q.queryData),q=f.map((Q)=>Q.opts??{});return P(S,q,T)};async function P(f,T,S){let{fetchEndpoint:q,fetchFunction:Q}=V0,v=Array.isArray(f)?{queries:f.map((JW)=>i6(JW))}:i6(f),j=J??{},A=$??!1,N=k??!1,b=Z,C=X,u=G;S!==void 0&&(S.fetchOptions!==void 0&&(j={...j,...S.fetchOptions}),S.arrayMode!==void 0&&(A=S.arrayMode),S.fullResults!==void 0&&(N=S.fullResults),S.isolationLevel!==void 0&&(b=S.isolationLevel),S.readOnly!==void 0&&(C=S.readOnly),S.deferrable!==void 0&&(u=S.deferrable)),T!==void 0&&!Array.isArray(T)&&T.fetchOptions!==void 0&&(j={...j,...T.fetchOptions});let c=z;!Array.isArray(T)&&T?.authToken!==void 0&&(c=T.authToken);let B=typeof q=="function"?q(_,D,{jwtAuth:c!==void 0}):q,m={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await S7(c);p&&(m.Authorization=`Bearer ${p}`),Array.isArray(f)&&(b!==void 0&&(m["Neon-Batch-Isolation-Level"]=b),C!==void 0&&(m["Neon-Batch-Read-Only"]=String(C)),u!==void 0&&(m["Neon-Batch-Deferrable"]=String(u))),V||V0.disableWarningInBrowsers||$9();let a;try{a=await(Q??fetch)(B,{method:"POST",body:JSON.stringify(v),headers:m,...j})}catch(JW){let n=new a0(`Error connecting to database: ${JW}`);throw n.sourceError=JW,n}if(a.ok){let JW=await a.json();if(Array.isArray(f)){let n=JW.results;if(!Array.isArray(n))throw new a0("Neon internal error: unexpected result format");return n.map((sW,RW)=>{let SW=T[RW]??{},r0=SW.arrayMode??A,e0=SW.fullResults??N;return p6(sW,{arrayMode:r0,fullResults:e0,types:SW.types})})}else{let n=T??{},sW=n.arrayMode??A,RW=n.fullResults??N;return p6(JW,{arrayMode:sW,fullResults:RW,types:n.types})}}else{let{status:JW}=a;if(JW===400){let n=await a.json(),sW=new a0(n.message);for(let RW of v2)sW[RW]=n[RW]??void 0;throw sW}else{let n=await a.text();throw new a0(`Server error (HTTP status ${JW}): ${n}`)}}}return U(P,"execute"),M}U(N4,"neon");var E7=class{constructor($,k,J){this.execute=$,this.queryData=k,this.opts=J}then($,k){return this.execute(this.queryData,this.opts).then($,k)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};U(E7,"NeonQueryPromise");var P4=E7;function p6(W,{arrayMode:$,fullResults:k,types:J}){let Z=new f2.default(J),X=W.fields.map((V)=>V.name),G=W.fields.map((V)=>Z.getTypeParser(V.dataTypeID)),z=$===!0?W.rows.map((V)=>V.map((w,R)=>w===null?null:G[R](w))):W.rows.map((V)=>Object.fromEntries(V.map((w,R)=>[X[R],w===null?null:G[R](w)])));return k?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=z,W._parsers=G,W._types=Z,W):z}U(p6,"processQueryResult");async function S7(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let k=new a0("Error getting auth token.");throw $ instanceof Error&&(k=new a0(`Error getting auth token: ${$.message}`)),k}}U(S7,"getAuthToken");l();var E2=R0(S4());l();var S2=R0(S4()),N7=class extends S2.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:k}=this;k.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&k.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||o.env.PGHOST!==void 0,Z=o.env.USER??o.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===Z&&this.database===Z&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${Z}, db: ${Z}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let X=super.connect($),G=k.pipelineTLS&&this.ssl,z=k.pipelineConnect==="password";if(!G&&!k.pipelineConnect)return X;let V=this.connection;if(G&&V.on("connect",()=>V.stream.emit("data","S")),z){V.removeAllListeners("authenticationCleartextPassword"),V.removeAllListeners("readyForQuery"),V.once("readyForQuery",()=>V.on("readyForQuery",this._handleReadyForQuery.bind(this)));let w=this.ssl?"sslconnect":"connect";V.on(w,()=>{this.neonConfig.disableWarningInBrowsers||$9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return X}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 k=crypto.subtle,J=this.saslSession,Z=this.password,X=$.data;if(J.message!=="SASLInitialResponse"||typeof Z!="string"||typeof X!="string")throw Error("SASL: protocol error");let G=Object.fromEntries(X.split(",").map((JW)=>{if(!/^.=/.test(JW))throw Error("SASL: Invalid attribute pair entry");let n=JW[0],sW=JW.substring(2);return[n,sW]})),z=G.r,V=G.s,w=G.i;if(!z||!/^[!-+--~]+$/.test(z))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(!w||!/^[1-9][0-9]*$/.test(w))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!z.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(z.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let R=parseInt(w,10),h=t.from(V,"base64"),_=new TextEncoder,D=_.encode(Z),F=await k.importKey("raw",D,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),M=new Uint8Array(await k.sign("HMAC",F,t.concat([h,t.from([0,0,0,1])]))),P=M;for(var f=0;f<R-1;f++)M=new Uint8Array(await k.sign("HMAC",F,M)),P=t.from(P.map((JW,n)=>P[n]^M[n]));let T=P,S=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),q=new Uint8Array(await k.sign("HMAC",S,_.encode("Client Key"))),Q=await k.digest("SHA-256",q),v="n=*,r="+J.clientNonce,j="r="+z+",s="+V+",i="+R,A="c=biws,r="+z,N=v+","+j+","+A,b=await k.importKey("raw",Q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await k.sign("HMAC",b,_.encode(N))),u=t.from(q.map((JW,n)=>q[n]^C[n])),c=u.toString("base64");let B=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),m=await k.sign("HMAC",B,_.encode("Server Key")),p=await k.importKey("raw",m,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var a=t.from(await k.sign("HMAC",p,_.encode(N)));J.message="SASLResponse",J.serverSignature=a.toString("base64"),J.response=A+",p="+c,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};U(N7,"NeonClient");var N2=N7;Q8();var O2=R0(e6());function O7(W,$){if($)return{callback:$,result:void 0};let k,J,Z=U(function(G,z){G?k(G):J(z)},"cb"),X=new W(function(G,z){J=G,k=z});return{callback:Z,result:X}}U(O7,"promisify");var A7=class extends E2.Pool{constructor(){super(...arguments);s(this,"Client",N2),s(this,"hasFetchUnsupportedListeners",!1),s(this,"addListener",this.on)}on($,k){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,k)}query($,k,J){if(!V0.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,k,J);typeof k=="function"&&(J=k,k=void 0);let Z=O7(this.Promise,J);J=Z.callback;try{let X=new O2.default(this.options),G=encodeURIComponent,z=encodeURI,V=`postgresql://${G(X.user)}:${G(X.password)}@${G(X.host)}/${z(X.database)}`,w=typeof $=="string"?$:$.text,R=k??$.values??[];N4(V,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(w,R,{types:$.types??this.options?.types}).then((h)=>J(void 0,h)).catch((h)=>J(h))}catch(X){J(X)}return Z.result}};U(A7,"NeonPool");var j7=A7;Q8();var q8=R0(S4());var{DatabaseError:i_,defaults:p_,escapeIdentifier:t_,escapeLiteral:s_,types:a_}=q8;/*! Bundled license information:
43
+ ************************************************************`)}U($9,"warnIfBrowser");Q8();var f2=R0(a6()),T2=R0(v4()),T7=class W extends Error{constructor($){super($);s(this,"name","NeonDbError"),s(this,"severity"),s(this,"code"),s(this,"detail"),s(this,"hint"),s(this,"position"),s(this,"internalPosition"),s(this,"internalQuery"),s(this,"where"),s(this,"schema"),s(this,"table"),s(this,"column"),s(this,"dataType"),s(this,"constraint"),s(this,"file"),s(this,"line"),s(this,"routine"),s(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};U(T7,"NeonDbError");var a0=T7,g5="transaction() expects an array of queries, or a function returning an array of queries",v2=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function v7(W){return W instanceof t?"\\x"+_7(W):W}U(v7,"encodeBuffersAsBytea");function i6(W){let{query:$,params:k}=W instanceof P7?W.toParameterizedQuery():W;return{query:$,params:k.map((J)=>v7((0,T2.prepareValue)(J)))}}U(i6,"prepareQuery");function N4(W,{arrayMode:$,fullResults:k,fetchOptions:J,isolationLevel:Z,readOnly:X,deferrable:G,authToken:z,disableWarningInBrowsers:V}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let w;try{w=s6(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:R,username:h,hostname:_,port:D,pathname:F}=w;if(R!=="postgres:"&&R!=="postgresql:"||!h||!_||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function M(f,...T){if(!(Array.isArray(f)&&Array.isArray(f.raw)&&Array.isArray(T)))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 P4(P,new P7(f,T))}U(M,"templateFn"),M.query=(f,T,S)=>new P4(P,{query:f,params:T??[]},S),M.unsafe=(f)=>new f7(f),M.transaction=async(f,T)=>{if(typeof f=="function"&&(f=f(M)),!Array.isArray(f))throw Error(g5);f.forEach((Q)=>{if(!(Q instanceof P4))throw Error(g5)});let S=f.map((Q)=>Q.queryData),q=f.map((Q)=>Q.opts??{});return P(S,q,T)};async function P(f,T,S){let{fetchEndpoint:q,fetchFunction:Q}=V0,v=Array.isArray(f)?{queries:f.map((JW)=>i6(JW))}:i6(f),j=J??{},A=$??!1,N=k??!1,b=Z,C=X,u=G;S!==void 0&&(S.fetchOptions!==void 0&&(j={...j,...S.fetchOptions}),S.arrayMode!==void 0&&(A=S.arrayMode),S.fullResults!==void 0&&(N=S.fullResults),S.isolationLevel!==void 0&&(b=S.isolationLevel),S.readOnly!==void 0&&(C=S.readOnly),S.deferrable!==void 0&&(u=S.deferrable)),T!==void 0&&!Array.isArray(T)&&T.fetchOptions!==void 0&&(j={...j,...T.fetchOptions});let c=z;!Array.isArray(T)&&T?.authToken!==void 0&&(c=T.authToken);let B=typeof q=="function"?q(_,D,{jwtAuth:c!==void 0}):q,m={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await S7(c);p&&(m.Authorization=`Bearer ${p}`),Array.isArray(f)&&(b!==void 0&&(m["Neon-Batch-Isolation-Level"]=b),C!==void 0&&(m["Neon-Batch-Read-Only"]=String(C)),u!==void 0&&(m["Neon-Batch-Deferrable"]=String(u))),V||V0.disableWarningInBrowsers||$9();let a;try{a=await(Q??fetch)(B,{method:"POST",body:JSON.stringify(v),headers:m,...j})}catch(JW){let n=new a0(`Error connecting to database: ${JW}`);throw n.sourceError=JW,n}if(a.ok){let JW=await a.json();if(Array.isArray(f)){let n=JW.results;if(!Array.isArray(n))throw new a0("Neon internal error: unexpected result format");return n.map((sW,RW)=>{let SW=T[RW]??{},r0=SW.arrayMode??A,e0=SW.fullResults??N;return p6(sW,{arrayMode:r0,fullResults:e0,types:SW.types})})}else{let n=T??{},sW=n.arrayMode??A,RW=n.fullResults??N;return p6(JW,{arrayMode:sW,fullResults:RW,types:n.types})}}else{let{status:JW}=a;if(JW===400){let n=await a.json(),sW=new a0(n.message);for(let RW of v2)sW[RW]=n[RW]??void 0;throw sW}else{let n=await a.text();throw new a0(`Server error (HTTP status ${JW}): ${n}`)}}}return U(P,"execute"),M}U(N4,"neon");var E7=class{constructor($,k,J){this.execute=$,this.queryData=k,this.opts=J}then($,k){return this.execute(this.queryData,this.opts).then($,k)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};U(E7,"NeonQueryPromise");var P4=E7;function p6(W,{arrayMode:$,fullResults:k,types:J}){let Z=new f2.default(J),X=W.fields.map((V)=>V.name),G=W.fields.map((V)=>Z.getTypeParser(V.dataTypeID)),z=$===!0?W.rows.map((V)=>V.map((w,R)=>w===null?null:G[R](w))):W.rows.map((V)=>Object.fromEntries(V.map((w,R)=>[X[R],w===null?null:G[R](w)])));return k?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=z,W._parsers=G,W._types=Z,W):z}U(p6,"processQueryResult");async function S7(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let k=new a0("Error getting auth token.");throw $ instanceof Error&&(k=new a0(`Error getting auth token: ${$.message}`)),k}}U(S7,"getAuthToken");l();var E2=R0(S4());l();var S2=R0(S4()),N7=class extends S2.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:k}=this;k.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&k.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||o.env.PGHOST!==void 0,Z=o.env.USER??o.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===Z&&this.database===Z&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${Z}, db: ${Z}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let X=super.connect($),G=k.pipelineTLS&&this.ssl,z=k.pipelineConnect==="password";if(!G&&!k.pipelineConnect)return X;let V=this.connection;if(G&&V.on("connect",()=>V.stream.emit("data","S")),z){V.removeAllListeners("authenticationCleartextPassword"),V.removeAllListeners("readyForQuery"),V.once("readyForQuery",()=>V.on("readyForQuery",this._handleReadyForQuery.bind(this)));let w=this.ssl?"sslconnect":"connect";V.on(w,()=>{this.neonConfig.disableWarningInBrowsers||$9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return X}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 k=crypto.subtle,J=this.saslSession,Z=this.password,X=$.data;if(J.message!=="SASLInitialResponse"||typeof Z!="string"||typeof X!="string")throw Error("SASL: protocol error");let G=Object.fromEntries(X.split(",").map((JW)=>{if(!/^.=/.test(JW))throw Error("SASL: Invalid attribute pair entry");let n=JW[0],sW=JW.substring(2);return[n,sW]})),z=G.r,V=G.s,w=G.i;if(!z||!/^[!-+--~]+$/.test(z))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(!w||!/^[1-9][0-9]*$/.test(w))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!z.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(z.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let R=parseInt(w,10),h=t.from(V,"base64"),_=new TextEncoder,D=_.encode(Z),F=await k.importKey("raw",D,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),M=new Uint8Array(await k.sign("HMAC",F,t.concat([h,t.from([0,0,0,1])]))),P=M;for(var f=0;f<R-1;f++)M=new Uint8Array(await k.sign("HMAC",F,M)),P=t.from(P.map((JW,n)=>P[n]^M[n]));let T=P,S=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),q=new Uint8Array(await k.sign("HMAC",S,_.encode("Client Key"))),Q=await k.digest("SHA-256",q),v="n=*,r="+J.clientNonce,j="r="+z+",s="+V+",i="+R,A="c=biws,r="+z,N=v+","+j+","+A,b=await k.importKey("raw",Q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await k.sign("HMAC",b,_.encode(N))),u=t.from(q.map((JW,n)=>q[n]^C[n])),c=u.toString("base64");let B=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),m=await k.sign("HMAC",B,_.encode("Server Key")),p=await k.importKey("raw",m,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var a=t.from(await k.sign("HMAC",p,_.encode(N)));J.message="SASLResponse",J.serverSignature=a.toString("base64"),J.response=A+",p="+c,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};U(N7,"NeonClient");var N2=N7;Q8();var O2=R0(e6());function O7(W,$){if($)return{callback:$,result:void 0};let k,J,Z=U(function(G,z){G?k(G):J(z)},"cb"),X=new W(function(G,z){J=G,k=z});return{callback:Z,result:X}}U(O7,"promisify");var A7=class extends E2.Pool{constructor(){super(...arguments);s(this,"Client",N2),s(this,"hasFetchUnsupportedListeners",!1),s(this,"addListener",this.on)}on($,k){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,k)}query($,k,J){if(!V0.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,k,J);typeof k=="function"&&(J=k,k=void 0);let Z=O7(this.Promise,J);J=Z.callback;try{let X=new O2.default(this.options),G=encodeURIComponent,z=encodeURI,V=`postgresql://${G(X.user)}:${G(X.password)}@${G(X.host)}/${z(X.database)}`,w=typeof $=="string"?$:$.text,R=k??$.values??[];N4(V,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(w,R,{types:$.types??this.options?.types}).then((h)=>J(void 0,h)).catch((h)=>J(h))}catch(X){J(X)}return Z.result}};U(A7,"NeonPool");var j7=A7;Q8();var q8=R0(S4());var{DatabaseError:l_,defaults:i_,escapeIdentifier:p_,escapeLiteral:t_,types:s_}=q8;/*! Bundled license information:
43
44
 
44
45
  ieee754/index.js:
45
46
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@@ -51,4 +52,4 @@ buffer/index.js:
51
52
  * @author Feross Aboukhadijeh <https://feross.org>
52
53
  * @license MIT
53
54
  *)
54
- */var C7=Symbol("release"),Q7=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 k=BigInt($.rowCount);return{numUpdatedOrDeletedRows:k,numAffectedRows:k,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[C7](){this.#W.release?.()}},x7=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new A2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},A2=class{#W;#$=new WeakMap;#k;constructor(W){this.#W=W}async init(){Object.assign(V0,this.#W),this.#k=new j7(this.#W)}async acquireConnection(){let W=await this.#k.connect(),$=this.#$.get(W);if(!$)$=new Q7(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(E8.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(E8.raw("begin"))}async commitTransaction(W){await W.executeQuery(E8.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(E8.raw("rollback"))}async releaseConnection(W){W[C7]()}async destroy(){if(this.#k){let W=this.#k;this.#k=void 0,await W.end()}}},kh=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new j2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},j2=class{#W;#$;constructor(W){this.#W=W,this.#$=new Q7({query:N4(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 O4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function C2({pg_host:W,environment:$,...k}){let J=k.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let Z;if($==="production")Z=W;else if($==="development")if(W.includes("localhost"))Z="localhost";else Z="postgres-ws-proxy";else if($==="test"||$==="staging")Z="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(O4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let V=`${Z}${$!=="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 q7=C2;function Q2(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 b7=Q2;function x2(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var J0=x2;function q2(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var B7=q2;function b2(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((w)=>typeof w!=="string"&&typeof w<"u"&&typeof w!=="number"&&typeof w!=="boolean")){let w=new Set(Object.values(W).map((R)=>typeof R));throw w.delete("undefined"),w.delete("string"),w.delete("number"),w.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(w).join(", ")}`)}let k=J0(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!k){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: "${k}"`);let J=J0(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 Z=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)Z=Number.parseInt(J0(W.POSTGRES_PORT)??"NaN");if(typeof Z!=="number"||isNaN(Z))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let X=J0(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!X)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let G=J0(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!G)throw Error("POSTGRES_USER is not defined in environment variables!");let z=J0(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!z)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let V="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)V=J0(W.POSTGRES_URL)??"";else V=B7({POSTGRES_DATABASE:X,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_USER:G,POSTGRES_PASSWORD:z});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:G,POSTGRES_PASSWORD:z,POSTGRES_URL:V,POSTGRES_URL_NON_POOLING:k,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_DATABASE:X}}var A4=b2;function B2(W,$=!1){return A4(W,$)}var I7=B2;class n0{kysely_db;env;debug;static getPostgresNeonWsProxyUrl(W){return q7(W)}static parsePort(W){let $=typeof W.POSTGRES_PORT==="number"?W.POSTGRES_PORT:Number.parseInt(W.POSTGRES_PORT);if(isNaN($))throw Error(`Invalid port number: ${W.POSTGRES_PORT}`);return $}constructor({environment:W,...$}){if(!O4(W))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W;let k=b7(this.env);this.debug=k;let J=void 0;if($.credentials){if(typeof $.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");J=A4($.credentials,this.debug)}else J=I7(process.env,this.debug);if(!J)throw Error("Failed to parse database credentials from options or environment variables!");let Z={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:n0.parsePort(J),wsProxy:(z)=>{if(k)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}")`);let V;try{let w={pg_host:z,environment:W,debug:this.debug};if(typeof $.wsProxyUrl>"u"||!$.wsProxyUrl)V=n0.getPostgresNeonWsProxyUrl(w);else if(typeof $.wsProxyUrl==="string"&&$.wsProxyUrl&&$.wsProxyUrl.length>0)V=$.wsProxyUrl;else if(typeof $.wsProxyUrl==="function"&&$.wsProxyUrl){let R=$.wsProxyUrl;V=R(w)}else throw Error(`Invalid wsProxy url for host: "${z}". Not a string, undefined, or function!`)}catch(w){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => Failure: `,w),Error(`Failed to calculate wsProxy url for host: "${z}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => `,V);return V}};if(this.debug)Z.pipelineTLS=!1,Z.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",Z);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initializing SchemaVaults x Kysely x Neon database adapter...");let G={dialect:new x7(Z),log:["query","error"]};if(this.kysely_db=new g1(G),this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}get db(){return this.kysely_db}async destroy(){await this.kysely_db.destroy();return}}import I2 from"fs/promises";import y2 from"path";import{existsSync as y7}from"fs";function g7({db:W,migrationFolder:$}){return new g6({db:W,provider:new m6({fs:I2,path:y2,migrationFolder:$})})}function g2(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 m7(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)g2($);return!0}async function c7({db:W,migrationFolder:$,...k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!y7($))throw Error(`migrationFolder '${$}' does not exist`);let J=g7({db:W,migrationFolder:$}),Z;if(typeof k.version==="string")Z=await J.migrateTo(k.version);else Z=await J.migrateToLatest();let{error:X,results:G}=Z;if(X)throw console.error(X),X;if(!G)return[];if(!m7(G))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return G}async function u7({db:W,migrationFolder:$,version:k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!y7($))throw Error(`migrationFolder '${$}' does not exist`);let J=g7({db:W,migrationFolder:$}),{error:Z,results:X}=await J.migrateTo(k);if(Z)throw console.error(Z),Z;if(!X)return[];if(!m7(X))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return X}var i2=c2(import.meta.url),{version:l7}=i2("../package.json");if(typeof l7!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var o0=new E9;o0.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(l7);o0.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").action(async(W,$,k)=>{let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await c7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to run.")}catch(X){console.error("Migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.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").action(async(W,$,k)=>{let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await u7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to reverse.")}catch(X){console.error("Reverse migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.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{u2("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 k=j4.dirname(m2(import.meta.url)),Z=["run",j4.resolve(k,"build-db-migrations.js"),W];if(Z.push("--outdir",$.outdir),Z.push("--sql-module",$.sqlModule),$.sqlOutdir)Z.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)Z.push("--external",...$.external);if($.debug)Z.push("--debug");l2("bun",Z,{stdio:"inherit",cwd:process.cwd()}).on("close",(G)=>{process.exit(G??1)})});var uh=o0,p2=process.argv[1]&&import.meta.url===`file://${process.argv[1]}`;if(p2)o0.parse();export{uh as default};
55
+ */var C7=Symbol("release"),Q7=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 k=BigInt($.rowCount);return{numUpdatedOrDeletedRows:k,numAffectedRows:k,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[C7](){this.#W.release?.()}},x7=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new A2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},A2=class{#W;#$=new WeakMap;#k;constructor(W){this.#W=W}async init(){Object.assign(V0,this.#W),this.#k=new j7(this.#W)}async acquireConnection(){let W=await this.#k.connect(),$=this.#$.get(W);if(!$)$=new Q7(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(E8.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(E8.raw("begin"))}async commitTransaction(W){await W.executeQuery(E8.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(E8.raw("rollback"))}async releaseConnection(W){W[C7]()}async destroy(){if(this.#k){let W=this.#k;this.#k=void 0,await W.end()}}},$h=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new j2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},j2=class{#W;#$;constructor(W){this.#W=W,this.#$=new Q7({query:N4(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 O4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function C2({pg_host:W,environment:$,...k}){let J=k.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let Z;if($==="production")Z=W;else if($==="development")if(W.includes("localhost"))Z="localhost";else Z="postgres-ws-proxy";else if($==="test"||$==="staging")Z="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(O4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let V=`${Z}${$!=="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 q7=C2;function Q2(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 b7=Q2;function x2(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var J0=x2;function q2(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var B7=q2;function b2(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((w)=>typeof w!=="string"&&typeof w<"u"&&typeof w!=="number"&&typeof w!=="boolean")){let w=new Set(Object.values(W).map((R)=>typeof R));throw w.delete("undefined"),w.delete("string"),w.delete("number"),w.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(w).join(", ")}`)}let k=J0(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!k){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: "${k}"`);let J=J0(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 Z=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)Z=Number.parseInt(J0(W.POSTGRES_PORT)??"NaN");if(typeof Z!=="number"||isNaN(Z))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let X=J0(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!X)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let G=J0(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!G)throw Error("POSTGRES_USER is not defined in environment variables!");let z=J0(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!z)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let V="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)V=J0(W.POSTGRES_URL)??"";else V=B7({POSTGRES_DATABASE:X,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_USER:G,POSTGRES_PASSWORD:z});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:G,POSTGRES_PASSWORD:z,POSTGRES_URL:V,POSTGRES_URL_NON_POOLING:k,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_DATABASE:X}}var A4=b2;function B2(W,$=!1){return A4(W,$)}var I7=B2;class n0{kysely_db;env;debug;static getPostgresNeonWsProxyUrl(W){return q7(W)}static parsePort(W){let $=typeof W.POSTGRES_PORT==="number"?W.POSTGRES_PORT:Number.parseInt(W.POSTGRES_PORT);if(isNaN($))throw Error(`Invalid port number: ${W.POSTGRES_PORT}`);return $}constructor({environment:W,...$}){if(!O4(W))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W;let k=b7(this.env);this.debug=k;let J=void 0;if($.credentials){if(typeof $.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");J=A4($.credentials,this.debug)}else J=I7(process.env,this.debug);if(!J)throw Error("Failed to parse database credentials from options or environment variables!");let Z={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:n0.parsePort(J),wsProxy:(z)=>{if(k)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}")`);let V;try{let w={pg_host:z,environment:W,debug:this.debug};if(typeof $.wsProxyUrl>"u"||!$.wsProxyUrl)V=n0.getPostgresNeonWsProxyUrl(w);else if(typeof $.wsProxyUrl==="string"&&$.wsProxyUrl&&$.wsProxyUrl.length>0)V=$.wsProxyUrl;else if(typeof $.wsProxyUrl==="function"&&$.wsProxyUrl){let R=$.wsProxyUrl;V=R(w)}else throw Error(`Invalid wsProxy url for host: "${z}". Not a string, undefined, or function!`)}catch(w){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => Failure: `,w),Error(`Failed to calculate wsProxy url for host: "${z}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => `,V);return V}};if(this.debug)Z.pipelineTLS=!1,Z.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",Z);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initializing SchemaVaults x Kysely x Neon database adapter...");let G={dialect:new x7(Z),log:["query","error"]};if(this.kysely_db=new g1(G),this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}get db(){return this.kysely_db}async destroy(){await this.kysely_db.destroy();return}}import I2 from"fs/promises";import y2 from"path";import{existsSync as y7}from"fs";function g7({db:W,migrationFolder:$}){return new g6({db:W,provider:new m6({fs:I2,path:y2,migrationFolder:$})})}function g2(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 m7(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)g2($);return!0}async function c7({db:W,migrationFolder:$,...k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!y7($))throw Error(`migrationFolder '${$}' does not exist`);let J=g7({db:W,migrationFolder:$}),Z;if(typeof k.version==="string")Z=await J.migrateTo(k.version);else Z=await J.migrateToLatest();let{error:X,results:G}=Z;if(X)throw console.error(X),X;if(!G)return[];if(!m7(G))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return G}async function u7({db:W,migrationFolder:$,version:k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!y7($))throw Error(`migrationFolder '${$}' does not exist`);let J=g7({db:W,migrationFolder:$}),{error:Z,results:X}=await J.migrateTo(k);if(Z)throw console.error(Z),Z;if(!X)return[];if(!m7(X))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return X}var i2=c2(import.meta.url),{version:l7}=i2("../package.json");if(typeof l7!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var o0=new E9;o0.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(l7);o0.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").action(async(W,$,k)=>{let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await c7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to run.")}catch(X){console.error("Migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.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").action(async(W,$,k)=>{let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await u7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to reverse.")}catch(X){console.error("Reverse migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.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{u2("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 k=j4.dirname(m2(import.meta.url)),Z=["run",j4.resolve(k,"build-db-migrations.js"),W];if(Z.push("--outdir",$.outdir),Z.push("--sql-module",$.sqlModule),$.sqlOutdir)Z.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)Z.push("--external",...$.external);if($.debug)Z.push("--debug");l2("bun",Z,{stdio:"inherit",cwd:process.cwd()}).on("close",(G)=>{process.exit(G??1)})});var ch=o0;o0.parse();export{ch as default};